text stringlengths 14 6.51M |
|---|
{-----------------------------------------------------------------------------
Unit Name: SLForms
Author: n0mad
Version: 1.2.8.x
Creation: 06.08.2003
Purpose: Forms with position and dimensions autosave
History:
-----------------------------------------------------------------------------}
unit SLForms;
{$I kinode01.inc}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
FrmRstr, ActnList
{$IFNDEF No_XP_Menu}
, XPMenu
{$ENDIF}
;
type
{$IFNDEF No_XP_Menu}
TXPMenu_Wrap = class(TXPMenu)
end;
{$ELSE}
TXPMenu_Wrap = class(TAction)
end;
{$ENDIF}
TSLForm = class(TForm)
SLFormRestorer: TFrmRstr;
SLActionList: TActionList;
SLFullScreen: TAction;
SLXPMenu: TXPMenu_Wrap;
procedure SLFullScreenExecute(Sender: TObject);
private
_WindowState: TWindowState;
FFullScreen: Boolean;
function GetFullScreen: Boolean;
procedure SetFullScreen(const Value: Boolean);
protected
procedure Activate; override;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property FullScreen: Boolean read GetFullScreen write SetFullScreen default false;
end;
implementation
{$R *.DFM}
const
UnitName: string = 'SLForms';
procedure TSLForm.SLFullScreenExecute(Sender: TObject);
begin
FullScreen := not FullScreen;
SLFullScreen.Checked := FullScreen;
end;
function TSLForm.GetFullScreen: Boolean;
begin
FFullScreen := (Self.WindowState = wsMaximized) and (Self.BorderStyle =
bsNone);
Result := FFullScreen;
end;
procedure TSLForm.SetFullScreen(const Value: Boolean);
var
MousePoint: TPoint;
begin
// -----------------------------------------------------------------------------
if FFullScreen <> Value then
begin
FFullScreen := Value;
GetCursorPos(MousePoint);
MousePoint := ScreenToClient(MousePoint);
if FFullScreen then
begin
// -----------------------------------------------------------------------------
_WindowState := WindowState;
if WindowState = wsMaximized then
WindowState := wsNormal;
BorderStyle := bsNone;
WindowState := wsMaximized;
// -----------------------------------------------------------------------------
end
else
begin
// -----------------------------------------------------------------------------
WindowState := wsNormal;
BorderStyle := bsSizeable;
WindowState := _WindowState;
// -----------------------------------------------------------------------------
end;
MousePoint := ClientToScreen(MousePoint);
SetCursorPos(MousePoint.X, MousePoint.Y);
end;
// -----------------------------------------------------------------------------
end;
procedure TSLForm.Activate;
begin
inherited;
{$IFNDEF No_XP_Menu}
if SLXPMenu.Tag = 0 then
begin
SLXPMenu.Tag := 1;
SLXPMenu.Active := false;
SLXPMenu.Active := true;
end;
{$ENDIF}
end;
constructor TSLForm.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
if Assigned(SLFormRestorer) and (SLFormRestorer is TFrmRstr) then
SLFormRestorer.RegKey := 'Software\Home(R)\KinoDe\1.2.8';
{$IFNDEF No_XP_Menu}
SLXPMenu := TXPMenu_Wrap.Create(Self);
SLXPMenu.Active := false;
{$ENDIF}
end;
destructor TSLForm.Destroy;
begin
{$IFNDEF No_XP_Menu}
try
SLXPMenu.Active := false;
finally
SLXPMenu.Destroy;
end;
{$ENDIF}
inherited;
end;
end.
|
{
* Type=1001 酷Q启动
* 无论本应用是否被启用,本函数都会在酷Q启动后执行一次,请在这里执行应用初始化代码。
* 如非必要,不建议在这里加载窗口。(可以添加菜单,让用户手动打开窗口)
}
Function code_eventStartup:longint;
Begin
exit(0)
End;
{
* Type=1002 酷Q退出
* 无论本应用是否被启用,本函数都会在酷Q退出前执行一次,请在这里执行插件关闭代码。
* 本函数调用完毕后,酷Q将很快关闭,请不要再通过线程等方式执行其他代码。
}
Function code_eventExit:longint;
Begin
exit(0);
End;
{
* Type=1003 应用已被启用
* 当应用被启用后,将收到此事件。
* 如果酷Q载入时应用已被启用,则在_eventStartup(Type=1001,酷Q启动)被调用后,本函数也将被调用一次。
* 如非必要,不建议在这里加载窗口。(可以添加菜单,让用户手动打开窗口)
}
Function code_eventEnable:longint;
Begin
exit(0)
End;
{
* Type=1004 应用将被停用
* 当应用被停用前,将收到此事件。
* 如果酷Q载入时应用已被停用,则本函数*不会*被调用。
* 无论本应用是否被启用,酷Q关闭前本函数都*不会*被调用。
}
Function code_eventDisable:longint;
Begin
exit(0);
End;
{
* Type=21 私聊消息
* subType 子类型,11/来自好友 1/来自在线状态 2/来自群 3/来自讨论组
}
Function code_eventPrivateMsg(
subType,sendTime :longint;
fromQQ :int64;
const msg :ansistring;
font :longint):longint;
Begin
exit(EVENT_IGNORE);
//如果要回复消息,请调用酷Q方法发送,并且这里 exit(EVENT_BLOCK) - 截断本条消息,不再继续处理 注意:应用优先级设置为"最高"(10000)时,不得使用本返回值
//如果不回复消息,交由之后的应用/过滤器处理,这里 exit(return EVENT_IGNORE) - 忽略本条消息
End;
{
* Type=2 群消息
}
Function code_eventGroupMsg(
subType,sendTime :longint;
fromgroup,fromQQ :int64;
const fromAnonymous,msg :ansistring;
font :longint):longint;
Var
AnonymousMes : CQ_Type_GroupAnonymous;
Begin
if (fromQQ=80000000) and (fromAnonymous<>'') then begin
CQ_Tools_TextToAnonymous(fromAnonymous,AnonymousMes);
//将匿名用户信息存到 AnonymousMes
end;
if msg='签到' then CQ_sendGroupMsg(AuthCode,fromgroup,
sTop(CQCode_Group_At(fromQQ)+' : 签到并没有成功[CQ:image,file=funnyface.png]')
);
exit(EVENT_IGNORE);
//关于返回值说明, 见“code_eventPrivateMsg”函数
End;
{
* Type=4 讨论组消息
}
Function code_eventDiscussMsg(
subType,sendTime :longint;
fromDiscuss,fromQQ :int64;
msg :ansistring;
font :longint):longint;
Begin
exit(EVENT_IGNORE);
//关于返回值说明, 见“code_eventPrivateMsg”函数
End;
{
* Type=101 群事件-管理员变动
* subType 子类型,1/被取消管理员 2/被设置管理员
}
Function code_eventSystem_GroupAdmin(
subType,sendTime :longint;
fromGroup,
beingOperateQQ :int64):longint;
Begin
exit(EVENT_IGNORE);
//关于返回值说明, 见“code_eventPrivateMsg”函数
End;
{
* Type=102 群事件-群成员减少
* subType 子类型,1/群员离开 2/群员被踢 3/自己(即登录号)被踢
* fromQQ 操作者QQ(仅subType为2、3时存在)
* beingOperateQQ 被操作QQ
}
Function code_eventSystem_GroupMemberDecrease(
subType,sendTime :longint;
fromGroup,fromQQ,
beingOperateQQ :int64):longint;
stdcall;
Begin
exit(EVENT_IGNORE);
//关于返回值说明, 见“code_eventPrivateMsg”函数
End;
{
* Type=103 群事件-群成员增加
* subType 子类型,1/管理员已同意 2/管理员邀请
* fromQQ 操作者QQ(即管理员QQ)
* beingOperateQQ 被操作QQ(即加群的QQ)
}
Function code_eventSystem_GroupMemberIncrease(
subType,sendTime :longint;
fromGroup,fromQQ,
beingOperateQQ :int64):longint;
stdcall;
Begin
CQ_sendGroupMsg(AuthCode,fromgroup,StoP('欢迎新人 [CQ:at,qq='+NumToChar(beingOperateQQ)+'] 加入本群'));
exit(EVENT_IGNORE);
//关于返回值说明, 见“code_eventPrivateMsg”函数
End;
{
* Type=201 好友事件-好友已添加
}
Function code_eventFriend_Add(
subType,sendTime :longint;
fromQQ :int64):longint;
stdcall;
Begin
exit(EVENT_IGNORE);
//关于返回值说明, 见“code_eventPrivateMsg”函数
End;
{
* Type=301 请求-好友添加
* msg 附言
* responseFlag
反馈标识(处理请求用)
这个我就不帮你转换成string了,反正你拿来也没什么用
}
Function code_eventRequest_AddFriend(
subType,sendTime :longint;
fromQQ :int64;
const msg :ansistring;
responseFlag :Pchar):longint;
stdcall;
Begin
CQ_setFriendAddRequest(AuthCode, responseFlag, REQUEST_DENY,'');
exit(EVENT_IGNORE);
//关于返回值说明, 见“code_eventPrivateMsg”函数
End;
{
* Type=302 请求-群添加
* subType 子类型,1/他人申请入群 2/自己(即登录号)受邀入群
* msg 附言
* responseFlag
反馈标识(处理请求用)
这个我也不帮你转换了
}
Function code_eventRequest_AddGroup(
subType,sendTime :longint;
fromGroup,fromQQ :int64;
msg :ansistring;
responseFlag :Pchar):longint;
stdcall;
Begin
if fromGroup<>311954860 then CQ_setGroupAddRequestV2(AuthCode,responseflag,subType,REQUEST_ALLOW,'');
exit(EVENT_IGNORE);
//关于返回值说明, 见“code_eventPrivateMsg”函数
End; |
unit GameUnit; // implements the IGame interface
interface
uses BowlingInt;
type
TGame = class(TInterfacedObject, IGame)
private
FLine: TBowlLine;
function GetScoreByFrame: TBowlLine;
public
procedure Start;
procedure Roll(ARoll: integer);
property ScoreByFrame: TBowlLine read GetScoreByFrame;
function TotalScore: integer;
constructor Create;
destructor Destroy; override;
end;
implementation
uses
Generics.Collections,
SysUtils,
BowlError,
BowlFrameUnit,
Forms;
{ TGame }
constructor TGame.Create;
begin
inherited;
FLine := TBowlLine.Create;
end;
destructor TGame.Destroy;
begin
if assigned(FLine) then
FLine.Free;
inherited;
end;
function TGame.GetScoreByFrame: TBowlLine;
begin
Result := FLine;
end;
procedure TGame.Roll(ARoll: integer);
var
Current: IBowlFrame;
Status: TBowlFrameType;
begin
if (FLine.Count = 0) then begin
Current := TBowlFrame.Create; // use new frame and put into the line
FLine.Add(Current);
end else begin
Current := FLine[FLine.Count - 1];
Status := Current.BowlFrameType(FLine.Count);
if (FLine.Count = 10) and (Status <> frameIncomplete) then begin // last frame with completed status can't be added to
raise EBowlException.Create('Trying to add a frame to a line that already has 10 frames.'); //checked
end else begin // Set Current to the proper frame
if (Status <> frameIncomplete) then begin
Current := TBowlFrame.Create; // use new frame and put into the line
FLine[FLine.Count - 1].LinkNextFrame(Current);
FLine.Add(Current);
end;
end;
end;
Current.AddRoll(ARoll);
end;
procedure TGame.Start;
begin
FLine.Clear;
end;
function TGame.TotalScore: integer;
var
i: integer;
begin
Result := 0;
for i := 0 to (FLine.Count - 1) do
Result := Result + FLine[i].CurrentScore(i + 1);
end;
end.
|
unit MediaProcessing.Processor.VA.Any.Impl;
interface
uses SysUtils,Windows,Classes, SyncObjs, Generics.Collections, MediaProcessing.Definitions,MediaProcessing.Global,
MediaProcessing.Processor.VA.Any,MediaProcessing.VideoAnalytics,MediaProcessing.VideoAnalytics.Definitions;
type
TMediaProcessor_VA_Any_Impl= class (TMediaProcessor_VA_Any,IMediaProcessorImpl,IMediaProcessorImpl2)
private
FVideoAnalytics: TVideoAnalytics;
FVideoAnalyticsFailure: string;
FCurrentResult: TList<TVaProcessingResult>;
FCurrentResultLock: TCriticalSection;
FCache: TObjectList<TBytesStream>;
procedure OnVideoAnalyticsFrameProcessed(Sender: TVideoAnalytics);
function IsAllowedBySchedule: boolean;
protected
procedure LoadCustomProperties(const aReader: IPropertiesReader); override;
procedure Process(aInData: pointer; aInDataSize:cardinal; const aInFormat: TMediaStreamDataHeader; aInfo: pointer; aInfoSize: cardinal;
out aOutData: pointer; out aOutDataSize: cardinal; out aOutFormat: TMediaStreamDataHeader; out aOutInfo: pointer; out aOutInfoSize: cardinal); override;
procedure ProcessData2(aInData: pointer; aInDataSize:cardinal; const aInFormat: TMediaStreamDataHeader; aInfo: pointer; aInfoSize: cardinal;
out aOutData: pointer; out aOutDataSize: cardinal; out aOutFormat: TMediaStreamDataHeader; out aOutInfo: pointer; out aOutInfoSize: cardinal;
aAuxResults: TMediaProcessorResultList);
public
constructor Create; override;
destructor Destroy; override;
procedure Prepare; override;
end;
implementation
uses uBaseClasses,uTrace;
{ TMediaProcessor_VA_Any_Impl }
constructor TMediaProcessor_VA_Any_Impl.Create;
begin
inherited;
try
FVideoAnalytics := TVideoAnalytics.Create;
FVideoAnalytics.OnFrameProcessed:=OnVideoAnalyticsFrameProcessed;
except
on E:Exception do
begin
TraceLine(Format('Îøèáêà: ',[E.Message]));
FVideoAnalyticsFailure:=E.Message;
FreeAndNil(FVideoAnalytics);
end;
end;
FCache:=TObjectList<TBytesStream>.Create;
FCurrentResultLock:=TCriticalSection.Create;
FCurrentResult:=TList<TVaProcessingResult>.Create;
//FVideoAnalytics.OnTrace := OnVideoAnalyticsTrace;
//FVideoAnalytics.OnFrameProcessed := OnVideoAnalyticsFrameProcessed;
end;
destructor TMediaProcessor_VA_Any_Impl.Destroy;
begin
inherited;
FreeAndNil(FVideoAnalytics);
FreeAndNil(FCurrentResult);
FreeAndNil(FCurrentResultLock);
FreeAndNil(FCache);
end;
function TMediaProcessor_VA_Any_Impl.IsAllowedBySchedule: boolean;
var
i: Integer;
aNowTime: TTime;
begin
if not FConfig_ScheduleEnabled then
exit(true);
result:=false;
aNowTime:=Frac(Now);
for i := 0 to High(FConfig_Schedule) do
begin
if (aNowTime>=FConfig_Schedule[i].From) and (aNowTime<=FConfig_Schedule[i].To_) then
begin
result:=true;
break;
end;
end;
end;
procedure TMediaProcessor_VA_Any_Impl.LoadCustomProperties(const aReader: IPropertiesReader);
var
aParameters: TVaParameters;
begin
inherited;
if FConfig_VaConfigFileName <> '' then
FVideoAnalytics.LoadConfig(FConfig_VaConfigFileName);
if FConfig_VaModelFileName <> '' then
FVideoAnalytics.LoadModel(FConfig_VaModelFileName);
aParameters:=FVideoAnalytics.Parameters;
aParameters.OtEnabled:=FConfig_VaOtEnabled;
aParameters.AsyncProcessing:=FConfig_VaAsyncProcessing;
aParameters.OtFilters:=FConfig_VaFilters;
aParameters.OtEngine:=FConfig_VaOtEngine;
aParameters.LuEnabled:=FConfig_VaLuEnabled;
aParameters.LuMinY:=FConfig_VaLuMinY;
aParameters.LuMaxY:=FConfig_VaLuMaxY;
FVideoAnalytics.Parameters:=aParameters;
end;
procedure TMediaProcessor_VA_Any_Impl.OnVideoAnalyticsFrameProcessed(
Sender: TVideoAnalytics);
begin
FCurrentResultLock.Enter;
try
FCurrentResult.Add(Sender.GetCurrentResultCopy);
finally
FCurrentResultLock.Leave;
end;
end;
procedure TMediaProcessor_VA_Any_Impl.Prepare;
begin
inherited;
FVideoAnalytics.Init;
end;
procedure TMediaProcessor_VA_Any_Impl.Process(aInData: pointer;
aInDataSize: cardinal; const aInFormat: TMediaStreamDataHeader;
aInfo: pointer; aInfoSize: cardinal; out aOutData: pointer;
out aOutDataSize: cardinal; out aOutFormat: TMediaStreamDataHeader;
out aOutInfo: pointer; out aOutInfoSize: cardinal);
begin
aOutData:=aInData;
aOutDataSize:=aInDataSize;
aOutFormat:=aInFormat;
aOutInfo:=aInfo;
aOutInfoSize:=aInfoSize;
aOutFormat:=aInFormat;
if IsAllowedBySchedule then
begin
if FVideoAnalytics=nil then
begin
SetLastError(FVideoAnalyticsFailure);
end
else begin
FVideoAnalytics.ProcessFrame(aInFormat,aInData,aInDataSize,aInfo,aInfoSize);
end;
end;
end;
procedure TMediaProcessor_VA_Any_Impl.ProcessData2(aInData: pointer;
aInDataSize: cardinal; const aInFormat: TMediaStreamDataHeader;
aInfo: pointer; aInfoSize: cardinal; out aOutData: pointer;
out aOutDataSize: cardinal; out aOutFormat: TMediaStreamDataHeader;
out aOutInfo: pointer; out aOutInfoSize: cardinal;
aAuxResults: TMediaProcessorResultList);
var
i,j,k: Integer;
aStream: TBytesStream;
aObject: ^TVaObject;
aEvent: ^TVaEvent;
aCurrResult: TVaProcessingResult;
aMPResult: TMediaProcessorResult;
begin
Process(aInData,aInDataSize,aInFormat,aInfo,aInfoSize,aOutData,aOutDataSize,aOutFormat,aOutInfo,aOutInfoSize);
if IsAllowedBySchedule and (FVideoAnalytics<>nil) then
begin
FCurrentResultLock.Enter;
try
if FCurrentResult.Count=0 then
exit;
for k := 0 to FCurrentResult.Count-1 do
begin
aCurrResult:=FCurrentResult[k];
if k>=FCache.Count then
FCache.Add(TBytesStream.Create());
aStream:=FCache[k];
aStream.Position:=0;
aStream.WriteInteger(Length(aCurrResult.Objects));
for i := 0 to High(aCurrResult.Objects) do
begin
aObject:=@aCurrResult.Objects[i];
aStream.WriteInteger(aObject.id);
aStream.WriteInteger(aObject.type_);
aStream.WriteBuffer(aObject.position,sizeof(aObject.position));
aStream.WriteBuffer(aObject.rect,sizeof(aObject.rect));
aStream.WriteBuffer(aObject.start_position,sizeof(aObject.start_position));
aStream.WriteInteger(Length(aObject.trajectory));
for j := 0 to High(aObject.trajectory) do
aStream.WriteBuffer(aObject.trajectory[j],sizeof(aObject.trajectory[j]));
aStream.WriteInteger(aObject.mask_index);
aStream.WriteBuffer(aObject.mask_rect,sizeof(aObject.mask_rect));
aStream.WriteInteger(Length(aObject.all_events_deprecated));
for j := 0 to High(aObject.all_events_deprecated) do
aStream.WriteInteger(aObject.all_events_deprecated[j]);
end;
aStream.WriteInteger(Length(aCurrResult.Events));
for i := 0 to High(aCurrResult.Events) do
begin
aEvent:=@aCurrResult.Events[i];
aStream.WriteInteger(integer(aEvent.type_));
aStream.WriteInteger(aEvent.level);
aStream.WriteInteger(aEvent.object_id);
aStream.WriteInteger(aEvent.rule_id);
aStream.WriteString(aEvent.description);
end;
aMPResult.Data:=aStream.Bytes;
aMPResult.DataSize:=aStream.Position;
aMPResult.Info:=nil;
aMPResult.InfoSize:=0;
aMPResult.Format.Clear;
aMPResult.Format.biMediaType:=mtSysData;
aMPResult.Format.biStreamType:=stVideoAnalytics;
aMPResult.Format.TimeStamp:=GetTickCount;
aMPResult.Format.VideoWidth:=FVideoAnalytics.CurrentWidth;
aMPResult.Format.VideoHeight:=FVideoAnalytics.CurrentHeight;
aAuxResults.Add(aMPResult);
end;
FCurrentResult.Clear;
finally
FCurrentResultLock.Leave;
end;
end;
end;
initialization
MediaProceccorFactory.RegisterMediaProcessorImplementation(TMediaProcessor_VA_Any_Impl);
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Data.Cloud.AzureAPI;
interface
uses System.Classes,
System.SysUtils,
System.Generics.Collections,
Data.Cloud.CloudAPI,
Xml.XMLIntf
;
type
/// <summary>Azure extension of TCloudConnectionInfo</summary>
/// <remarks>This provides Azure specific information, such as settings for development storage,
/// and getting the service URLs.
/// </remarks>
TAzureConnectionInfo = class(TCloudConnectionInfo)
private
/// <summary>True to connect to a local development storage service, False to connect to the cloud.</summary>
FUseDevelopmentStorage: boolean;
/// <summary>The blob service URL to use if FUseDefaultEndpoints is false</summary>
FBlobEndpoint: String;
/// <summary>The queue service URL to use if FUseDefaultEndpoints is false</summary>
FQueueEndpoint: String;
/// <summary>The table service URL to use if FUseDefaultEndpoints is false</summary>
FTableEndpoint: String;
/// <summary>Sets if development storage should be used, instead of issuing requests to the cloud.</summary>
/// <param name="use">True to use development storage, false otherwise</param>
procedure SetUseDevelopmentStorage(use: boolean);
/// <summary>Returns the service URL, based on the given information</summary>
/// <remarks>This is a helper function used by the BlobURL, TableURL and QueueURL functions.</remarks>
/// <param name="ServiceType">One of: (blob|table|queue)</param>
/// <param name="ServiceEndpoint">The value of the corresponding [X]Endpoint property.</param>
/// <returns>The URL to the storage service.</returns>
function ServiceURL(const ServiceType, ServiceEndpoint: String): String;
function GetBlobEndpoint: String;
function GetQueueEndpoint: String;
function GetTableEndpoint: String;
protected
/// <summary>Returns the account name used for authentication with the service</summary>
function GetAccountName: String; override;
/// <summary>Returns the account key/password used for authenticating the service</summary>
function GetAccountKey: String; override;
public
/// <summary>Creates a new instance of TAzureConnectionInfo</summary>
// / <param name="AOwner">The TComponent owning this one, or nil</param>
constructor Create(AOwner: TComponent); override;
/// <summary>Returns the URL for working with the blob service.</summary>
/// <returns>The URL for working with the blob service.</returns>
function BlobURL: String;
/// <summary>Returns the URL for working with the table service.</summary>
/// <returns>The URL for working with the table service.</returns>
function TableURL: String;
/// <summary>Returns the URL for working with the queue service.</summary>
/// <returns>The URL for working with the queue service.</returns>
function QueueURL: String;
published
/// <summary>True to connect to a local development storage service, False to connect to the cloud.</summary>
property UseDevelopmentStorage: boolean read FUseDevelopmentStorage write SetUseDevelopmentStorage;
/// <summary>The blob service URL to use if FUseDefaultEndpoints is false</summary>
property BlobEndpoint: string read GetBlobEndpoint write FBlobEndpoint;
/// <summary>The queue service URL to use if FUseDefaultEndpoints is false</summary>
property QueueEndpoint: string read GetQueueEndpoint write FQueueEndpoint;
/// <summary>The table service URL to use if FUseDefaultEndpoints is false</summary>
property TableEndpoint: string read GetTableEndpoint write FTableEndpoint;
/// <summary>The protocol to use as part of the service URL (http|https)</summary>
property Protocol;
/// <summary>Raising the property to published</summary>
property AccountName;
/// <summary>Raising the property to published</summary>
property AccountKey;
/// <summary>The proxy host to use for the HTTP requests to the cloud, or empty string to use none</summary>
property RequestProxyHost;
/// <summary>The proxy host's port to use for the HTTP requests to the cloud</summary>
property RequestProxyPort;
/// <summary>True to use the default service URLs, false to use endpoints from the endpoint properties.
/// </summary>
property UseDefaultEndpoints;
end;
/// <summary>Azure specific implementation of TCloudSHA256Authentication</summary>
/// <remarks>Sets the Authorization type to 'SharedKey'</remarks>
TAzureAuthentication = class(TCloudSHA256Authentication)
protected
/// <summary>Overrides the base implementation, treating the key as base64 encoded.</summary>
/// <param name="AccountKey">The account key, in base64 encoded string representation.</param>
procedure AssignKey(const AccountKey: String); override;
public
/// <summary>Creates a new instance of TAzureAuthentication</summary>
/// <remarks>Sets the authorization type (for the authorization header) to 'SharedKey'</remarks>
// / <param name="ConnectionInfo">The connection info to use in authentiation</param>
constructor Create(ConnectionInfo: TAzureConnectionInfo); overload;
end;
/// <summary>Abstract extension of the TCloudService class.</summary>
/// <remarks>This implements all functionality common to the Azure Blob, Queue and Table
/// services, or common two two of them (allowing the third to extend further and override.)
///</remarks>
TAzureService = class abstract(TCloudService)
protected
/// <summary>The lazy-loaded list of required header names.</summary>
FRequiredHeaderNames: TStrings;
/// <summary>URL Encodes the param name and value.</summary>
/// <remarks>Skips encoding if not for URL.</remarks>
/// <param name="ForURL">True if the parameter is for a URL, false if it is for a signature.</param>
/// <param name="ParamName">Name of the parameter</param>
/// <param name="ParamValue">Value of the parameter</param>
procedure URLEncodeQueryParams(const ForURL: Boolean; var ParamName, ParamValue: String); override;
/// <summary>Returns the current date and time, properly formatted for the x-ms-date header.</summary>
/// <returns>The current date and time, properly formatted for the x-ms-date header.</returns>
function XMsDate: String;
/// <summary>Populates the x-ms-date (and optionally the Date) header in the given list.</summary>
/// <param name="Headers">The header list to add the date header(s) to.</param>
/// <param name="AddRegularDateHeader">True to add the Date header instead of just thex-ms-date one.</param>
procedure PopulateDateHeader(Headers: TStrings; AddRegularDateHeader: Boolean = True);
/// <summary>Returns the TAzureConnectionInfo held by the service</summary>
/// <returns>The TAzureConnectionInfo held by the service</returns>
function GetConnectionInfo: TAzureConnectionInfo;
/// <summary>Returns the list of required header names</summary>
/// <remarks>Implementation of abstract declaration in parent class.
/// Lazy-loads and returns FRequiredHeaderNames. Sets InstanceOwner to false,
/// since this class instance will manage the memory for the object.
/// </remarks>
/// <param name="InstanceOwner">Returns false, specifying the caller doesn't own the list.</param>
/// <returns>The list of required hear names. No values.</returns>
function GetRequiredHeaderNames(out InstanceOwner: Boolean): TStrings; override;
/// <summary>Returns the header name prefix for Azure services, for headers to be included
/// as name/value pairs in the StringToSign in authentication.
/// </summary>
/// <returns>The header prefix (x-ms-)</returns>
function GetCanonicalizedHeaderPrefix: String; override;
public
/// <summary>Creates a new instance of TAzureService</summary>
/// <remarks>This class does not own the ConnectionInfo instance.</remarks>
// / <param name="ConnectionInfo">The Azure service connection info</param>
constructor Create(ConnectionInfo: TAzureConnectionInfo);
/// <summary>Frees the required headers list and destroys the instance</summary>
destructor Destroy; override;
end;
/// <summary>Implementation of TAzureService for managing a Windows Azure Table Service account.</summary>
TAzureTableService = class(TAzureService)
private
function ModifyEntityHelper(const TableName: String; const Entity: TCloudTableRow;
out url, QueryPrefix: String;
out Headers: TStringList): boolean;
procedure AddTableVersionHeaders(Headers: TStrings);
function UpdatedDate: String;
function BuildRowList(const XML: String; const FromQuery: Boolean): TList<TCloudTableRow>;
function GetTablesQueryPrefix(Headers: TStrings; TableName: String = 'Tables'): String;
function GetInsertEntityXML(Entity: TCloudTableRow): String;
protected
/// <summary>Returns the list of required header names</summary>
/// <remarks>Overrides the base implementation, as the Table Service had different/fewer
/// required headers. Lazy-loads and returns FRequiredHeaderNames. Sets InstanceOwner to false,
/// since this class instance will manage the memory for the object.
/// </remarks>
/// <param name="InstanceOwner">Returns false, specifying the caller doesn't own the list.</param>
/// <returns>The list of required hear names. No values.</returns>
function GetRequiredHeaderNames(out InstanceOwner: Boolean): TStrings; override;
public
/// <summary>Creates a new instance of TAzureTableService</summary>
/// <remarks>Sets FUseCanonicalizedHeaders to False</remarks>
// / <param name="ConnectionInfo">The connection info to use for issuing requests.</param>
constructor Create(ConnectionInfo: TAzureConnectionInfo);
/// <summary>Returns an XML representation of the tables existing in the table service account.</summary>
/// <remarks>ContinuationToken is used if there exists more than 1000 tables, and a previous call
/// didn't return the last of the tables. It would have provided a ContinuationToken in the header:
/// 'x-ms-continuation-NextTableName'.
/// </remarks>
/// <param name="ContinuationToken">The optional name of the table to start retrieval from</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The XML representation of the available tables for the service</returns>
function QueryTablesXML(const ContinuationToken: String = ''; ResponseInfo: TCloudResponseInfo = nil): String;
/// <summary>Returns a list of the tables existing in the table service account.</summary>
/// <remarks>ContinuationToken is used if there exists more than 1000 tables, and a previous call
/// didn't return the last of the tables. It would have provided a ContinuationToken in the header:
/// 'x-ms-continuation-NextTableName'.
/// </remarks>
/// <param name="ContinuationToken">The optional name of the table to start retrieval from</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The list of available tables for the service</returns>
function QueryTables(const ContinuationToken: String = ''; ResponseInfo: TCloudResponseInfo = nil): TStrings;
/// <summary>Returns the entities (rows) for the specified table, optionally filtering the result.</summary>
/// <remarks> See the MSDN documentation on "Querying Tables and Entities" for more information
/// on the FilterExpression parameter.
/// At most, 1000 rows are returned. If 1000 rows are returned, use the header values for:
/// x-ms-continuation-NextPartitionKey and x-ms-continuation-NextRowKey to get the unique
/// identifier of the 1001th row. To get these values you need to use the ResponseInfo parameter.
/// Uses the unique identifier values (NextParitionKey and NextRowKey) in your next call to this
/// function, to retrieve the next batch of rows.
/// </remarks>
/// <param name="TableName">The name of the table to get the rows for</param>
/// <param name="FilterExpression">The optional filter expression for refining the results</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="NextPartitionKey">Continuation token value from x-ms-continuation-NextPartitionKey</param>
/// <param name="NextRowKey">Continuation token value from x-ms-continuation-NextRowKey</param>
/// <returns>The XML representation of the rows</returns>
function QueryEntitiesXML(const TableName: String; const FilterExpression: String = '';
ResponseInfo: TCloudResponseInfo = nil;
const NextPartitionKey: String = '';
const NextRowKey: String = ''): String; overload;
/// <summary>Returns the entities (rows) for the specified table, optionally filtering the result.</summary>
/// <remarks> See the MSDN documentation on "Querying Tables and Entities" for more information
/// on the FilterExpression parameter.
/// At most, 1000 rows are returned. If 1000 rows are returned, use the header values for:
/// x-ms-continuation-NextPartitionKey and x-ms-continuation-NextRowKey to get the unique
/// identifier of the 1001th row. To get these values you need to use the ResponseInfo parameter.
/// Uses the unique identifier values (NextParitionKey and NextRowKey) in your next call to this
/// function, to retrieve the next batch of rows.
/// </remarks>
/// <param name="TableName">The name of the table to get the rows for</param>
/// <param name="FilterExpression">The optional filter expression for refining the results</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="NextPartitionKey">Continuation token value from x-ms-continuation-NextPartitionKey</param>
/// <param name="NextRowKey">Continuation token value from x-ms-continuation-NextRowKey</param>
/// <returns>The table's rows which match the given filter, or all rows (up to 1000 rows)
/// if no filter is given.
/// </returns>
function QueryEntities(const TableName: String; const FilterExpression: String = '';
ResponseInfo: TCloudResponseInfo = nil;
const NextPartitionKey: String = '';
const NextRowKey: String = ''): TList<TCloudTableRow>; overload;
/// <summary>Returns the entity(row) for the specified table with the given partition and row keys.</summary>
/// <remarks> The unique key of any Azure table row is comprised of both the Partition Key and Row Key.
/// There should be no situation where a call to this function returns more than one row.
/// </remarks>
/// <param name="TableName">The name of the table to get the row from</param>
/// <param name="PartitionKey">The value of the partition key in the row you want to get</param>
/// <param name="RowKey">The value of the row key in the row you want to get</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The XML representation of the row</returns>
function QueryEntityXML(const TableName: String; const PartitionKey: String; const RowKey: String;
ResponseInfo: TCloudResponseInfo = nil): String; overload;
/// <summary>Returns the entity(row) for the specified table with the given partition and row keys.</summary>
/// <remarks> The unique key of any Azure table row is comprised of both the Partition Key and Row Key.
/// </remarks>
/// <param name="TableName">The name of the table to get the row from</param>
/// <param name="PartitionKey">The value of the partition key in the row you want to get</param>
/// <param name="RowKey">The value of the row key in the row you want to get</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The table's row matching the specified keys, or nil if not found</returns>
function QueryEntity(const TableName: String; const PartitionKey: String; const RowKey: String;
ResponseInfo: TCloudResponseInfo = nil): TCloudTableRow; overload;
/// <summary>Creates a table with the given name.</summary>
/// <param name="TableName">The name of the table to create</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the creation was a success, false otherwise.</returns>
function CreateTable(const TableName: String; ResponseInfo: TCloudResponseInfo = nil): boolean;
/// <summary>Deletes the table with the given name.</summary>
/// <remarks>This marks the table for delete and hides it from future calls when querying the
/// list of available tables. However, it isn't deleted from the server right away,
/// and for a short time after calling delete, you will not be able to create a new table
/// with the same name.
/// </remarks>
/// <param name="TableName">The name of the table to delete</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the delete is successful, false otherwise</returns>
function DeleteTable(const TableName: String; ResponseInfo: TCloudResponseInfo = nil): boolean;
/// <summary>Inserts a row into the given table.</summary>
/// <remarks> The row must have a PartitionKey and RowKey column. If it has a Timestamp column,
/// it will be ignored.
/// Insert fails (409 - Conflict) if another row with the same PartitonKey and RowKey exists.
/// </remarks>
/// <param name="TableName">The name of the table to insert the row into</param>
/// <param name="Entity">The row to insert</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the insertion is successful, false otherwise</returns>
function InsertEntity(const TableName: String; Entity: TCloudTableRow;
ResponseInfo: TCloudResponseInfo = nil): boolean;
/// <summary>Inserts a row into the given table, replacing a previous version of the row, if any.</summary>
/// <remarks> The row must have a PartitionKey and RowKey column. If it has a Timestamp column,
/// it will be ignored.
/// If another row already exists in the table with the given PartitionKey and RowKey, it will
/// be replaced by this row, losing any columns the original row had but this new one doesn't.
/// </remarks>
/// <param name="TableName">The name of the table to insert the row into</param>
/// <param name="Entity">The row to insert</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the insertion is successful, false otherwise</returns>
function UpdateEntity(const TableName: String; Entity: TCloudTableRow;
ResponseInfo: TCloudResponseInfo = nil): boolean;
/// <summary>Inserts a row into the given table, merging with a previous version of the row, if any.</summary>
/// <remarks> The row must have a PartitionKey and RowKey column. If it has a Timestamp column,
/// it will be ignored.
/// If another row already exists in the table with the given PartitionKey and RowKey, it will
/// be merged with the row being specified in this call. The resulting row will be the one
/// specified here, plus any columns not in this row, but existing in the original row.
/// </remarks>
/// <param name="TableName">The name of the table to insert the row into</param>
/// <param name="Entity">The row to insert</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the insertion is successful, false otherwise</returns>
function MergeEntity(const TableName: String; Entity: TCloudTableRow;
ResponseInfo: TCloudResponseInfo = nil): boolean;
/// <summary>Deletes the given row from the specified table.</summary>
/// <remarks>The row must have a PartitionKey and RowKey column specified.</remarks>
/// <param name="TableName">The name of the table to delete the row from.</param>
/// <param name="Entity">The row to delete</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the deletion is successful, false otherwise.</returns>
function DeleteEntity(const TableName: String; const Entity: TCloudTableRow;
ResponseInfo: TCloudResponseInfo = nil): boolean;
end;
/// <summary>Implementation of TAzureService for managing a Windows Azure Queue Service account.</summary>
TAzureQueueService = class(TAzureService)
private
function GetQueuesQueryPrefix(Headers: TStrings; QueueName: String = 'Queues'): String;
function GetMessagesFromXML(const xml: String): TList<TCloudQueueMessage>;
function GetOrPeekMessagesXML(const QueueName: String;
PeekOnly: Boolean;
NumOfMessages: Integer = 0;
VisibilityTimeout: Integer = 0;
ResponseInfo: TCloudResponseInfo = nil): String;
public
/// <summary>Returns the maximum number of queue messages that can be returned.</summary>
/// <returns>The number of queue messages which can be returned by the API for a given queue.</returns>
function GetMaxMessageReturnCount: Integer;
/// <summary>Lists the queues currently available in the queue service account.</summary>
/// <remarks>The supported optional parameters are: prefix, maxresults, include=metadata
/// The 'prefix' parameter has a value which is the prefix a queue name must start with
/// in order to be includes in the list of queues returned by this request.
/// The 'maxresults' parameter takes an integer value specifying how many
/// queues to return. If this isn't specified, up to 5000 queues will be returned.
/// If the 'include' parameter is specified with a value of 'metadata', then metadata
/// corresponding to each queue will be returned in the XML.
/// </remarks>
/// <param name="OptionalParams">Optional parameters to use in the query. See remarks for more information.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The XML string representing the queues</returns>
function ListQueuesXML(OptionalParams: TStrings = nil; ResponseInfo: TCloudResponseInfo = nil): String;
/// <summary>Lists the queues currently available in the queue service account.</summary>
/// <remarks>The supported optional parameters are: prefix, maxresults
/// The 'prefix' parameter has a value which is the prefix a queue name must start with
/// in order to be includes in the list of queues returned by this request.
/// The 'maxresults' parameter takes an integer value specifying how many
/// queues to return. If this isn't specified, up to 5000 queues will be returned.
/// </remarks>
/// <param name="OptionalParams">Optional parameters to use in the query. See remarks for more information.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The list of queues, or an empty list</returns>
function ListQueues(OptionalParams: TStrings = nil; ResponseInfo: TCloudResponseInfo = nil): TList<TCloudQueue>;
/// <summary>Creates a queue with the given name and metadata.</summary>
/// <remarks>If metadata is specified, it will be set as the metadata associated with the queue.</remarks>
/// <param name="QueueName">The name of the queue to create.</param>
/// <param name="MetaDataHeaders">The header name/value pairs to associate with the queue.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the create was successful, false otherwise.</returns>
function CreateQueue(const QueueName: String; const MetaDataHeaders: TStrings = nil;
ResponseInfo: TCloudResponseInfo = nil): boolean;
/// <summary>Deletes the queue with the given name.</summary>
/// <remarks>The queue is marked for delete and won't show up in queries, but there will be a short time
/// before the server allows another queue with the same name to be created again.
/// </remarks>
/// <param name="QueueName">The name of the queue to delete.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the delete is successful, false otherwise</returns>
function DeleteQueue(const QueueName: String; ResponseInfo: TCloudResponseInfo = nil): boolean;
/// <summary>Returns the metadata name/value pairs associated with the given queue</summary>
/// <param name="QueueName">The name of the queue to get the metadata for</param>
/// <param name="MetaData">The returned metadata, or nil if the call fails</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the call is successful, false otherwise</returns>
function GetQueueMetadata(const QueueName: String; out MetaData: TStrings;
ResponseInfo: TCloudResponseInfo = nil): boolean;
/// <summary>Sets the metadata name/value pairs associated with the given queue</summary>
/// <param name="QueueName">The name of the queue to set the metadata for</param>
/// <param name="MetaData">The metadata to set for the queue</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the call is successful, false otherwise</returns>
function SetQueueMetadata(const QueueName: String; const MetaData: TStrings;
ResponseInfo: TCloudResponseInfo = nil): boolean;
/// <summary>Adds a message to the given queue</summary>
/// <remarks>The TimeToLive parameter, if set to something greater tha 0, speicifies the time in seconds
/// to leave the message in the queue before expiring it. The maximum (and default) is 7 days.
/// </remarks>
/// <param name="QueueName">The queue to add the message to</param>
/// <param name="MessageText">The text of the message</param>
/// <param name="TimeToLive">The time in seconds before the message expires, or 0 to use the server default.
/// </param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the message was added successfully, false otherwise.</returns>
function AddMessage(const QueueName: String; const MessageText: String; const TimeToLive: Integer = 0;
ResponseInfo: TCloudResponseInfo = nil): boolean;
/// <summary>Returns messages from the given queue.</summary>
/// <remarks>If NumOfMessages isn't set, then the server default of 1 is used. The maximum allowed value is 32.
/// If VisibilityTimeout isn't set, the server default (30 seconds) is used. The maximum allowed
/// value is 2 hours.
/// Note that messages returned by this call will have their PopReceipt specified, which is a
/// token unique to the message during the VisibilityTimeout which can be used to delete the message.
/// </remarks>
/// <param name="QueueName">The name of the queue to get the messages for</param>
/// <param name="NumOfMessages">The maximum number of messages to return.</param>
/// <param name="VisibilityTimeout">How long the messages should be reserved for</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The XML representation of the messages</returns>
function GetMessagesXML(const QueueName: String;
NumOfMessages: Integer = 0;
VisibilityTimeout: Integer = 0;
ResponseInfo: TCloudResponseInfo = nil): String;
/// <summary>Returns messages from the given queue.</summary>
/// <remarks>If NumOfMessages isn't set, then the server default of 1 is used. The maximum allowed value is 32.
/// If VisibilityTimeout isn't set, the server default (30 seconds) is used. The maximum allowed
/// value is 2 hours.
/// Note that messages returned by this call will have their PopReceipt specified, which is a
/// token unique to the message during the VisibilityTimeout which can be used to delete the message.
/// During VisibilityTimeout the messages are hidden from any further message querying.
/// </remarks>
/// <param name="QueueName">The name of the queue to get the messages for</param>
/// <param name="NumOfMessages">The maximum number of messages to return.</param>
/// <param name="VisibilityTimeout">How long the messages should be reserved for</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The list of messages, with their pop receipts populated</returns>
function GetMessages(const QueueName: String;
NumOfMessages: Integer = 0;
VisibilityTimeout: Integer = 0;
ResponseInfo: TCloudResponseInfo = nil): TList<TCloudQueueMessage>;
/// <summary>Returns messages from the given queue.</summary>
/// <remarks>If NumOfMessages isn't set, then the server default of 1 is used. The maximum allowed value is 32.
/// Note that messages returned by this call will NOT have their PopReceipt specified. There is
/// not VisibilityTimeout, and so other people can instantly query messages and see them.
/// </remarks>
/// <param name="QueueName">The name of the queue to get the messages for</param>
/// <param name="NumOfMessages">The maximum number of messages to return.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The XML representation of the messages</returns>
function PeekMessagesXML(const QueueName: String; NumOfMessages: Integer;
ResponseInfo: TCloudResponseInfo = nil): String;
/// <summary>Returns messages from the given queue.</summary>
/// <remarks>If NumOfMessages isn't set, then the server default of 1 is used. The maximum allowed value is 32.
/// Note that messages returned by this call will NOT have their PopReceipt specified. There is
/// no VisibilityTimeout, so other people can instantly query messages and see them.
/// </remarks>
/// <param name="QueueName">The name of the queue to get the messages for</param>
/// <param name="NumOfMessages">The maximum number of messages to return.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The list of messages</returns>
function PeekMessages(const QueueName: String; NumOfMessages: Integer;
ResponseInfo: TCloudResponseInfo = nil): TList<TCloudQueueMessage>;
/// <summary>Deletes the given message from the specified queue</summary>
/// <param name="QueueName">Name of the queue to delete a message from</param>
/// <param name="MessageId">The unique ID of the message to delete</param>
/// <param name="PopReceipt">The pop receipt required for deleting the message</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the delete was successful, false otherwise</returns>
function DeleteMessage(const QueueName: String; const MessageId: String; const PopReceipt: String;
ResponseInfo: TCloudResponseInfo = nil): boolean; overload;
/// <summary>Deletes the given message from the specified queue</summary>
/// <remarks>If GetPopReceiptIfNeeded is set to true (which it is by default) then if the message object
/// has empty string set as its pop receipt then a pop receipt is acquired by first calling
/// GetMessages with the default values for number of messages and visibility timeout.
/// If the message requesting deletion isn't on the top of the queue, the deletion will fail.
/// </remarks>
/// <param name="QueueName">The name of the queue to delete the message from</param>
/// <param name="QueueMessage">The message to delete</param>
/// <param name="GetPopReceiptIfNeeded">True to try getting a pop receipt for the message
/// if it doesn't have one already.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the deletion succeeds, false otherwise.</returns>
function DeleteMessage(const QueueName: String; const QueueMessage: TCloudQueueMessage;
GetPopReceiptIfNeeded: Boolean = True;
ResponseInfo: TCloudResponseInfo = nil): boolean; overload;
/// <summary>Clears the messages from the given queue</summary>
/// <param name="QueueName">The name of the queue to delete all messages from</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if successful, false otherwise</returns>
function ClearMessages(const QueueName: String;
ResponseInfo: TCloudResponseInfo = nil): boolean;
end;
/// <summary>Represents a container for the Windows Azure Blob Service</summary>
TAzureContainer = class
private
FName: String;
FURL: String;
FProperties: TStrings;
FMetadata: TStrings;
public
/// <summary>Creates a new instance of TAzureContainer</summary>
/// <remarks>If Properties and/or Metadata are left as nil, then a new empty TStrings will be created.
/// </remarks>
// / <param name="Name">The name of the container</param>
// / <param name="URL">The unique URL of the container</param>
// / <param name="Properties">The properties associated with the container</param>
// / <param name="Metadata">The metadata associated with the container</param>
constructor Create(const Name, URL: String; Properties: TStrings = nil; Metadata: TStrings = nil);
/// <summary>Frees the properties and metadata and destroys the instance.</summary>
destructor Destroy; override;
/// <summary>Says if this container is the root container</summary>
/// <returns>Returns </returns>
function IsRoot: Boolean;
/// <summary>The name of the container</summary>
property Name: String read FName;
/// <summary>The unique URL of the container</summary>
property URL: String read FURL;
/// <summary>The properties associated with the container</summary>
property Properties: TStrings read FProperties;
/// <summary>The metadata associated with the container</summary>
property Metadata: TStrings read FMetadata;
end;
/// <summary>Options for container and blob public access restrictions.</summary>
/// <remarks>These are used to determine which containers (and the blobs they contain) are visible to the public
/// and with which restrictions they are visible.
/// When bpaPrivate is used, neither the Container or the blobs it contains are publicly visible.
/// When bpaContainer is used, the container and its blobs are fully visible
/// When bpaBlob is used, the blobs within the container are visible, but the container
/// data itself is hidden. This also prevents enumerating the blobs of a container.
/// </remarks>
TBlobPublicAccess = (bpaPrivate, bpaContainer, bpaBlob);
/// <summary>Access policy information, specifying the allowed public operations.</summary>
/// <remarks>The four operations are: Read, Write, Delete and List. Each of these can be
/// enabled or disabled. Furthermore, the access policy can have a start time and
/// an expiry time, to create a window of time the policy takes effect for.
/// </remarks>
TAccessPolicy = record
/// <summary>The date the access policy is not valid before.</summary>
/// <remarks>must be expressed as UTC times and must adhere to a valid ISO 8061 format.
/// Supported formats include:
/// YYYY-MM-DD
/// YYYY-MM-DDThh:mmTZD
/// YYYY-MM-DDThh:mm:ssTZD
/// YYYY-MM-DDThh:mm:ss.ffffffTZD
/// </remarks>
Start: String;
/// <summary>The date the access policy is not valid after.</summary>
/// <remarks>must be expressed as UTC times and must adhere to a valid ISO 8061 format.
/// Supported formats include:
/// YYYY-MM-DD
/// YYYY-MM-DDThh:mmTZD
/// YYYY-MM-DDThh:mm:ssTZD
/// YYYY-MM-DDThh:mm:ss.ffffffTZD
/// </remarks>
Expiry: String;
/// <summary>True when read permission is granted by this access policy</summary>
PermRead: boolean;
/// <summary>True when write permission is granted by this access policy</summary>
PermWrite: boolean;
/// <summary>True when delete permission is granted by this access policy</summary>
PermDelete:boolean;
/// <summary>True when list permission is granted by this access policy</summary>
PermList: boolean;
/// <summary>Returns the string representation of the permissions.</summary>
/// <remarks>Always in the order: rwdl, omitting any which are currently set to false.</remarks>
/// <returns>The string representation of the permissions currently set to true.</returns>
function GetPermission: String;
/// <summary>Sets the boolean fields by parsing the string representation.</summary>
/// <remarks>Only four characters, at most, are expected in the string: rwdl. If one of
/// those characters is present in the string, then its corresponding permission
/// boolean field is set to true. Otherwise, it is set to false.
/// </remarks>
/// <param name="rwdl">The string representation of the permission fields that should be set to true</param>
procedure SetPermission(const rwdl: String);
/// <summary>Returns the XML representation of the access policy, as it is required by Azure</summary>
/// <returns>The XML representation of the access policy, as it is required by Azure</returns>
function AsXML: String;
/// <summary>Creates a new instance of TAccessPolicy with all permissions, except read, off.</summary>
/// <returns>The new initialized instance.</returns>
class function Create: TAccessPolicy; static;
/// <summary>Returns or sets the permissions with a string representation.</summary>
property Permission: string read GetPermission write SetPermission;
end;
/// <summary>A signed identifier, which is used to uniquely identify an Access Policy.</summary>
TSignedIdentifier = class
private
FId: String;
FResource: String;
public
/// <summary>The Access Policy this identifies.</summary>
AccessPolicy: TAccessPolicy;
/// <summary>Creates a new instance of TSignedIdentifier</summary>
// / <param name="Resource">The resource (container, for example) name this is for.</param>
constructor Create(const Resource: String); overload;
/// <summary>Creates a new instance of TSignedIdentifier</summary>
// / <param name="Resource">The resource (container, for example) name this is for.</param>
// / <param name="Policy">The access policy this identifies.</param>
constructor Create(const Resource: String; Policy: TAccessPolicy; UniqueId: String = ''); overload;
/// <summary>The XML representation of the signed identifier, as it is required for Azure requests.</summary>
/// <returns>The XML representation used for create/update requests.</returns>
function AsXML: String; virtual;
/// <summary>The unique Id</summary>
/// <remarks>The maximum length of the unique identifier is 64 characters</remarks>
property Id: String read FId write FId;
end;
/// <summary>Enumerates the types of Azure blobs</summary>
/// <remarks>abtPrefix is used when the item represents a virtual subdirectory containing blobs</remarks>
TAzureBlobType = (abtBlock, abtPage, abtPrefix);
/// <summary>Enumerates the different states a leasable item can be in.</summary>
TAzureLeaseStatus = (alsLocked, alsUnlocked);
/// <summary>Represents a blob of any supported type, with its common features.</summary>
/// <remarks>abtPrefix is used as the BlobType when the item represents a virtual subdirectory
/// containing blobs and/or subdirectories. It signifies that only the Name property of
/// the blob instance is valid, as it doesn't represent a blob itself, but instead
/// represents a directory.
/// </remarks>
TAzureBlob = class
private
FName: String;
FUrl: String;
FSnapshot: String;
FBlobType: TAzureBlobType;
FLeaseStatus: TAzureLeaseStatus;
FProperties: TStrings;
FMetadata: TStrings;
public
/// <summary>Creates a new instance of TAzureBlob</summary>
// / <param name="Name">The name of the blob, or BlobPrefix if BlobType is abtPrefix</param>
// / <param name="BlobType">The blob type</param>
// / <param name="Url">The Blob URL, or empty string if BlobType is abtPrefix</param>
// / <param name="LeaseStatus">The lease status of the blob</param>
// / <param name="Snapshot">The optional Snapshot date-time-value</param>
constructor Create(const Name: String; BlobType: TAzureBlobType; const Url: String = '';
LeaseStatus: TAzureLeaseStatus = alsUnlocked; const Snapshot: String = '');
/// <summary>Frees the metadata and properties and destroys the instance.</summary>
destructor Destroy; override;
/// <summary>The name of the blob, or BlobPrefix if BlobType is abtPrefix</summary>
property Name: String read FName;
/// <summary>The Blob URL, or empty string if BlobType is abtPrefix</summary>
property Url: String read FUrl;
/// <summary>The Blob type</summary>
property BlobType: TAzureBlobType read FBlobType;
/// <summary>The optional Snapshot date-time-value</summary>
property Snapshot: String read FSnapshot;
/// <summary>The lease status of the blob (locked/unlocked)</summary>
property LeaseStatus: TAzureLeaseStatus read FLeaseStatus write FLeaseStatus;
/// <summary>The blob's list of property name/value pairs</summary>
property Properties: TStrings read FProperties;
/// <summary>The blob's list of metadata name/value pairs</summary>
property Metadata: TStrings read FMetadata;
end;
/// <summary>Record of optional conditional restrictions.</summary>
/// <remarks>These can be used, for example, when copying a blob or when creating a blob
/// snapshot. They provide a way to specify under which conditions the action
/// should happen or not happen.
/// </remarks>
TBlobActionConditional = record
/// <summary>A DateTime value. Specify to copy the blob only if the source blob has been
/// modified since the specified date/time.
///</summary>
IfSourceModifiedSince: String;
/// <summary>A DateTime value. Specify to copy the blob only if the source blob has not been
/// modified since the specified date/time.
/// </summary>
IfSourceUnmodifiedSince: String;
/// <summary>Specify this conditional header to copy the source blob only if its
/// ETag matches the value specified.
/// </summary>
IfSourceMatch: String;
/// <summary>Specify this conditional header to copy the blob only if its ETag
/// does not match the value specified.
/// </summary>
IfSourceNoneMatch: String;
/// <summary>A DateTime value. Specify this conditional header to perform the action:
/// Copying a Blob:
/// only if the destination blob has been modified since the specified date/time.
/// Creating a Snapshot:
/// only if the blob has been modified since the specified date/time.
/// </summary>
IfModifiedSince: String;
/// <summary>A DateTime value. Specify this conditional header to perform the action:
/// Copying a Blob:
/// only if the destination blob has not been modified since the specified date/time.
/// Creating a Snapshot:
/// only if the blob has not been modified since the specified date/time.
/// </summary>
IfUnmodifiedSince: String;
/// <summary>Specify an ETag value to perform the action only if the blob's ETag value
/// matches the value specified. The blob checked is either the destination
/// blob (when copying a blob) or the blob being snapshotted (when creating a snapshot.)
/// </summary>
IfMatch: String;
/// <summary>Specify an ETag value to perform the action only if the blob's ETag value
/// does not match the value specified. The blob checked is either the destination
/// blob (when copying a blob) or the blob being snapshotted (when creating a snapshot.)
/// </summary>
IfNoneMatch: String;
/// <summary>Specifies a number that the sequence number must be less than or equal to.
/// Used in the PutPage action.
/// </summary>
IfSequenceNumberLessThanOrEqual: String;
/// <summary>Specifies a number that the sequence number must be less than.
/// Used in the PutPage action.
/// </summary>
IfSequenceNumberLessThan: String;
/// <summary>Specifies a number that the sequence number must be equal to.
/// Used in the PutPage action.
/// </summary>
IfSequenceNumberEquals: String;
/// <summary>Creates a new instance of TBlobActionConditional</summary>
class function Create: TBlobActionConditional; static;
/// <summary>Populates the given header list with the key/value pair of any field with an assigned value.
/// </summary>
/// <remarks>The keys used will be the header names, as required by Azure requests.</remarks>
/// <param name="Headers">The headers list to populate</param>
procedure PopulateHeaders(Headers: TStrings);
end;
/// <summary>The available block types for Azure block blobs</summary>
/// <remarks>abtLatest is used when calling PutBlockList and you want to use the latest version
/// of a block, which would either be in the uncommitted list (newer)
/// or the commited list (older.)
/// </remarks>
TAzureBlockType = (abtCommitted, abtUncommitted, abtLatest);
/// <summary>A block blob block item.</summary>
/// <remarks>Size can be left out if this item is being used in a PutBlockList operation.
/// It will be populated when calling GetBlockList.
/// </remarks>
TAzureBlockListItem = record
/// <summary>The base 64 encoded unique ID of the block</summary>
BlockId: String;
/// <summary>The size of the block data in bytes</summary>
/// <remarks>Ignore this value when doing utBlockList requests</remarks>
Size: String;
/// <summary>The block type</summary>
/// <remarks>When populated from a GetBlockList call, the available types are:
/// abtCommitted and abtUncommitted. When calling PutBlockList, abtLatest is also supported.
/// A given ID can have up to two blocks associated with it, where one block is in
/// the committed list, and the other is in the uncommited list.
/// </remarks>
BlockType: TAzureBlockType;
/// <summary>Creates a new instance of TAzureBlockListItem with the given values</summary>
/// <param name="ABlockId">The blob Id to set</param>
/// <param name="ABlockType">The block type to set</param>
/// <param name="ASize">The size to set</param>
/// <returns>A new instance of TAzureBlockListItem</returns>
class function Create(ABlockId: String; ABlockType: TAzureBlockType;
ASize: String = '0'): TAzureBlockListItem; static;
/// <summary>Returns the XML in a format as required by the PutBlockList action.</summary>
function AsXML: String;
end;
/// <summary>Used when querying blocks, to get all blocks, or refine based on type.</summary>
TAzureQueryIncludeBlockType = (aqbtCommitted, aqbtUncommitted, aqbtAll);
/// <summary>Represents a page range, as returned by GetPageRegions.</summary>
/// <remarks>These are used to specify pages which have been populated with data.
/// </remarks>
TAzureBlobPageRange = record
/// <summary>The first byte of the range, which cab be used to infer the page</summary>
StartByte: Int64;
/// <summary>The end byte of the range, which can be used to calculate how many pages are in the range.</summary>
EndByte: Int64;
/// <summary>Creates a new instance of TAzureBlobPageRange</summary>
class function Create(StartByte, EndByte: Int64): TAzureBlobPageRange; static;
/// <summary>Returns the starting page, zero-indexed, based on the StartByte.</summary>
/// <returns>the starting page of the range</returns>
function GetStartPage: Integer;
/// <summary>Returns the number of pages in the range.</summary>
/// <returns>The number of pages in the range.</returns>
function GetPageCount: Integer;
end;
/// <summary>Implementation of TAzureService for managing a Windows Azure Blob Service account.</summary>
TAzureBlobService = class(TAzureService)
private
function GetBlobContainerQueryPrefix(Headers: TStrings;
ContainerName: String = 'Container';
BlobName: String = ''): String;
function LoadChildrenAsProperties(ANode: IXMLNode): TStrings;
function ParseContainerFromContainerNode(ContainerNode: IXMLNode): TAzureContainer;
function BuildMetadataHeaderList(const Metadata: TStrings): TStringList;
function GetPublicAccessString(PublicAccess: TBlobPublicAccess): String;
function HandleBlobLease(ContainerName, BlobName: String; const LeaseAction, LeaseId: String;
SuccessCode: Integer;
out Success: boolean; ResponseInfo: TCloudResponseInfo = nil): String;
function DeleteBlobInternal(ContainerName, BlobName, SnapShot: String; OnlySnapshots: Boolean;
LeaseId: String; ResponseInfo: TCloudResponseInfo): boolean;
function GetBlobInternal(ContainerName, BlobName, Snapshot, LeaseId: String;
out Metadata, Properties: TStrings;
ResponseContent: TStream;
StartByte, EndByte: int64; GetAsHash: boolean;
ResponseInfo: TCloudResponseInfo): boolean;
function CopyBlobInternal(TargetContainerName, TargetBlobName, SourceContainerName,
SourceBlobName: String;
const SourceSnapshot: String;
const TargetLeaseId: String;
CopyConditionals: TBlobActionConditional;
Metadata: TStrings;
ResponseInfo: TCloudResponseInfo): boolean;
function PutPageInternal(ContainerName, BlobName: String;
Content: TBytes; DoClear: Boolean;
StartPage, PageCount: Integer;
ActionConditional: TBlobActionConditional;
const ContentMD5: String;
const LeaseId: String;
ResponseInfo: TCloudResponseInfo): boolean; overload;
procedure PopulateBlobPropertyHeaders(Headers, Properties: TStrings);
procedure AddBlockItems(BlocksNode: IXMLNode; BlockList: TList<TAzureBlockListItem>;
BlockType: TAzureBlockType);
public
/// <summary>Returns the containers available on the blob service account</summary>
/// <remarks>Supported optional parameters are: prefix, marker, maxresults, include=metadata.
/// If 'prefix' is set, its value is set as being the prefix a container name needs to
/// start with in order to be included in the list of containers returned by this call.
/// If 'marker' is set then this is used as a continuation token, for which container to
/// start the listing at. The value for this continuation token is specified in the 'NextMarker'
/// element of the XML returned.
/// If 'maxresults' is specified, it is treated as an integer between 1 and 5000. This represents
/// the maximum number of containers to return with this call.
/// If 'include' is set, with a value of 'metadata' then the metadata for each container is also returned.
/// </remarks>
/// <param name="OptionalParams">The optional parameters for the call. See remarks for more information.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The XML representation of the available containers.</returns>
function ListContainersXML(OptionalParams: TStrings = nil; ResponseInfo: TCloudResponseInfo = nil): String;
/// <summary>Returns the containers available on the blob service account</summary>
/// <remarks>Supported optional parameters are: prefix, marker, maxresults.
/// If 'prefix' is set, its value is set as being the prefix a container name needs to
/// start with in order to be included in the list of containers returned by this call.
/// If 'marker' is set then this is used as a continuation token, for which container to
/// start the listing at. The value for this continuation token is specified in the 'NextMarker'
/// element of the XML returned.
/// If 'maxresults' is specified, it is treated as an integer between 1 and 5000. This represents
/// the maximum number of containers to return with this call.
/// If 'include' is set, with a value of 'metadata' then the metadata for each container is also returned.
/// </remarks>
/// <param name="NextMarker">Will be set to the 'NextMarker' returned from the request, or empty string</param>
/// <param name="OptionalParams">The optional parameters for the call. See remarks for more information.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The XML representation of the available containers.</returns>
function ListContainers(out NextMarker: String;
OptionalParams: TStrings = nil;
ResponseInfo: TCloudResponseInfo = nil): TList<TAzureContainer>; overload;
/// <summary>Returns the containers available on the blob service account</summary>
/// <remarks>Supported optional parameters are: prefix, marker, maxresults.
/// If 'prefix' is set, its value is set as being the prefix a container name needs to
/// start with in order to be included in the list of containers returned by this call.
/// If 'marker' is set then this is used as a continuation token, for which container to
/// start the listing at. The value for this continuation token is specified in the 'NextMarker'
/// element of the XML returned.
/// If 'maxresults' is specified, it is treated as an integer between 1 and 5000. This represents
/// the maximum number of containers to return with this call.
/// If 'include' is set, with a value of 'metadata' then the metadata for each container is also returned.
/// </remarks>
/// <param name="OptionalParams">The optional parameters for the call. See remarks for more information.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The XML representation of the available containers.</returns>
function ListContainers(OptionalParams: TStrings = nil;
ResponseInfo: TCloudResponseInfo = nil): TList<TAzureContainer>; overload;
/// <summary>Creates a new container with the given name</summary>
/// <remarks>If the container with the same name already exists, or if the naming requirements
/// aren't followed, then the operation fails.
/// </remarks>
/// <param name="ContainerName">The name of the container to create</param>
/// <param name="MetaData">The optional metadata to associate with the container</param>
/// <param name="PublicAccess">The public access setting to use for the container</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the creation was successful, false otherwise.</returns>
function CreateContainer(ContainerName: string;
MetaData: TStrings = nil;
PublicAccess: TBlobPublicAccess = bpaContainer;
ResponseInfo: TCloudResponseInfo = nil): boolean;
/// <summary>Creates the root container</summary>
/// <remarks>If the root container already eists then the operation fails. This calls into
/// CreateContainer, passing $root as the ContainerName.
/// </remarks>
/// <param name="MetaData">The optional metadata to associate with the container</param>
/// <param name="PublicAccess">The public access setting to use for the container</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the creation was successful, false otherwise.</returns>
function CreateRootContainer(MetaData: TStrings = nil;
PublicAccess: TBlobPublicAccess = bpaContainer;
ResponseInfo: TCloudResponseInfo = nil): boolean;
/// <summary>Deletes the container with the given name</summary>
/// <param name="ContainerName">The name of the container to delete</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the delete is successful, false otherwise.</returns>
function DeleteContainer(ContainerName: String; ResponseInfo: TCloudResponseInfo = nil): boolean;
/// <summary>Deletes the root container</summary>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the delete is successful, false otherwise.</returns>
function DeleteRootContainer(ResponseInfo: TCloudResponseInfo = nil): boolean;
/// <summary>Returns the properties for the container with the given name.</summary>
/// <param name="ContainerName">The name of the container to get the properties for</param>
/// <param name="Properties">The outputted properties, or nil if the call fails</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the population was successful, false otherwise</returns>
function GetContainerProperties(ContainerName: String; out Properties: TStrings;
ResponseInfo: TCloudResponseInfo = nil): boolean; overload;
/// <summary>Returns the properties and metadata for the container with the given name.</summary>
/// <param name="ContainerName">The name of the container to get the properties and metadata for</param>
/// <param name="Properties">The outputted properties, or nil if the call fails</param>
/// <param name="Metadata">The outputted metadata, or nil if the call fails</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the population was successful, false otherwise</returns>
function GetContainerProperties(ContainerName: String; out Properties, Metadata: TStrings;
ResponseInfo: TCloudResponseInfo = nil): boolean; overload;
/// <summary>Returns the metadata for the container with the given name.</summary>
/// <param name="ContainerName">The name of the container to get the metadata for</param>
/// <param name="Metadata">The outputted metadata, or an empty list</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the population was successful, false otherwise</returns>
function GetContainerMetadata(ContainerName: String; out Metadata: TStrings;
ResponseInfo: TCloudResponseInfo = nil): boolean;
/// <summary>Sets the metadata for the specified container.</summary>
/// <remarks>Note that this replaces any existing metadata values. If you don't want to lose any
/// of the metadata already on the container, be sure to include them in the Metadata
/// passed in to this call.
/// </remarks>
/// <param name="ContainerName">The name of the container to set the metadata for</param>
/// <param name="Metadata">The metadata to set onto the container</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the action was successful, false otherwise</returns>
function SetContainerMetadata(ContainerName: String; const Metadata: TStrings;
ResponseInfo: TCloudResponseInfo = nil): boolean;
/// <summary>Returns the public permissions for the container.</summary>
/// <param name="ContainerName">The name of the container to get the permissions for</param>
/// <param name="PublicAccess">The public access setting for the container</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The XML representation of the access policies</returns>
function GetContainerACLXML(ContainerName: String; out PublicAccess: TBlobPublicAccess;
ResponseInfo: TCloudResponseInfo = nil): String;
/// <summary>Returns the public permissions for the container.</summary>
/// <param name="ContainerName">The name of the container to get the permissions for</param>
/// <param name="PublicAccess">The public access setting for the container</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The list of access policies</returns>
function GetContainerACL(ContainerName: String; out PublicAccess: TBlobPublicAccess;
ResponseInfo: TCloudResponseInfo = nil): TList<TSignedIdentifier>;
/// <summary>Adds or updates the Signed Identifier with the given ID for the specified container.</summary>
/// <remarks>When calling this function, the existing permissions are replaced.
/// To update the container's permissions, call GetContainerACL to retrieve all access policies
/// associated with the container, change the access policy that you want,
/// then call SetContainerACL with the complete list of TSignedIdentifier to perform the update,
/// Or passing the single SignedIdentifier's Id and AccessPolicy.
/// </remarks>
/// <param name="ContainerName">The name of the container to set the signed identifier for</param>
/// <param name="SignedIdentifierId">The unique ID of the single signed identifier to add/update</param>
/// <param name="AccessPolicy">The SignedIdentifier's access policy</param>
/// <param name="PublicAccess">The value to set as the container's public access. Defaults to container</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the action was successful, false otherwise</returns>
function SetContainerACL(ContainerName: String;
const SignedIdentifierId: String;
AccessPolicy: TAccessPolicy;
PublicAccess: TBlobPublicAccess = bpaContainer;
ResponseInfo: TCloudResponseInfo = nil): boolean; overload;
/// <summary>Adds or updates the Signed Identifiers for the specified container.</summary>
/// <remarks>When calling this function, the existing permissions are replaced.
/// To update the container's permissions, call GetContainerACL to retrieve all access policies
/// associated with the container, change the access policy that you want,
/// then call SetContainerACL with the complete list of TSignedIdentifier to perform the update.
/// </remarks>
/// <param name="ContainerName">The name of the container to set the signed identifiers for</param>
/// <param name="SignedIdentifiers">The signed identifiers (with their access policies) to set.</param>
/// <param name="PublicAccess">The value to set as the container's public access. Defaults to container</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the action was successful, false otherwise</returns>
function SetContainerACL(ContainerName: String;
SignedIdentifiers: TList<TSignedIdentifier>;
PublicAccess: TBlobPublicAccess = bpaContainer;
ResponseInfo: TCloudResponseInfo = nil): boolean; overload;
/// <summary>Returns the list of blobs for the given container.</summary>
/// <remarks>The following optional parameters are supported:
/// prefix, delimiter, marker, maxresults, include={snapshots,metadata,uncommittedblobs}
/// If prefix is specified, only blobs with names starting with the specified prefix are shown.
/// If delimiter is specified, then Any blob with a name (after the prefix string) containing
/// the delimiter string will be grouped into a 'BlobPrefix' node, as appropriate. What this
/// does is provides a way to view the blobs with a virtual directory structure, where you could
/// then take the values of the returned 'BlobPrefix' Name nodes, and use those as prefix values
/// for subsequent calls.
/// If marker is specified, it is used as a continuation token to retrieve more blobs from where
/// a previous invocation left off when it wasn't able to return all the blobs.
/// If maxresults is specified, then it is treated as an integer representing the maximum
/// number of blobs to return. The default (and maximum) is 5000. If more blobs exist than the
/// maxresults allows, then the 'NextMarker' in the XML will be populated, and you can use this
/// as the value of 'marker' in a future call.
/// If include is specified it can have a CSV string of one or more of the following:
/// snapshots - include blob snapshots in the response (ordered oldest to newest)
/// metadata - specifies to include each blob's metadata in the response
/// uncommittedblobs - says to include in the response blobs with uncommitted sections
/// Note that blobs under the $root container can't have a slash in thier name.
/// </remarks>
/// <param name="ContainerName">The container to get the blobs for. Or $root for the root container.</param>
/// <param name="OptionalParams">The optional parameter name/value pairs. See remarks for more information.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The XML representation of the container's blobs.</returns>
function ListBlobsXML(ContainerName: String; OptionalParams: TStrings = nil;
ResponseInfo: TCloudResponseInfo = nil): String;
/// <summary>Returns the list of blobs for the given container.</summary>
/// <remarks>The following optional parameters are supported:
/// prefix, delimiter, marker, maxresults, include={snapshots,metadata,uncommittedblobs}
/// See comment for ListBlobsXML for more information.
/// </remarks>
/// <param name="ContainerName">The container to get the blobs for. Or $root for the root container.</param>
/// <param name="OptionalParams">The optional parameter name/value pairs. See remarks for more information.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The list of the container's blobs.</returns>
function ListBlobs(ContainerName: String; OptionalParams: TStrings = nil;
ResponseInfo: TCloudResponseInfo = nil): TList<TAzureBlob>; overload;
/// <summary>Returns the list of blobs for the given container.</summary>
/// <remarks>The following optional parameters are supported:
/// prefix, delimiter, marker, maxresults, include={snapshots,metadata,uncommittedblobs}
/// See comment for ListBlobsXML for more information.
/// </remarks>
/// <param name="ContainerName">The container to get the blobs for. Or $root for the root container.</param>
/// <param name="NextMarker">The continuation token if not all the blobs were returned.</param>
/// <param name="OptionalParams">The optional parameter name/value pairs. See remarks for more information.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The list of the container's blobs.</returns>
function ListBlobs(ContainerName: String; out NextMarker: String; OptionalParams: TStrings = nil;
ResponseInfo: TCloudResponseInfo = nil): TList<TAzureBlob>; overload;
/// <summary>Creates a new block blob, or updates an existing one, in the given container</summary>
/// <remarks>If a block blob with the given name (in the specified container) already exists,
/// then its content will be replaced with the data from this call.
/// Note that LeaseId should be set as EmptyString, except when a blob with the given name
/// already exists, and it is currently locked.
/// The Optional headers can be set onto the request. Such as:
/// Content-Type (or x-ms-blob-content-type)
/// Content-Encoding (or x-ms-blob-content-encoding)
/// Content-Language (or x-ms-blob-content-language)
/// Content-MD5 (or x-ms-blob-content-md5)
/// Cache-Control (or x-ms-blob-cache-control)
/// If-Modified-Since
/// If-Unmodified-Since
/// If-Match (Compares the resource's Etag value to the value of this header)
/// If-None-Match (Compares the resource's Etag value to the value of this header)
/// The optional metadata names should start with 'x-ms-meta-'. If they do not,
/// this prefix will be added.
/// The maximum allowed Content-Length of a block blob is 64 MB. If it is larger than
/// that, then you need to upload it as blocks.
/// </remarks>
/// <param name="ContainerName">The name of the blob's container</param>
/// <param name="BlobName">The name of the blob</param>
/// <param name="Content">The content to set into the blob</param>
/// <param name="LeaseId">The optional lease Id.</param>
/// <param name="OptionalHeaders">The optional headers</param>
/// <param name="Metadata">The metadata to set onto the blob</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the create/replace was successful, false otherwise.</returns>
function PutBlockBlob(ContainerName, BlobName: String; Content: TBytes;
LeaseId: String = '';
OptionalHeaders: TStrings = nil; Metadata: TStrings = nil;
ResponseInfo: TCloudResponseInfo = nil): boolean;
/// <summary>Creates a new block blob, or updates an existing one, in the given container</summary>
/// <remarks>Creates a new page blob, with no content, but a specified maximum content length.
/// Page blobs don't have content until you add pages with a PutPage request.
/// For more information on the Header and Metadata parameters, see the documentation
/// for PutBlockBlob.
/// The maximum supported length is 1TB. Each page must be aligned to a 512-byte boundary.
/// </remarks>
/// <param name="ContainerName">The name of the container the blob should be created in</param>
/// <param name="BlobName">The name of the blob</param>
/// <param name="MaximumSize">The maximum contentent length of the blob.</param>
/// <param name="OptionalHeaders">The optional headers</param>
/// <param name="Metadata">The metadata to set onto the blob</param>
/// <param name="BlobSequenceNumber">Optional user-controlled value usable for tracking requests</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the create/replace was successful, false otherwise.</returns>
function PutPageBlob(ContainerName, BlobName: String; MaximumSize: int64;
OptionalHeaders: TStrings = nil; Metadata: TStrings = nil;
BlobSequenceNumber: int64 = 0;
ResponseInfo: TCloudResponseInfo = nil): boolean;
/// <summary>Attempts to acquire a lease on the specified blob</summary>
/// <remarks>You can not acquire a lease for a snapshot.</remarks>
/// <param name="ContainerName">The name of the container the blob is in</param>
/// <param name="BlobName">The name of the blob to acquire a lease for</param>
/// <param name="LeaseId">The acquired lease ID, or empty string is failed</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the lease was acquired, false otherwise</returns>
function AcquireBlobLease(ContainerName, BlobName: String; out LeaseId: String;
ResponseInfo: TCloudResponseInfo = nil): boolean;
/// <summary>Attempts to renew the specified lease for the given blob.</summary>
/// <param name="ContainerName">The name of the container the blob is in</param>
/// <param name="BlobName">The name of the blob to renew the lease for</param>
/// <param name="LeaseId">The Id of the lease that was previously acquired</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the lease was renewed, false otherwise</returns>
function RenewBlobLease(ContainerName, BlobName: String; const LeaseId: String;
ResponseInfo: TCloudResponseInfo = nil): boolean;
/// <summary>Releases a lease that was previously acquired</summary>
/// <param name="ContainerName">The name of the container the blob is in</param>
/// <param name="BlobName">The name of the blob to release the lease for</param>
/// <param name="LeaseId">The Id of the lease that was previously acquired</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the call executes successfully, false otherwise</returns>
function ReleaseBlobLease(ContainerName, BlobName: String; const LeaseId: String;
ResponseInfo: TCloudResponseInfo = nil): boolean;
/// <summary>Breaks a lease previously acquired, without specifying the lease Id</summary>
/// <remarks>Similar to calling 'ReleaseBlobLease' but since the LeaseId is not specified,
/// the lease is allowed to expire before a new lease can be acquired. In this period,
/// the lease is not able to be renewed.
/// The value set into LeaseTimeRemaining specifies how many seconds remain before
/// the current lease expires.
/// </remarks>
/// <param name="ContainerName">The name of the container the blob is in</param>
/// <param name="BlobName">The name of the blob to break the lease for</param>
/// <param name="LeaseTimeRemaining">The number of seconds remaining until the lease expires</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the call executes successfully, false otherwise</returns>
function BreakBlobLease(ContainerName, BlobName: String; out LeaseTimeRemaining: Integer;
ResponseInfo: TCloudResponseInfo = nil): boolean;
/// <summary>Gets the metadata for a given blob</summary>
/// <remarks>LeaseId is only required if it is the blob (not a snapshot) you are interested in,
/// and if that blob is currently locked. In no other situation should you specify a value
/// other than empty string for LeaseId, otherwise the request will fail.
/// </remarks>
/// <param name="ContainerName">The name of the container the blob is in</param>
/// <param name="BlobName">The name of the blob to get the metadata for</param>
/// <param name="Metadata">The returned metadata, or nil if the request fails</param>
/// <param name="Snapshot">The snapshot identifier, if you are interested in a snapshot of the blob</param>
/// <param name="LeaseId">The LeaseId, required if the blob is locked</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the call executes successfully, false otherwise</returns>
function GetBlobMetadata(ContainerName, BlobName: String; out Metadata: TStrings;
const Snapshot: String = ''; const LeaseId: String = '';
ResponseInfo: TCloudResponseInfo = nil): boolean;
/// <summary>Sets the given metadata onto the specified blob</summary>
/// <remarks>LeaseId should only be something other than empty string if the blob is locked.
/// This replaces the full set of metadata currently on the blob, it doesn't append to it.
/// Updating the metadata of a snapshot is not supported.
/// </remarks>
/// <param name="ContainerName">The name of the container the blob is in</param>
/// <param name="BlobName">The name of the blob to set the metadata for</param>
/// <param name="Metadata">The metadata to set.</param>
/// <param name="LeaseId">The LeaseId, required if the blob is locked</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the call executes successfully, false otherwise</returns>
function SetBlobMetadata(ContainerName, BlobName: String; Metadata: TStrings; LeaseId: String = '';
ResponseInfo: TCloudResponseInfo = nil): boolean;
/// <summary>Gets the properties for a given blob</summary>
/// <remarks>LeaseId is only required if it is the blob (not a snapshot) you are interested in,
/// and if that blob is currently locked. In no other situation should you specify a value
/// other than empty string for LeaseId, otherwise the request will fail.
/// </remarks>
/// <param name="ContainerName">The name of the container the blob is in</param>
/// <param name="BlobName">The name of the blob to get the properties for</param>
/// <param name="Properties">The returned properties, or nil if the request fails</param>
/// <param name="Snapshot">The snapshot identifier, if you are interested in a snapshot of the blob</param>
/// <param name="LeaseId">The LeaseId, required if the blob is locked</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the call executes successfully, false otherwise</returns>
function GetBlobProperties(ContainerName, BlobName: String; out Properties: TStrings;
const Snapshot: String = ''; const LeaseId: String = '';
ResponseInfo: TCloudResponseInfo = nil): boolean; overload;
/// <summary>Gets the properties and metadata for a given blob</summary>
/// <remarks>LeaseId is only required if it is the blob (not a snapshot) you are interested in,
/// and if that blob is currently locked. In no other situation should you specify a value
/// other than empty string for LeaseId, otherwise the request will fail.
/// </remarks>
/// <param name="ContainerName">The name of the container the blob is in</param>
/// <param name="BlobName">The name of the blob to get the properties for</param>
/// <param name="Properties">The returned properties, or nil if the request fails</param>
/// <param name="Metadata">The returned metadata, or nil if the request fails</param>
/// <param name="Snapshot">The snapshot identifier, if you are interested in a snapshot of the blob</param>
/// <param name="LeaseId">The LeaseId, required if the blob is locked</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the call executes successfully, false otherwise</returns>
function GetBlobProperties(ContainerName, BlobName: String; out Properties: TStrings;
out Metadata: TStrings;
const Snapshot: String = ''; const LeaseId: String = '';
ResponseInfo: TCloudResponseInfo = nil): boolean; overload;
/// <summary>Sets the given properties onto the specified blob</summary>
/// <remarks>The supported properties are:
/// x-ms-blob-cache-control,
/// x-ms-blob-content-type,
/// x-ms-blob-content-md5,
/// x-ms-blob-content-encoding,
/// x-ms-blob-content-language.
/// For Page Blobs, these are also supported:
/// x-ms-blob-content-length,
/// x-ms-sequence-number-action (max, update, increment)
/// x-ms-blob-sequence-number (unless x-ms-sequence-number-action = increment).
/// When issuing a GetBlobProperties request, the names of the properties are different:
/// Cache-Control,
/// Content-Type,
/// Content-MD5,
/// Content-Encoding,
/// Content-Language.
/// Properties passed in will be given the 'x-ms-blob-' prefix if it is missing. All other
/// properties will be ignored.
/// LeaseId should only be something other than empty string if the blob is locked.
/// This replaces the full set of metadata currently on the blob, it doesn't append to it.
/// Updating the metadata of a snapshot is not supported.
///
/// The x-ms-blob-content-length property can be set to change the "MaximumSize" value specified
/// when 'PutPageBlob' was executed.
///
/// The x-ms-sequence-number-action can be one of 'max', 'update', 'increment'.
/// 'max': Use the largest integer, either the one specified with 'x-ms-blob-sequence-number'
/// or the one already existing on the server.
/// 'update': Replace the value of 'x-ms-blob-sequence-number' on the server with this one.
/// 'increment': Increment the server's value of 'x-ms-blob-sequence-number' by one. Do not
/// specify the 'x-ms-blob-sequence-number' header in this request.
/// </remarks>
/// <param name="ContainerName">The name of the container the blob is in</param>
/// <param name="BlobName">The name of the blob to set the properties for</param>
/// <param name="Properties">The properties to set.</param>
/// <param name="LeaseId">The LeaseId, required if the blob is locked</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the call executes successfully, false otherwise</returns>
function SetBlobProperties(ContainerName, BlobName: String; Properties: TStrings;
const LeaseId: String = '';
ResponseInfo: TCloudResponseInfo = nil): boolean;
/// <summary>Deletes the specified blob, or deletes all of its snapshots.</summary>
/// <remarks>Deletes the specified blob if 'OnlySnapshots' is False, or deletes
/// only the blob's snapshots if 'SnapShot' is true.
/// </remarks>
/// <param name="ContainerName">The name of the container the blob is in</param>
/// <param name="BlobName">The name of the blob to delete</param>
/// <param name="OnlySnapshots">True to delete all of the blob's snapshots, but not the blob.</param>
/// <param name="LeaseId">The LeaseId, required if the blob is locked</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the blob is deleted successfully, false otherwise</returns>
function DeleteBlob(ContainerName, BlobName: String; OnlySnapshots: Boolean = False;
LeaseId: String = '';
ResponseInfo: TCloudResponseInfo = nil): boolean;
/// <summary>Deletes the specified snapshot of then given blob.</summary>
/// <remarks>Deletes one specific snapshot of the specified blob.
/// To delete all snapshots, or the blob itself, call DeleteBlob.
/// </remarks>
/// <param name="ContainerName">The name of the container the blob is in</param>
/// <param name="BlobName">The name of the blob to delete</param>
/// <param name="SnapShot">The snapshot to delete</param>
/// <param name="LeaseId">The LeaseId, required if the blob is locked</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the blob is deleted successfully, false otherwise</returns>
function DeleteBlobSnapshot(ContainerName, BlobName: String; SnapShot: String;
LeaseId: String = '';
ResponseInfo: TCloudResponseInfo = nil): boolean;
/// <summary>Downloads the given blob, writing its content into the provided stream.</summary>
/// <param name="ContainerName">The name of the container the blob is in</param>
/// <param name="BlobName">The name of the blob to download</param>
/// <param name="BlobStream">The stream to write the blob content into</param>
/// <param name="LeaseId">The lease Id, required if the blob is locked</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the task was successful, false otherwise</returns>
function GetBlob(ContainerName, BlobName: String; BlobStream: TStream;
const LeaseId: String = ''; ResponseInfo: TCloudResponseInfo = nil): boolean; overload;
/// <summary>Downloads the given blob, writing its content into the provided stream.</summary>
/// <remarks>This call also returns the blob's properties and metadata</remarks>
/// <param name="ContainerName">The name of the container the blob is in</param>
/// <param name="BlobName">The name of the blob to download</param>
/// <param name="BlobStream">The stream to write the blob content into</param>
/// <param name="Properties">The blob's property name/value pairs</param>
/// <param name="Metadata">The blob's metadata name/value pairs</param>
/// <param name="LeaseId">The lease Id, required if the blob is locked</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the task was successful, false otherwise</returns>
function GetBlob(ContainerName, BlobName: String; BlobStream: TStream;
out Properties, Metadata: TStrings; const LeaseId: String = '';
ResponseInfo: TCloudResponseInfo = nil): boolean; overload;
/// <summary>Downloads the given blob, writing its content into the provided stream.</summary>
/// <remarks>You can request only a range of the blob to be returned by specifying values
/// for StartByte and EndByte. If you specify a range, you can also set GetAsHash
/// to True, which will return the MD5 hash of the range's content, instead of the
/// content itself. Note that you can only return the hash for a range, and not the
/// full content.
/// </remarks>
/// <param name="ContainerName">The name of the container the blob is in</param>
/// <param name="BlobName">The name of the blob to download</param>
/// <param name="BlobStream">The stream to write the blob content into</param>
/// <param name="StartByte">The starting byte index</param>
/// <param name="EndByte">The ending byte index, or 0 if you don't want a range of the blob</param>
/// <param name="GetAsHash">True, if EndByte greater than Start byte, returns content as MD5 hash</param>
/// <param name="LeaseId">The lease Id, required if the blob is locked</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the task was successful, false otherwise</returns>
function GetBlob(ContainerName, BlobName: String; BlobStream: TStream;
StartByte: int64; EndByte: int64; GetAsHash: boolean = False;
const LeaseId: String = ''; ResponseInfo: TCloudResponseInfo = nil): boolean; overload;
/// <summary>Downloads the given blob, writing its content into the provided stream.</summary>
/// <remarks>This call also returns the blob's properties and metadata.
/// You can request only a range of the blob to be returned by specifying values
/// for StartByte and EndByte. If you specify a range, you can also set GetAsHash
/// to True, which will return the MD5 hash of the range's content, instead of the
/// content itself. Note that you can only return the hash for a range, and not the
/// full content.
/// </remarks>
/// <param name="ContainerName">The name of the container the blob is in</param>
/// <param name="BlobName">The name of the blob to download</param>
/// <param name="BlobStream">The stream to write the blob content into</param>
/// <param name="Properties">The blob's property name/value pairs</param>
/// <param name="Metadata">The blob's metadata name/value pairs</param>
/// <param name="StartByte">The starting byte index</param>
/// <param name="EndByte">The ending byte index, or 0 if you don't want a range of the blob</param>
/// <param name="GetAsHash">True, if EndByte greater than Start byte, returns content as MD5 hash</param>
/// <param name="LeaseId">The lease Id, required if the blob is locked</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the task was successful, false otherwise</returns>
function GetBlob(ContainerName, BlobName: String; BlobStream: TStream;
out Properties, Metadata: TStrings;
StartByte: int64; EndByte: int64; GetAsHash: boolean = False;
const LeaseId: String = ''; ResponseInfo: TCloudResponseInfo = nil): boolean; overload;
/// <summary>Downloads the given blob snapshot, writing its content into the provided stream.</summary>
/// <param name="ContainerName">The name of the container the blob is in</param>
/// <param name="BlobName">The name of the blob the snapshot is for</param>
/// <param name="Snapshot">The snapshot to get</param>
/// <param name="SnapshotStream">The stream to write the snapshot content into</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the task was successful, false otherwise</returns>
function GetBlobSnapshot(ContainerName, BlobName, Snapshot: String; SnapshotStream: TStream;
ResponseInfo: TCloudResponseInfo = nil): boolean; overload;
/// <summary>Downloads the given snapshot, writing its content into the provided stream.</summary>
/// <remarks>This call also returns the snapshot's properties and metadata</remarks>
/// <param name="ContainerName">The name of the container the blob is in</param>
/// <param name="BlobName">The name of the blob the snapshot is for</param>
/// <param name="Snapshot">The snapshot to get</param>
/// <param name="SnapshotStream">The stream to write the snapshot content into</param>
/// <param name="Properties">The snapshot's property name/value pairs</param>
/// <param name="Metadata">The snapshot's metadata name/value pairs</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the task was successful, false otherwise</returns>
function GetBlobSnapshot(ContainerName, BlobName, Snapshot: String; SnapshotStream: TStream;
out Properties, Metadata: TStrings;
ResponseInfo: TCloudResponseInfo = nil): boolean; overload;
/// <summary>Downloads the given snapshot, writing its content into the provided stream.</summary>
/// <param name="ContainerName">The name of the container the blob is in</param>
/// <param name="BlobName">The name of the blob the snapshot is for</param>
/// <param name="Snapshot">The snapshot to get</param>
/// <param name="SnapshotStream">The stream to write the snapshot content into</param>
/// <param name="StartByte">The starting byte index</param>
/// <param name="EndByte">The ending byte index, or 0 if you don't want a range of the snapshot</param>
/// <param name="GetAsHash">True, if EndByte greater than Start byte, returns content as MD5 hash</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the task was successful, false otherwise</returns>
function GetBlobSnapshot(ContainerName, BlobName, Snapshot: String; SnapshotStream: TStream;
StartByte: int64 = 0; EndByte: int64 = 0;
GetAsHash: boolean = False;
ResponseInfo: TCloudResponseInfo = nil): boolean; overload;
/// <summary>Downloads the given snapshot, writing its content into the provided stream.</summary>
/// <param name="ContainerName">The name of the container the blob is in</param>
/// <param name="BlobName">The name of the blob the snapshot is for</param>
/// <param name="Snapshot">The snapshot to get</param>
/// <param name="SnapshotStream">The stream to write the snapshot content into</param>
/// <param name="Properties">The snapshot's property name/value pairs</param>
/// <param name="Metadata">The snapshot's metadata name/value pairs</param>
/// <param name="StartByte">The starting byte index</param>
/// <param name="EndByte">The ending byte index, or 0 if you don't want a range of the snapshot</param>
/// <param name="GetAsHash">True, if EndByte greater than Start byte, returns content as MD5 hash</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the task was successful, false otherwise</returns>
function GetBlobSnapshot(ContainerName, BlobName, Snapshot: String; SnapshotStream: TStream;
out Properties, Metadata: TStrings;
StartByte: int64 = 0; EndByte: int64 = 0;
GetAsHash: boolean = False;
ResponseInfo: TCloudResponseInfo = nil): boolean; overload;
/// <summary>Copies the specified blob to the given target location.</summary>
/// <remarks>If a blob exists at the target location, the content will be replaced.
/// If metadata is specified, then the target blob will have that metadata,
/// otherwise, it will have the metadata that exists on the source blob.
/// </remarks>
/// <param name="TargetContainerName">The container to put the copied blob into</param>
/// <param name="TargetBlobName">The name of the resulting blob</param>
/// <param name="SourceContainerName">The container the blob being copied is in</param>
/// <param name="SourceBlobName">The name of the blob being copied</param>
/// <param name="TargetLeaseId">The lease Id, required if the target blob exists already and is locked.</param>
/// <param name="Metadata">The optional metadata to use on the target, instead of the source's</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the copy was successful, false otherwise.</returns>
function CopyBlob(TargetContainerName, TargetBlobName, SourceContainerName, SourceBlobName: String;
const TargetLeaseId: String = ''; Metadata: TStrings = nil;
ResponseInfo: TCloudResponseInfo = nil): boolean; overload;
/// <summary>Copies the specified blob to the given target location.</summary>
/// <remarks>If a blob exists at the target location, the content will be replaced.
/// If metadata is specified, then the target blob will have that metadata,
/// otherwise, it will have the metadata that exists on the source blob.
/// </remarks>
/// <param name="TargetContainerName">The container to put the copied blob into</param>
/// <param name="TargetBlobName">The name of the resulting blob</param>
/// <param name="SourceContainerName">The container the blob being copied is in</param>
/// <param name="SourceBlobName">The name of the blob being copied</param>
/// <param name="CopyConditionals">The conditions to meet in order to do the copy</param>
/// <param name="TargetLeaseId">The lease Id, required if the target blob exists already and is locked.</param>
/// <param name="Metadata">The optional metadata to use on the target, instead of the source's</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the copy was successful, false otherwise.</returns>
function CopyBlob(TargetContainerName, TargetBlobName, SourceContainerName, SourceBlobName: String;
CopyConditionals: TBlobActionConditional;
const TargetLeaseId: String = ''; Metadata: TStrings = nil;
ResponseInfo: TCloudResponseInfo = nil): boolean; overload;
/// <summary>Copies the specified snapshot into the target blob location.</summary>
/// <remarks>If a blob exists at the target location, the content will be replaced.
/// If metadata is specified, then the target blob will have that metadata,
/// otherwise, it will have the metadata that exists on the source snapshot.
/// </remarks>
/// <param name="TargetContainerName">The container to put the copied blob into</param>
/// <param name="TargetBlobName">The name of the resulting blob</param>
/// <param name="SourceContainerName">The container the blob being copied is in</param>
/// <param name="SourceBlobName">The name of the blob owning the snapshot being copied</param>
/// <param name="SourceSnapshot">The blob's snapshot to copy</param>
/// <param name="Metadata">The optional metadata to use on the target, instead of the source's</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the copy was successful, false otherwise.</returns>
function CopySnapshotToBlob(TargetContainerName, TargetBlobName, SourceContainerName, SourceBlobName: String;
const SourceSnapshot: String; Metadata: TStrings = nil;
ResponseInfo: TCloudResponseInfo = nil): boolean; overload;
/// <summary>Copies the specified snapshot into the target blob location.</summary>
/// <remarks>If a blob exists at the target location, the content will be replaced.
/// If metadata is specified, then the target blob will have that metadata,
/// otherwise, it will have the metadata that exists on the source snapshot.
/// </remarks>
/// <param name="TargetContainerName">The container to put the copied blob into</param>
/// <param name="TargetBlobName">The name of the resulting blob</param>
/// <param name="SourceContainerName">The container the blob being copied is in</param>
/// <param name="SourceBlobName">The name of the blob owning the snapshot being copied</param>
/// <param name="CopyConditionals">The conditions to meet in order to do the copy</param>
/// <param name="SourceSnapshot">The blob's snapshot to copy</param>
/// <param name="Metadata">The optional metadata to use on the target, instead of the source's</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the copy was successful, false otherwise.</returns>
function CopySnapshotToBlob(TargetContainerName, TargetBlobName, SourceContainerName, SourceBlobName: String;
const SourceSnapshot: String;
CopyConditionals: TBlobActionConditional;
Metadata: TStrings = nil;
ResponseInfo: TCloudResponseInfo = nil): boolean; overload;
/// <summary>Creates a new snapshot of the specified blob.</summary>
/// <remarks>Set Metadata to nil or an empty list unless you want the snapshot's metadata
/// to be that, instead of the metadata on the blob having the snapshot taken.
/// </remarks>
/// <param name="ContainerName">The name of the container the blob is in.</param>
/// <param name="BlobName">The name of the blob to create a snapshot for</param>
/// <param name="SnapshotId">The resulting Snapshot Id, if successfully created</param>
/// <param name="LeaseId">The lease Id, required if the blob is locked</param>
/// <param name="Metadata">The metadata to set onto the snapshot, instead of the blob's</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns></returns>
function SnapshotBlob(ContainerName, BlobName: String; out SnapshotId: String; const LeaseId: String = '';
Metadata: TStrings = nil; ResponseInfo: TCloudResponseInfo = nil): boolean; overload;
/// <summary>Conditionally creates a new snapshot of the specified blob.</summary>
/// <remarks>The snapshot is only created if the conditions specified in SnapshotConditionals are met.
/// Only some of the conditionals of the TBlobActionConditional instance are used.
/// For example, none which have field names beginning with 'IfSource' are used here.
/// Set Metadata to nil or an empty list unless you want the snapshot's metadata
/// to be that, instead of the metadata on the blob having the snapshot taken.
/// </remarks>
/// <param name="ContainerName">The name of the container the blob is in.</param>
/// <param name="BlobName">The name of the blob to create a snapshot for</param>
/// <param name="SnapshotConditionals">The conditions to meet in order to create the snapshot</param>
/// <param name="SnapshotId">The resulting Snapshot Id, if successfully created</param>
/// <param name="LeaseId">The lease Id, required if the blob is locked</param>
/// <param name="Metadata">The metadata to set onto the snapshot, instead of the blob's</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns></returns>
function SnapshotBlob(ContainerName, BlobName: String;
SnapshotConditionals: TBlobActionConditional;
out SnapshotId: String;
const LeaseId: String = '';
Metadata: TStrings = nil;
ResponseInfo: TCloudResponseInfo = nil): boolean; overload;
/// <summary>Creates a new block to be committed as part of a blob.</summary>
/// <remarks>A block may be up to 4 MB in size.
/// BlockId must be a base 64 encoded string, which was less than or equal to 64 bytes
/// in size before it was encoded.
/// For a given blob, all block IDs must be the same length.
/// After you have uploaded a set of blocks, you can create or update the blob
/// on the server from this set by calling PutBlockList. Until then, the blob does
/// not contain this block as part of its content.
/// If you call Put Block on a blob that does not yet exist, a new uncommitted
/// block blob is created with a content length of 0.
/// If you call Put Block using a BlockId of an existing uncommitted block,
/// the content will be replaced.
/// If PutBlockList isn't called within a week, all uncommitted blocks will be deleted.
/// After calling PutBlockList, any uncommitted blocks not included in the list
/// will be deleted.
/// </remarks>
/// <param name="ContainerName">The name of the container the blob is in.</param>
/// <param name="BlobName">The name of the blob to upload the block for</param>
/// <param name="BlockId">The Id to that uniquely identifies the block</param>
/// <param name="Content">The block's content in bytes</param>
/// <param name="ContentMD5">An optional MD5 hash of the content, for verification purposes.</param>
/// <param name="LeaseId">The lease Id, required if the blob is locked</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if successful, false otherwise</returns>
function PutBlock(ContainerName, BlobName: String; const BlockId: String; Content: TBytes;
const ContentMD5: String = ''; const LeaseId: String = '';
ResponseInfo: TCloudResponseInfo = nil): boolean;
/// <summary>Writes content to a range with a page blob.</summary>
/// <remarks>The StartPage is zero-indexed, and maps to the first page in a range of 1 or more pages
/// to create or modify the content for.
/// Each page is exactly 512 bytes, so when passing in the Content, the length must be
/// (512 * PageCount). If the content is not that long, be sure to pad with zeros.
/// </remarks>
/// <param name="ContainerName">The name of the container the blob is in.</param>
/// <param name="BlobName">The name of the page blob</param>
/// <param name="Content">The content to add. Must be evenly divisible by 512. Pad with zeros if needed.</param>
/// <param name="StartPage">The zero-based index of the first page this content applies to</param>
/// <param name="PageCount">The number of (512 byte) pages this content spans</param>
/// <param name="ContentMD5">The optional MD5 hash of the content being sent, for verifying integrity.</param>
/// <param name="LeaseId">The lease Id, required if the blob is locked</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if successful, false otherwise</returns>
function PutPage(ContainerName, BlobName: String; Content: TBytes;
StartPage, PageCount: Integer;
const LeaseId: String = '';
const ContentMD5: String = '';
ResponseInfo: TCloudResponseInfo = nil): boolean; overload;
/// <summary>Writes content to a range with a page blob.</summary>
/// <remarks>The StartPage is zero-indexed, and maps to the first page in a range of 1 or more pages
/// to create or modify the content for.
/// Each page is exactly 512 bytes, so when passing in the Content, the length must be
/// (512 * PageCount). If the content is not that long, be sure to pad with zeros.
/// Supported action conditionals include:
/// IfModifiedSince,
/// IfUnmodifiedSince,
/// IfMatch,
/// IfNoneMatch,
/// if-sequence-number-lte,
/// if-sequence-number-lt,
/// if-sequence-number-eq.
/// </remarks>
/// <param name="ContainerName">The name of the container the blob is in.</param>
/// <param name="BlobName">The name of the page blob</param>
/// <param name="Content">The content to add. Must be evenly divisible by 512. Pad with zeros if needed.</param>
/// <param name="StartPage">The zero-based index of the first page this content applies to</param>
/// <param name="PageCount">The number of (512 byte) pages this content spans</param>
/// <param name="ActionConditional">Conditions that must be met for the action to be executed.</param>
/// <param name="ContentMD5">The optional MD5 hash of the content being sent, for verifying integrity.</param>
/// <param name="LeaseId">The lease Id, required if the blob is locked</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if successful, false otherwise</returns>
function PutPage(ContainerName, BlobName: String; Content: TBytes;
StartPage, PageCount: Integer; ActionConditional: TBlobActionConditional;
const ContentMD5: String = '';
const LeaseId: String = '';
ResponseInfo: TCloudResponseInfo = nil): boolean; overload;
/// <summary>Writes content to a range with a page blob.</summary>
/// <remarks>The StartPage is zero-indexed, and maps to the first page in a range of 1 or more pages
/// to create or modify the content for.
/// The number is pages is calculated dynamically based on the length of the specified content.
/// If the content's length isn't evenly divisible by 512, then it is padded with zeros.
/// Supported action conditionals include:
/// IfModifiedSince,
/// IfUnmodifiedSince,
/// IfMatch,
/// IfNoneMatch,
/// if-sequence-number-lte,
/// if-sequence-number-lt,
/// if-sequence-number-eq.
/// </remarks>
/// <param name="ContainerName">The name of the container the blob is in.</param>
/// <param name="BlobName">The name of the page blob</param>
/// <param name="Content">The content to add. Must be evenly divisible by 512. Pad with zeros if needed.</param>
/// <param name="StartPage">The zero-based index of the first page this content applies to</param>
/// <param name="ActionConditional">Conditions that must be met for the action to be executed.</param>
/// <param name="LeaseId">The lease Id, required if the blob is locked</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if successful, false otherwise</returns>
function PutPage(ContainerName, BlobName: String; Content: TBytes;
StartPage: Integer; ActionConditional: TBlobActionConditional;
const LeaseId: String = '';
ResponseInfo: TCloudResponseInfo = nil): boolean; overload;
/// <summary>Writes content to a range with a page blob.</summary>
/// <remarks>The StartPage is zero-indexed, and maps to the first page in a range of 1 or more pages
/// to create or modify the content for.
/// The number is pages is calculated dynamically based on the length of the specified content.
/// If the content's length isn't evenly divisible by 512, then it is padded with zeros.
/// This must only be called on a page blob that already exists.
/// </remarks>
/// <param name="ContainerName">The name of the container the blob is in.</param>
/// <param name="BlobName">The name of the page blob</param>
/// <param name="Content">The content to add. Must be evenly divisible by 512. Pad with zeros if needed.</param>
/// <param name="StartPage">The zero-based index of the first page this content applies to</param>
/// <param name="LeaseId">The lease Id, required if the blob is locked</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if successful, false otherwise</returns>
function PutPage(ContainerName, BlobName: String; Content: TBytes; StartPage: Integer;
const LeaseId: String = '';
ResponseInfo: TCloudResponseInfo = nil): boolean; overload;
/// <summary>Clears the specified range and releases the spaced used in storage for that range.</summary>
/// <param name="ContainerName">The name of the container the blob is in.</param>
/// <param name="BlobName">The name of the page blob</param>
/// <param name="StartPage">The zero-based index of the first page this action applies to</param>
/// <param name="PageCount">The number of pages this action applies to</param>
/// <param name="LeaseId">The lease Id, required if the blob is locked</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if successful, false otherwise</returns>
function ClearPage(ContainerName, BlobName: String; StartPage, PageCount: Integer;
const LeaseId: String = '';
ResponseInfo: TCloudResponseInfo = nil): boolean; overload;
/// <summary>Clears the specified range and releases the spaced used in storage for that range.</summary>
/// <remarks>Supported action conditionals include:
/// IfModifiedSince,
/// IfUnmodifiedSince,
/// IfMatch,
/// IfNoneMatch,
/// if-sequence-number-lte,
/// if-sequence-number-lt,
/// if-sequence-number-eq.
/// </remarks>
/// <param name="ContainerName">The name of the container the blob is in.</param>
/// <param name="BlobName">The name of the page blob</param>
/// <param name="StartPage">The zero-based index of the first page this action applies to</param>
/// <param name="PageCount">The number of pages this action applies to</param>
/// <param name="ActionConditional">Conditions that must be met for the action to be executed.</param>
/// <param name="LeaseId">The lease Id, required if the blob is locked</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if successful, false otherwise</returns>
function ClearPage(ContainerName, BlobName: String; StartPage, PageCount: Integer;
ActionConditional: TBlobActionConditional;
const LeaseId: String = '';
ResponseInfo: TCloudResponseInfo = nil): boolean; overload;
/// <summary>Specifies the list of blocks to form the blob content from.</summary>
/// <remarks>The list of blocks is used to build the given blob's content. The blocks
/// can either be committed (already part of the blob's content) or uncommitted
/// (uploaded with PutBlock, but not yet included in a PutBlockList call.)
/// Once this call is made, any block not in the block list is permanently deleted.
/// </remarks>
/// <param name="ContainerName">The name of the container the blob is in.</param>
/// <param name="BlobName">The blob to commit the block list for</param>
/// <param name="BlockList">The list of blocks to form the blob's content with</param>
/// <param name="Properties">Optional list of properties to specify on the blob</param>
/// <param name="Metadata">Optional list of metadata to specify on the blob</param>
/// <param name="LeaseId">The lease Id, required if the blob is locked</param>
/// <param name="ContentMD5">The optional MD5 hash of the content being sent, for verifying integrity.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if successful, false otherwise</returns>
function PutBlockList(ContainerName, BlobName: String; BlockList: TList<TAzureBlockListItem>;
Properties: TStrings = nil; Metadata: TStrings = nil;
const LeaseId: String = ''; const ContentMD5: String = '';
ResponseInfo: TCloudResponseInfo = nil): boolean;
/// <summary>Returns the block list for the given blob</summary>
/// <param name="ContainerName">The name of the container the blob is in.</param>
/// <param name="BlobName">The name of the block blob to get the block list for</param>
/// <param name="BlockType">The type of blocks to get. Either committed, uncommitted, or both</param>
/// <param name="SnapShot">The snapshot Id if you want the list of a snapshot instead of the blob</param>
/// <param name="LeaseId">The lease Id, required if the blob is locked</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The XML representation of the block list</returns>
function GetBlockListXML(ContainerName, BlobName: String;
BlockType: TAzureQueryIncludeBlockType = aqbtCommitted;
const SnapShot: String = ''; const LeaseId: String = '';
ResponseInfo: TCloudResponseInfo = nil): String;
/// <summary>Returns the block list for the given blob</summary>
/// <param name="ContainerName">The name of the container the blob is in.</param>
/// <param name="BlobName">The name of the block blob to get the block list for</param>
/// <param name="BlockType">The type of blocks to get. Either committed, uncommitted, or both</param>
/// <param name="SnapShot">The snapshot Id if you want the list of a snapshot instead of the blob</param>
/// <param name="LeaseId">The lease Id, required if the blob is locked</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The list of blocks for the given blob or snapshot</returns>
function GetBlockList(ContainerName, BlobName: String;
BlockType: TAzureQueryIncludeBlockType = aqbtCommitted;
const SnapShot: String = ''; const LeaseId: String = '';
ResponseInfo: TCloudResponseInfo = nil): TList<TAzureBlockListItem>;
/// <summary>Returns the page regions for the given page blob.</summary>
/// <remarks>This takes in a range. If the bytes are set to zero the whole page blob will
/// be analyzed, otherwise only the given range will be analyzed.
/// What is returns is a list of valid page ranges (start byte / end byte pairs).
/// </remarks>
/// <param name="ContainerName">The name of the container the blob is in.</param>
/// <param name="BlobName">The name of the page blob</param>
/// <param name="StartByte">The start byte in the range to check for valid pages.</param>
/// <param name="EndByte">The end byte in the range to check for valid pages.</param>
/// <param name="Snapshot">The optional snapshot Id if you want to check one of the blob's snapshots</param>
/// <param name="LeaseId">The lease Id, required if the blob is locked</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The XML representation of the returned valid page ranges</returns>
function GetPageRegionsXML(ContainerName, BlobName: String; StartByte, EndByte: Int64;
const Snapshot: String = ''; const LeaseId: String = '';
ResponseInfo: TCloudResponseInfo = nil): String; overload;
/// <summary>Returns the page regions for the given page blob.</summary>
/// <remarks>What is returns is a list of valid page ranges (start byte / end byte pairs).
/// Same as calling the version of GetPageRegionsXML with a Range, where the StartByte
/// and EndByte of the Range are set to zero.
/// </remarks>
/// <param name="ContainerName">The name of the container the blob is in.</param>
/// <param name="BlobName">The name of the page blob</param>
/// <param name="Snapshot">The optional snapshot Id if you want to check one of the blob's snapshots</param>
/// <param name="LeaseId">The lease Id, required if the blob is locked</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The XML representation of the returned valid page ranges</returns>
function GetPageRegionsXML(ContainerName, BlobName: String;
const Snapshot: String = ''; const LeaseId: String = '';
ResponseInfo: TCloudResponseInfo = nil): String; overload;
/// <summary>Returns the page regions for the given page blob.</summary>
/// <remarks>This takes in a range. If the bytes are set to zero the whole page blob will
/// be analyzed, otherwise only the given range will be analyzed.
/// What is returns is a list of valid page ranges (start byte / end byte pairs).
///
/// x-ms-blob-content-length is the name of one of the header values returned,
/// which can be read using the ResponseInfo parameter.
/// </remarks>
/// <param name="ContainerName">The name of the container the blob is in.</param>
/// <param name="BlobName">The name of the page blob</param>
/// <param name="StartByte">The start byte in the range to check for valid pages.</param>
/// <param name="EndByte">The end byte in the range to check for valid pages.</param>
/// <param name="Snapshot">The optional snapshot Id if you want to check one of the blob's snapshots</param>
/// <param name="LeaseId">The lease Id, required if the blob is locked</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The list of valid page ranges</returns>
function GetPageRegions(ContainerName, BlobName: String; StartByte, EndByte: Int64;
const Snapshot: String = ''; const LeaseId: String = '';
ResponseInfo: TCloudResponseInfo = nil): TList<TAzureBlobPageRange>; overload;
/// <summary>Returns the page regions for the given page blob.</summary>
/// <remarks>The whole page blob will be analyzed.
/// What is returns is a list of valid page ranges (start byte / end byte pairs).
/// </remarks>
/// <param name="ContainerName">The name of the container the blob is in.</param>
/// <param name="BlobName">The name of the page blob</param>
/// <param name="Snapshot">The optional snapshot Id if you want to check one of the blob's snapshots</param>
/// <param name="LeaseId">The lease Id, required if the blob is locked</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The list of valid page ranges</returns>
function GetPageRegions(ContainerName, BlobName: String;
const Snapshot: String = ''; const LeaseId: String = '';
ResponseInfo: TCloudResponseInfo = nil): TList<TAzureBlobPageRange>; overload;
end;
const
/// <summary>The root container's name for the blob service.</summary>
ROOT_CONTAINER = '$root';
implementation
uses System.DateUtils, System.StrUtils, Xml.XMLDoc;
const
NODE_TABLE = 'entry';
NODE_TABLE_CONTENT = 'content';
NODE_PROPERTIES = 'm:properties';
NODE_TABLE_NAME = 'd:TableName';
NODE_QUEUES = 'Queues';
NODE_QUEUE = 'Queue';
NODE_QUEUE_NAME = 'Name';
NODE_QUEUE_URL = 'Url';
DT_XML_PREFIX = 'Edm.';
DT_BINARY = 'Binary';
DT_BOOLEAN = 'Boolean';
DT_DATETIME = 'DateTime';
DT_DOUBLE = 'Double';
DT_GUID = 'Guid';
DT_INT32 = 'Int32';
DT_INT64 = 'Int64';
DT_STRING = 'String';
function GetRowFromConentNode(ContentNode: IXMLNode): TCloudTableRow;
var
PropertiesNode: IXMLNode;
PropertyNode: IXMLNode;
PropName: String;
Aux: Integer;
Row: TCloudTableRow;
Column: TCloudTableColumn;
begin
if (ContentNode = nil) or (ContentNode.NodeName <> NODE_TABLE_CONTENT) then
Exit(nil);
Result := nil;
if (ContentNode.HasChildNodes) then
begin
PropertiesNode := GetFirstMatchingChildNode(ContentNode, NODE_PROPERTIES);
if (PropertiesNode <> nil) and (PropertiesNode.HasChildNodes) then
begin
PropertyNode := PropertiesNode.ChildNodes.First;
Row := TCloudTableRow.Create;
while PropertyNode <> nil do
begin
try
PropName := PropertyNode.NodeName;
Aux := AnsiPos(':', PropName);
if Aux > -1 then
PropName := Copy(PropName, Aux + 1);
Column := TCloudTableColumn.Create;
Column.Name := PropName;
Column.Value := PropertyNode.Text;
if PropertyNode.HasAttribute('m:type') then
Column.DataType := PropertyNode.Attributes['m:type'];
Row.Columns.Add(Column);
except
break;
end;
PropertyNode := PropertyNode.NextSibling;
end;
Result := Row;
end;
end;
end;
{ TAzureConnectionInfo }
constructor TAzureConnectionInfo.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FUseDevelopmentStorage := false;
FUseDefaultEndpoints := true;
FProtocol := 'http';
end;
function TAzureConnectionInfo.GetAccountKey: String;
begin
if FUseDevelopmentStorage then
Exit('Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==');
Exit(FAccountKey);
end;
function TAzureConnectionInfo.GetAccountName: String;
begin
if FUseDevelopmentStorage then
Exit('devstoreaccount1');
Exit(FAccountName);
end;
function TAzureConnectionInfo.GetBlobEndpoint: String;
begin
if UseDefaultEndpoints and (not UseDevelopmentStorage) then
Exit(Format('%s.%s.core.windows.net', [AccountName, 'blob']));
Exit(FBlobEndpoint);
end;
function TAzureConnectionInfo.GetQueueEndpoint: String;
begin
if UseDefaultEndpoints and (not UseDevelopmentStorage) then
Exit(Format('%s.%s.core.windows.net', [AccountName, 'queue']));
Exit(FQueueEndpoint);
end;
function TAzureConnectionInfo.GetTableEndpoint: String;
begin
if UseDefaultEndpoints and (not UseDevelopmentStorage) then
Exit(Format('%s.%s.core.windows.net', [AccountName, 'table']));
Exit(FTableEndpoint);
end;
function TAzureConnectionInfo.BlobURL: String;
begin
Result := ServiceURL('blob', BlobEndpoint);
end;
function TAzureConnectionInfo.TableURL: String;
begin
Result := ServiceURL('table', TableEndpoint);
end;
function TAzureConnectionInfo.QueueURL: String;
begin
Result := ServiceURL('queue', QueueEndpoint);
end;
function TAzureConnectionInfo.ServiceURL(const ServiceType, ServiceEndpoint: String): String;
var
url: String;
begin
if UseDevelopmentStorage then
url := '127.0.0.1:10001/devstoreaccount1'
else if UseDefaultEndpoints then
url := Format('%s.%s.core.windows.net', [AccountName, ServiceType])
else
url := ServiceEndpoint;
Result := Format('%s://%s', [Protocol, url]);
end;
procedure TAzureConnectionInfo.SetUseDevelopmentStorage(use: boolean);
begin
FUseDevelopmentStorage := use;
end;
{ TAzureAuthentication }
procedure TAzureAuthentication.AssignKey(const AccountKey: String);
begin
FSHAKey := DecodeBytes64(FConnectionInfo.AccountKey);
end;
constructor TAzureAuthentication.Create(ConnectionInfo: TAzureConnectionInfo);
begin
inherited Create(ConnectionInfo, 'SharedKey'); {do not localize}
end;
{ TAzureService }
constructor TAzureService.Create(ConnectionInfo: TAzureConnectionInfo);
begin
inherited Create(ConnectionInfo, TAzureAuthentication.Create(ConnectionInfo));
FRequiredHeaderNames := nil;
//characters to use when building the query parameter part of the
//CanonicalizedResource part of the 'stringToSign'
FQueryStartChar := #10;
FQueryParamKeyValueSeparator := ':';
FQueryParamSeparator := #10;
end;
destructor TAzureService.Destroy;
begin
FreeAndNil(FRequiredHeaderNames);
inherited;
end;
function TAzureService.GetCanonicalizedHeaderPrefix: String;
begin
Result := 'x-ms-'; {do not localize}
end;
function TAzureService.GetConnectionInfo: TAzureConnectionInfo;
begin
Result := TAzureConnectionInfo(FConnectionInfo);
end;
function TAzureService.GetRequiredHeaderNames(out InstanceOwner: Boolean): TStrings;
begin
InstanceOwner := False;
//Required headers shared by Queue and Blob service. These go into the 'String To Sign' as just values
if FRequiredHeaderNames = nil then
begin
//http://msdn.microsoft.com/en-us/library/dd179428.aspx
FRequiredHeaderNames := TStringList.Create;
if GetConnectionInfo.UseDevelopmentStorage then
begin
FRequiredHeaderNames.Add('content-md5');
FRequiredHeaderNames.Add('content-type');
FRequiredHeaderNames.Add('date');
end
else
begin
FRequiredHeaderNames.Add('content-encoding');
FRequiredHeaderNames.Add('content-language');
FRequiredHeaderNames.Add('content-length');
FRequiredHeaderNames.Add('content-md5');
FRequiredHeaderNames.Add('content-type');
FRequiredHeaderNames.Add('date');
FRequiredHeaderNames.Add('if-modified-since');
FRequiredHeaderNames.Add('if-match');
FRequiredHeaderNames.Add('if-none-match');
FRequiredHeaderNames.Add('if-unmodified-since');
FRequiredHeaderNames.Add('range');
end;
end;
Result := FRequiredHeaderNames;
end;
procedure TAzureService.PopulateDateHeader(Headers: TStrings; AddRegularDateHeader: Boolean);
var
msDate: String;
begin
if Headers <> nil then
begin
msDate := XMsDate;
if AddRegularDateHeader then
Headers.Values['date'] := msDate;
Headers.Values['x-ms-date'] := msDate;
end;
end;
procedure TAzureService.URLEncodeQueryParams(const ForURL: Boolean; var ParamName, ParamValue: String);
begin
if ForURL then
inherited;
end;
function TAzureService.XMsDate: String;
begin
Result := FormatDateTime('ddd, dd mmm yyyy hh:nn:ss "GMT"',
TTimeZone.Local.ToUniversalTime(Now),
TFormatSettings.Create('en-US'));
end;
{ TAzureTableService }
procedure TAzureTableService.AddTableVersionHeaders(Headers: TStrings);
begin
if Headers <> nil then
begin
Headers.Values['x-ms-version'] := '2009-09-19';
Headers.Values['DataServiceVersion'] := '1.0;NetFx';
Headers.Values['MaxDataServiceVersion'] := '1.0;NetFx';
end;
end;
constructor TAzureTableService.Create(ConnectionInfo: TAzureConnectionInfo);
begin
inherited Create(ConnectionInfo);
FUseCanonicalizedHeaders := False;
end;
function TAzureTableService.GetInsertEntityXML(Entity: TCloudTableRow): String;
var
I, Count: Integer;
Col: TCloudTableColumn;
begin
Result :=
Format('<?xml version="1.0" encoding="utf-8" standalone="yes"?>' +
'<entry xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" ' +
'xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" ' +
'xmlns="http://www.w3.org/2005/Atom">' +
'<title />' +
'<updated>%s</updated>' +
'<author><name /></author>' +
'<id />' +
'<content type="application/xml">' +
'<m:properties>',
[XMLEscape(UpdatedDate)]);
Count := Entity.Columns.Count;
for I := 0 to Count - 1 do
begin
Col := Entity.Columns[I];
if (Length(Col.DataType) > 0) then
Result := Result + Format('<d:%s m:type="%s">%s</d:%s>',
[Col.Name, Col.DataType, XMLEscape(Col.Value), Col.Name])
else
Result := Result + Format('<d:%s>%s</d:%s>', [Col.Name, XMLEscape(Col.Value), Col.Name]);
end;
Result := Result + '</m:properties></content></entry>';
end;
function TAzureTableService.GetRequiredHeaderNames(out InstanceOwner: Boolean): TStrings;
begin
InstanceOwner := False;
if FRequiredHeaderNames = nil then
begin
//http://msdn.microsoft.com/en-us/library/dd179428.aspx
FRequiredHeaderNames := TStringList.Create;
FRequiredHeaderNames.Add('content-md5');
FRequiredHeaderNames.Add('content-type');
FRequiredHeaderNames.Add('date');
end;
Result := FRequiredHeaderNames;
end;
function TAzureTableService.GetTablesQueryPrefix(Headers: TStrings; TableName: String): String;
begin
if GetConnectionInfo.UseDevelopmentStorage then
Result := Format('/%s/%s/%s', [GetConnectionInfo.AccountName, GetConnectionInfo.AccountName, TableName])
else
begin
AddTableVersionHeaders(Headers);
Result := Format('/%s/%s', [GetConnectionInfo.AccountName, TableName]);
end;
end;
function TAzureTableService.InsertEntity(const TableName: String; Entity: TCloudTableRow;
ResponseInfo: TCloudResponseInfo): boolean;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
Response: TCloudHTTP;
InputStream : TBytesStream;
FreeResponseInfo: Boolean;
xml: String;
begin
url := Format('%s/%s', [GetConnectionInfo.TableURL, TableName]);
if (Entity = nil) or (URL = EmptyStr) then
Exit(False);
Headers := TStringList.Create;
PopulateDateHeader(Headers);
Headers.Values['Content-Type'] := 'application/atom+xml';
QueryPrefix := GetTablesQueryPrefix(Headers, TableName);
xml := GetInsertEntityXML(Entity);
FreeResponseInfo := ResponseInfo = nil;
if FreeResponseInfo then
ResponseInfo := TCloudResponseInfo.Create;
Response := nil;
InputStream := TBytesStream.Create(TEncoding.UTF8.GetBytes(xml));
try
try
Response := IssuePostRequest(url, Headers, nil, QueryPrefix, ResponseInfo, InputStream);
Result := ResponseInfo.StatusCode = 201;
except
Result := false;
end;
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
InputStream.Free;
if FreeResponseInfo then
ResponseInfo.Free;
end;
end;
function TAzureTableService.MergeEntity(const TableName: String; Entity: TCloudTableRow;
ResponseInfo: TCloudResponseInfo): boolean;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
Response: TCloudHTTP;
InputStream : TBytesStream;
FreeResponseInfo: Boolean;
xml: String;
begin
if not ModifyEntityHelper(TableName, Entity, url, QueryPrefix, Headers) then
Exit(False);
xml := GetInsertEntityXML(Entity);
FreeResponseInfo := False;
if ResponseInfo = nil then
begin
FreeResponseInfo := True;
ResponseInfo := TCloudResponseInfo.Create;
end;
Response := nil;
InputStream := TBytesStream.Create(TEncoding.UTF8.GetBytes(xml));
try
try
Response := IssueMergeRequest(url, Headers, nil, QueryPrefix, ResponseInfo, InputStream);
Result := ResponseInfo.StatusCode = 204;
except
Result := false;
end;
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
InputStream.Free;
if FreeResponseInfo then
ResponseInfo.Free;
end;
end;
function TAzureTableService.ModifyEntityHelper(const TableName: String; const Entity: TCloudTableRow;
out url, QueryPrefix: String;
out Headers: TStringList): boolean;
var
partitionKey, rowKey: String;
begin
if Entity = nil then
Exit(False);
if not (Entity.GetColumnValue('PartitionKey', partitionKey) and
Entity.GetColumnValue('RowKey', rowKey)) then
Exit(False);
Result := True;
url := Format('%s/%s(PartitionKey=''%s'',RowKey=''%s'')',
[GetConnectionInfo.TableURL, TableName, partitionKey, rowKey]);
Headers := TStringList.Create;
PopulateDateHeader(Headers);
Headers.Values['Content-Type'] := 'application/atom+xml';
Headers.Values['If-Match'] := '*';
QueryPrefix := GetTablesQueryPrefix(Headers, TableName);
QueryPrefix := Format('%s(PartitionKey=''%s'',RowKey=''%s'')', [QueryPrefix, partitionKey, rowKey]);
end;
function TAzureTableService.UpdateEntity(const TableName: String; Entity: TCloudTableRow;
ResponseInfo: TCloudResponseInfo): boolean;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
Response: TCloudHTTP;
InputStream : TBytesStream;
FreeResponseInfo: Boolean;
xml: String;
begin
if not ModifyEntityHelper(TableName, Entity, url, QueryPrefix, Headers) then
Exit(False);
xml := GetInsertEntityXML(Entity);
FreeResponseInfo := False;
if ResponseInfo = nil then
begin
FreeResponseInfo := True;
ResponseInfo := TCloudResponseInfo.Create;
end;
Response := nil;
InputStream := TBytesStream.Create(TEncoding.UTF8.GetBytes(xml));
try
try
Response := IssuePutRequest(url, Headers, nil, QueryPrefix, ResponseInfo, InputStream);
Result := ResponseInfo.StatusCode = 204;
except
Result := false;
end;
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
InputStream.Free;
if FreeResponseInfo then
ResponseInfo.Free;
end;
end;
function TAzureTableService.DeleteEntity(const TableName: String; const Entity: TCloudTableRow;
ResponseInfo: TCloudResponseInfo): boolean;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
Response: TCloudHTTP;
begin
if not ModifyEntityHelper(TableName, Entity, url, QueryPrefix, Headers) then
Exit(False);
Response := nil;
try
try
Response := IssueDeleteRequest(url, Headers, nil, QueryPrefix, ResponseInfo);
Result := (Response <> nil) and (Response.ResponseCode = 204);
except
Result := false;
end;
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
end;
end;
function TAzureTableService.CreateTable(const TableName: String;
ResponseInfo: TCloudResponseInfo): boolean;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
Response: TCloudHTTP;
InputStream : TBytesStream;
xml: String;
FreeResponseInfo: Boolean;
begin
url := Format('%s/%s', [GetConnectionInfo.TableURL, 'Tables']);
Headers := TStringList.Create;
PopulateDateHeader(Headers);
Headers.Values['Content-Type'] := 'application/atom+xml';
QueryPrefix := GetTablesQueryPrefix(Headers);
xml := Format('<?xml version="1.0" encoding="utf-8" standalone="yes"?>' +
'<entry xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" ' +
'xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" ' +
'xmlns="http://www.w3.org/2005/Atom">' +
'<title />' +
'<updated>%s</updated>' +
'<author>' +
'<name />' +
'</author>' +
'<content type="application/xml">' +
'<m:properties>' +
'<d:TableName>%s</d:TableName>' +
'</m:properties>' +
'</content>' +
'</entry>',
[XMLEscape(UpdatedDate), XMLEscape(TableName)]);
FreeResponseInfo := False;
if ResponseInfo = nil then
begin
FreeResponseInfo := True;
ResponseInfo := TCloudResponseInfo.Create;
end;
InputStream := TBytesStream.Create(TEncoding.UTF8.GetBytes(xml));
Response := nil;
try
try
Response := IssuePostRequest(url, Headers, nil, QueryPrefix, ResponseInfo, InputStream);
Result := ResponseInfo.StatusCode = 201;
except
Result := false;
end;
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
InputStream.Free;
if FreeResponseInfo then
ResponseInfo.Free;
end;
end;
function TAzureTableService.DeleteTable(const TableName: String; ResponseInfo: TCloudResponseInfo): boolean;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
Response: TCloudHTTP;
FreeResponseInfo: Boolean;
begin
url := Format('%s/Tables(''%s'')', [GetConnectionInfo.TableURL, TableName]);
Headers := TStringList.Create;
PopulateDateHeader(Headers);
Headers.Values['Content-Type'] := 'application/atom+xml';
QueryPrefix := GetTablesQueryPrefix(Headers);
QueryPrefix := Format('%s(''%s'')', [QueryPrefix, TableName]);
FreeResponseInfo := False;
if ResponseInfo = nil then
begin
FreeResponseInfo := True;
ResponseInfo := TCloudResponseInfo.Create;
end;
Response := nil;
try
try
Response := IssueDeleteRequest(url, Headers, nil, QueryPrefix, ResponseInfo);
Result := ResponseInfo.StatusCode = 204;
except
Result := false;
end;
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
if FreeResponseInfo then
ResponseInfo.Free;
end;
end;
function TAzureTableService.QueryTablesXML(const ContinuationToken: String; ResponseInfo: TCloudResponseInfo): String;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
Response: TCloudHTTP;
begin
url := Format('%s/%s', [GetConnectionInfo.TableURL, 'Tables']);
Headers := TStringList.Create;
PopulateDateHeader(Headers);
if ContinuationToken <> EmptyStr then
url := url + Format('?NextTableName=%s', [URLEncode(ContinuationToken)]);
QueryPrefix := GetTablesQueryPrefix(Headers);
Response := nil;
try
Response := IssueGetRequest(url, Headers, nil, QueryPrefix, ResponseInfo, Result);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
end;
end;
function TAzureTableService.UpdatedDate: String;
begin
Result := FormatDateTime('yyyy-mm-dd"T"hh:nn:ss"Z"', TTimeZone.Local.ToUniversalTime(Now));
end;
function TAzureTableService.QueryTables(const ContinuationToken: String; ResponseInfo: TCloudResponseInfo): TStrings;
var
xml: String;
xmlDoc: IXMLDocument;
TableNode: IXMLNode;
ContentNode: IXMLNode;
PropertiesNode: IXMLNode;
TableNameNode: IXMLNode;
begin
xml := QueryTablesXML(ContinuationToken, ResponseInfo);
Result := TStringList.Create;
if xml <> EmptyStr then
begin
xmlDoc := TXMLDocument.Create(nil);
try
xmlDoc.LoadFromXML(xml);
except
Exit(Result);
end;
TableNode := xmlDoc.DocumentElement.ChildNodes.FindNode(NODE_TABLE);
while (TableNode <> nil) and (TableNode.HasChildNodes) do
begin
if (TableNode.NodeName = NODE_TABLE) then
begin
ContentNode := TableNode.ChildNodes.FindNode(NODE_TABLE_CONTENT);
if (ContentNode <> nil) and (ContentNode.HasChildNodes) then
begin
PropertiesNode := GetFirstMatchingChildNode(ContentNode, NODE_PROPERTIES);
if (PropertiesNode <> nil) and (PropertiesNode.HasChildNodes) then
begin
TableNameNode := GetFirstMatchingChildNode(PropertiesNode, NODE_TABLE_NAME);
Result.Add(TableNameNode.Text);
end;
end;
end;
TableNode := TableNode.NextSibling;
end;
end;
end;
function TAzureTableService.QueryEntityXML(const TableName, PartitionKey, RowKey: String;
ResponseInfo: TCloudResponseInfo): String;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
Response: TCloudHTTP;
begin
url := Format('%s/%s(PartitionKey=''%s'',RowKey=''%s'')',
[GetConnectionInfo.TableURL, TableName, PartitionKey, RowKey]);
Headers := TStringList.Create;
PopulateDateHeader(Headers);
if GetConnectionInfo.UseDevelopmentStorage then
QueryPrefix := Format('/%s/%s/%s(PartitionKey=''%s'',RowKey=''%s'')',
[GetConnectionInfo.AccountName, GetConnectionInfo.AccountName, TableName, PartitionKey, RowKey])
else
begin
AddTableVersionHeaders(Headers);
QueryPrefix := Format('/%s/%s(PartitionKey=''%s'',RowKey=''%s'')',
[GetConnectionInfo.AccountName, TableName, PartitionKey, RowKey]);
end;
Response := nil;
try
Response := IssueGetRequest(url, Headers, nil, QueryPrefix, ResponseInfo, Result);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
end;
end;
function TAzureTableService.QueryEntitiesXML(const TableName, FilterExpression: String;
ResponseInfo: TCloudResponseInfo;
const NextPartitionKey, NextRowKey: String): String;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
QueryParams: TStringList;
Response: TCloudHTTP;
begin
url := Format('%s/%s()', [GetConnectionInfo.TableURL, TableName]);
QueryParams := nil;
if (NextPartitionKey <> EmptyStr) or (NextRowKey <> EmptyStr) then
begin
QueryParams := TStringList.Create;
QueryParams.Values['NextPartitionKey'] := NextPartitionKey;
QueryParams.Values['NextRowKey'] := NextRowKey;
url := BuildQueryParameterString(url, QueryParams, False, True);
end;
if FilterExpression <> EmptyStr then
begin
if QueryParams = nil then
QueryParams := TStringList.Create;
QueryParams.Values['$filter'] := FilterExpression;
end;
url := BuildQueryParameterString(url, QueryParams, False, True);
Headers := TStringList.Create;
PopulateDateHeader(Headers);
QueryPrefix := GetTablesQueryPrefix(Headers, TableName) + '()';
Response := nil;
try
Response := IssueGetRequest(url, Headers, nil, QueryPrefix, ResponseInfo, Result);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
end;
end;
function TAzureTableService.BuildRowList(const XML: String; const FromQuery: Boolean): TList<TCloudTableRow>;
var
xmlDoc: IXMLDocument;
TableNode: IXMLNode;
ContentNode: IXMLNode;
Row: TCloudTableRow;
begin
Result := TList<TCloudTableRow>.Create;
if XML = EmptyStr then
Exit;
xmlDoc := TXMLDocument.Create(nil);
xmlDoc.LoadFromXML(XML);
//If it isn't from a query, then they specified PartitionKey and RowKey, so the root node represents the result
//instead of having multiple child 'entry' nodes.
if FromQuery then
TableNode := xmlDoc.DocumentElement.ChildNodes.FindNode(NODE_TABLE)
else if AnsiCompareText(xmlDoc.DocumentElement.NodeName, NODE_TABLE) = 0 then
TableNode := xmlDoc.DocumentElement;
while (TableNode <> nil) and (TableNode.HasChildNodes) do
begin
if (TableNode.NodeName = NODE_TABLE) then
begin
ContentNode := TableNode.ChildNodes.FindNode(NODE_TABLE_CONTENT);
Row := GetRowFromConentNode(ContentNode);
if Row <> nil then
Result.Add(Row);
end;
//If it isn't from a query, then they specified PartitionKey and RowKey, so there is only one result
if FromQuery then
TableNode := TableNode.NextSibling
else
Break;
end;
end;
function TAzureTableService.QueryEntity(const TableName, PartitionKey, RowKey: String;
ResponseInfo: TCloudResponseInfo): TCloudTableRow;
var
LResultList: TList<TCloudTableRow>;
I, Count: Integer;
begin
LResultList := BuildRowList(QueryEntityXML(TableName, PartitionKey, RowKey, ResponseInfo), False);
try
Count := LResultList.Count;
if (LResultList = nil) or (Count = 0) then
Exit(nil);
//set the first row as the result.
Result := LResultList[0];
//there should never be a case where more than one row was returned, but
//handle that possibility anyway, by freeing any other rows returned.
if Count > 1 then
for I := 1 to Count - 1 do
LResultList[I].Free;
finally
FreeAndNil(LResultList);
end;
end;
function TAzureTableService.QueryEntities(const TableName, FilterExpression: String;
ResponseInfo: TCloudResponseInfo;
const NextPartitionKey, NextRowKey: String): TList<TCloudTableRow>;
begin
Result := BuildRowList(QueryEntitiesXML(TableName, FilterExpression, ResponseInfo,
NextPartitionKey, NextRowKey), True);
end;
{ TAzureQueueService }
function TAzureQueueService.ListQueuesXML(OptionalParams: TStrings;
ResponseInfo: TCloudResponseInfo): String;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
Response: TCloudHTTP;
QueryParams: TStringList;
begin
Headers := TStringList.Create;
PopulateDateHeader(Headers, False);
QueryParams := nil;
if GetConnectionInfo.UseDevelopmentStorage then
QueryPrefix := Format('/%s/%s?%s', [GetConnectionInfo.AccountName, GetConnectionInfo.AccountName, 'comp=list'])
else
begin
Headers.Values['x-ms-version'] := '2009-09-19';
QueryPrefix := Format('/%s/', [GetConnectionInfo.AccountName]);
QueryParams := TStringList.Create;
QueryParams.Values['comp'] := 'list';
if OptionalParams <> nil then
QueryParams.AddStrings(OptionalParams);
end;
url := BuildQueryParameterString(GetConnectionInfo.QueueURL, QueryParams, False, True);
Response := nil;
try
Response := IssueGetRequest(url, Headers, QueryParams, QueryPrefix, ResponseInfo, Result);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(QueryParams);
FreeAndNil(Headers);
end;
end;
function TAzureQueueService.GetQueuesQueryPrefix(Headers: TStrings; QueueName: String): String;
begin
if GetConnectionInfo.UseDevelopmentStorage then
Result := Format('/%s/%s/%s', [GetConnectionInfo.AccountName, GetConnectionInfo.AccountName, QueueName])
else
begin
Headers.Values['x-ms-version'] := '2009-09-19';
Result := Format('/%s/%s', [GetConnectionInfo.AccountName, QueueName]);
end;
end;
function TAzureQueueService.ListQueues(OptionalParams: TStrings;
ResponseInfo: TCloudResponseInfo): TList<TCloudQueue>;
var
xml: String;
xmlDoc: IXMLDocument;
QueuesXMLNode: IXMLNode;
QueueNode: IXMLNode;
NameNode, UrlNode: IXMLNode;
begin
xml := ListQueuesXML(OptionalParams, ResponseInfo);
if XML = EmptyStr then
Exit(nil);
Result := TList<TCloudQueue>.Create;
xmlDoc := TXMLDocument.Create(nil);
xmlDoc.LoadFromXML(XML);
QueuesXMLNode := xmlDoc.DocumentElement.ChildNodes.FindNode(NODE_QUEUES);
if (QueuesXMLNode <> nil) and (QueuesXMLNode.HasChildNodes) then
begin
QueueNode := QueuesXMLNode.ChildNodes.FindNode(NODE_QUEUE);
while (QueueNode <> nil) do
begin
if QueueNode.NodeName = NODE_QUEUE then
begin
NameNode := QueueNode.ChildNodes.FindNode(NODE_QUEUE_NAME);
UrlNode := QueueNode.ChildNodes.FindNode(NODE_QUEUE_URL);
if (NameNode <> nil) and (UrlNode <> nil) then
Result.Add(TCloudQueue.Create(NameNode.Text, UrlNode.Text));
end;
QueueNode := QueueNode.NextSibling;
end;
end;
end;
function TAzureQueueService.CreateQueue(const QueueName: String; const MetaDataHeaders: TStrings;
ResponseInfo: TCloudResponseInfo): boolean;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
Response: TCloudHTTP;
FreeResponseInfo: Boolean;
begin
url := Format('%s/%s', [GetConnectionInfo.QueueURL, QueueName]);
Headers := TStringList.Create;
if MetaDataHeaders <> nil then
Headers.AddStrings(MetaDataHeaders);
PopulateDateHeader(Headers, False);
Headers.Values['Content-Length'] := '0';
QueryPrefix := GetQueuesQueryPrefix(Headers, QueueName);
FreeResponseInfo := ResponseInfo = nil;
if FreeResponseInfo then
ResponseInfo := TCloudResponseInfo.Create;
Response := nil;
try
try
Response := IssuePutRequest(url, Headers, nil, QueryPrefix, ResponseInfo);
Result := ResponseInfo.StatusCode = 201;
except
Result := false;
end;
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
if FreeResponseInfo then
ResponseInfo.Free;
end;
end;
function TAzureQueueService.DeleteQueue(const QueueName: String; ResponseInfo: TCloudResponseInfo = nil): boolean;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
Response: TCloudHTTP;
begin
url := Format('%s/%s', [GetConnectionInfo.QueueURL, QueueName]);
Headers := TStringList.Create;
PopulateDateHeader(Headers, False);
QueryPrefix := GetQueuesQueryPrefix(Headers, QueueName);
Response := nil;
try
try
Response := IssueDeleteRequest(url, Headers, nil, QueryPrefix, ResponseInfo);
Result := (Response <> nil) and (Response.ResponseCode = 204);
except
Result := false;
end;
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
end;
end;
function TAzureQueueService.GetMaxMessageReturnCount: Integer;
begin
Result := 32;
end;
function TAzureQueueService.GetQueueMetadata(const QueueName: String; out MetaData: TStrings;
ResponseInfo: TCloudResponseInfo): boolean;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
Response: TCloudHTTP;
FreeResponseInfo: Boolean;
QueryParams: TStringList;
I, Count: Integer;
begin
QueryParams := nil;
MetaData := nil;
url := Format('%s/%s', [GetConnectionInfo.QueueURL, QueueName]);
Headers := TStringList.Create;
PopulateDateHeader(Headers, False);
QueryPrefix := GetQueuesQueryPrefix(Headers, QueueName);
if GetConnectionInfo.UseDevelopmentStorage then
QueryPrefix := Format('%s?%s', [QueryPrefix, 'comp=metadata'])
else
begin
QueryParams := TStringList.Create;
QueryParams.Values['comp'] := 'metadata';
url := BuildQueryParameterString(url, QueryParams, False, True);
end;
FreeResponseInfo := ResponseInfo = nil;
if FreeResponseInfo then
ResponseInfo := TCloudResponseInfo.Create;
Response := nil;
try
try
Response := IssueGetRequest(url, Headers, QueryParams, QueryPrefix, ResponseInfo);
Result := ResponseInfo.StatusCode = 200;
if Result then
begin
MetaData := TStringList.Create;
Count := ResponseInfo.Headers.Count;
for I := 0 to Count - 1 do
begin
if AnsiContainsText(ResponseInfo.Headers.Names[I], 'x-ms-')then
begin
MetaData.Add(ResponseInfo.Headers[I]);
end;
end;
end;
except
Result := false;
end;
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(QueryParams);
FreeAndNil(Headers);
if FreeResponseInfo then
ResponseInfo.Free;
end;
end;
function TAzureQueueService.SetQueueMetadata(const QueueName: String; const MetaData: TStrings;
ResponseInfo: TCloudResponseInfo): boolean;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
Response: TCloudHTTP;
QueryParams: TStringList;
I, Count: Integer;
MetaName: String;
begin
QueryParams := nil;
url := Format('%s/%s', [GetConnectionInfo.QueueURL, QueueName]);
Headers := TStringList.Create;
if MetaData <> nil then
begin
Count := MetaData.Count;
for I := 0 to Count - 1 do
begin
MetaName := MetaData.Names[I];
if not AnsiStartsText('x-ms-meta-', MetaName) then
MetaName := 'x-ms-meta-' + MetaName;
Headers.Values[MetaName] := MetaData.ValueFromIndex[I];
end;
end;
PopulateDateHeader(Headers, False);
Headers.Values['Content-Length'] := '0';
QueryPrefix := GetQueuesQueryPrefix(Headers, QueueName);
if GetConnectionInfo.UseDevelopmentStorage then
QueryPrefix := Format('%s?%s', [QueryPrefix, 'comp=metadata'])
else
begin
QueryParams := TStringList.Create;
QueryParams.Values['comp'] := 'metadata';
url := BuildQueryParameterString(url, QueryParams, False, True);
end;
Response := nil;
try
try
Response := IssuePutRequest(url, Headers, QueryParams, QueryPrefix, ResponseInfo);
Result := (Response <> nil) and (Response.ResponseCode = 204);
except
Result := false;
end;
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(QueryParams);
FreeAndNil(Headers);
end;
end;
function TAzureQueueService.AddMessage(const QueueName, MessageText: String; const TimeToLive: Integer;
ResponseInfo: TCloudResponseInfo): boolean;
var
strContent: String;
url: String;
Headers: TStringList;
QueryPrefix: String;
Response: TCloudHTTP;
QueryParams: TStringList;
reqStream: TBytesStream;
begin
strContent := '<?xml version="1.0" encoding="utf-8" standalone="yes"?>' +
'<QueueMessage><MessageText>' + XMLEscape(MessageText) + '</MessageText></QueueMessage>';
url := Format('%s/%s/messages', [GetConnectionInfo.QueueURL, QueueName]);
QueryParams := nil;
if TimeToLive > 0 then
begin
QueryParams := TStringList.Create;
QueryParams.Values['messagettl'] := IntToStr(TimeToLive);
url := BuildQueryParameterString(url, QueryParams, False, True);
end;
reqStream := TBytesStream.Create(TEncoding.UTF8.GetBytes(strContent));
Headers := TStringList.Create;
PopulateDateHeader(Headers, False);
Headers.Values['Content-Length'] := IntToStr(reqStream.Size);
QueryPrefix := GetQueuesQueryPrefix(Headers, QueueName) + '/messages';
if GetConnectionInfo.UseDevelopmentStorage then
begin
QueryPrefix := QueryPrefix + BuildQueryParameterString(EmptyStr, QueryParams, False, True);
//don't want to use the query params in the call to IssueGetRequest, since they are used now
FreeAndNil(QueryParams);
end;
Response := nil;
try
try
Response := IssuePostRequest(url, Headers, QueryParams, QueryPrefix, ResponseInfo, reqStream);
Result := (Response <> nil) and (Response.ResponseCode = 201);
except
Result := false;
end;
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(reqStream);
FreeAndNil(QueryParams);
FreeAndNil(Headers);
end;
end;
function TAzureQueueService.GetOrPeekMessagesXML(const QueueName: String; PeekOnly: Boolean; NumOfMessages,
VisibilityTimeout: Integer;
ResponseInfo: TCloudResponseInfo): String;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
Response: TCloudHTTP;
QueryParams: TStringList;
begin
url := Format('%s/%s/messages', [GetConnectionInfo.QueueURL, QueueName]);
Headers := TStringList.Create;
PopulateDateHeader(Headers, False);
QueryParams := nil;
if (NumOfMessages > 0) or ((not PeekOnly) and (VisibilityTimeout > 0)) or PeekOnly then
begin
QueryParams := TStringList.Create;
if NumOfMessages > 0 then
QueryParams.Values['numofmessages'] := IntToStr(NumOfMessages);
if (not PeekOnly) and (VisibilityTimeout > 0) then
QueryParams.Values['visibilitytimeout'] := IntToStr(VisibilityTimeout);
if PeekOnly then
QueryParams.Values['peekonly'] := 'true';
url := BuildQueryParameterString(url, QueryParams, False, True);
end;
QueryPrefix := GetQueuesQueryPrefix(Headers, QueueName) + '/messages';
if GetConnectionInfo.UseDevelopmentStorage then
begin
QueryPrefix := QueryPrefix + BuildQueryParameterString(EmptyStr, QueryParams, False, True);
//don't want to use the query params in the call to IssueGetRequest, since they are used now
FreeAndNil(QueryParams);
end;
Response := nil;
try
Response := IssueGetRequest(url, Headers, QueryParams, QueryPrefix, ResponseInfo, Result);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
FreeAndNil(QueryParams);
end;
end;
function TAzureQueueService.GetMessagesXML(const QueueName: String; NumOfMessages, VisibilityTimeout: Integer;
ResponseInfo: TCloudResponseInfo): String;
begin
Result := GetOrPeekMessagesXML(QueueName, False, NumOfMessages, VisibilityTimeout, ResponseInfo);
end;
function TAzureQueueService.GetMessages(const QueueName: String; NumOfMessages, VisibilityTimeout: Integer;
ResponseInfo: TCloudResponseInfo): TList<TCloudQueueMessage>;
var
xml: String;
begin
xml := GetMessagesXML(QueueName, NumOfMessages, VisibilityTimeout, ResponseInfo);
Result := GetMessagesFromXML(xml);
end;
function TAzureQueueService.GetMessagesFromXML(const xml: String): TList<TCloudQueueMessage>;
var
xmlDoc: IXMLDocument;
RootNode: IXMLNode;
MessageNode, ChildNode: IXMLNode;
MsgId, MsgText, PopReceipt: String;
Msg: TCloudQueueMessage;
MsgProps: TStrings;
begin
Result := nil;
if xml <> EmptyStr then
begin
Result := TList<TCloudQueueMessage>.Create;
xmlDoc := TXMLDocument.Create(nil);
xmlDoc.LoadFromXML(xml);
RootNode := xmlDoc.DocumentElement;
if (RootNode <> nil) and (RootNode.HasChildNodes) then
begin
MessageNode := RootNode.ChildNodes.FindNode('QueueMessage');
while (MessageNode <> nil) do
begin
MsgProps := nil;
//making sure to only add the message if MessageId and MessageText are both found
if (MessageNode.NodeName = 'QueueMessage') and MessageNode.HasChildNodes then
begin
ChildNode := MessageNode.ChildNodes.First;
MsgProps := TStringList.Create;
while (ChildNode <> nil) do
begin
if AnsiSameText('MessageId' , ChildNode.NodeName) then
MsgId := ChildNode.Text
else if AnsiSameText('MessageText' , ChildNode.NodeName) then
MsgText := ChildNode.Text
else if AnsiSameText('PopReceipt' , ChildNode.NodeName) then
PopReceipt := ChildNode.Text
else
MsgProps.Values[ChildNode.NodeName] := ChildNode.Text;
ChildNode := ChildNode.NextSibling;
end;
if (MsgId <> EmptyStr) and (MsgText <> EmptyStr) then
begin
Msg := TCloudQueueMessage.Create(MsgId, MsgText, MsgProps);
Msg.PopReceipt := PopReceipt;
Result.Add(Msg);
end
else
FreeAndNil(MsgProps);
end;
MessageNode := MessageNode.NextSibling;
end;
end;
end;
end;
function TAzureQueueService.PeekMessagesXML(const QueueName: String; NumOfMessages: Integer;
ResponseInfo: TCloudResponseInfo): String;
begin
Result := GetOrPeekMessagesXML(QueueName, True, NumOfMessages, 0, ResponseInfo);
end;
function TAzureQueueService.PeekMessages(const QueueName: String; NumOfMessages: Integer;
ResponseInfo: TCloudResponseInfo): TList<TCloudQueueMessage>;
var
xml: String;
begin
xml := PeekMessagesXML(QueueName, NumOfMessages, ResponseInfo);
Result := GetMessagesFromXML(xml);
end;
function TAzureQueueService.DeleteMessage(const QueueName: String; const QueueMessage: TCloudQueueMessage;
GetPopReceiptIfNeeded: Boolean; ResponseInfo: TCloudResponseInfo): boolean;
var
Msgs: TList<TCloudQueueMessage>;
begin
if (QueueName = EmptyStr) or (QueueMessage = nil) or (QueueMessage.MessageId = EmptyStr) then
Exit(False);
if QueueMessage.PopReceipt = EmptyStr then
begin
//If there is no pop receipt, and the caller doesn't want to compute one, fail the execution.
if not GetPopReceiptIfNeeded then
Exit(False);
Msgs := GetMessages(QueueName, 1, 0, ResponseInfo);
if (Msgs = nil) or (Msgs.Count <> 1) then
begin
FreeAndNil(Msgs);
Exit(False);
end;
//only set the pop receipt if the message on the top of the queue was the one requesting deletion.
if Msgs[0].MessageId = QueueMessage.MessageId then
QueueMessage.PopReceipt := Msgs[0].PopReceipt;
FreeAndNil(Msgs);
end;
Result := DeleteMessage(QueueName, QueueMessage.MessageId, QueueMessage.PopReceipt, ResponseInfo);
end;
function TAzureQueueService.DeleteMessage(const QueueName, MessageId, PopReceipt: String;
ResponseInfo: TCloudResponseInfo): boolean;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
Response: TCloudHTTP;
QueryParams: TStringList;
begin
if (QueueName = EmptyStr) or (MessageId = EmptyStr) or (PopReceipt = EmptyStr) then
Exit(False);
url := Format('%s/%s/messages/%s?popreceipt=%s',
[GetConnectionInfo.QueueURL, QueueName, MessageId, URLEncode(PopReceipt, ['+','='])]);
Headers := TStringList.Create;
PopulateDateHeader(Headers, False);
QueryParams := TStringList.Create;
QueryParams.Values['popreceipt'] := PopReceipt;
QueryPrefix := GetQueuesQueryPrefix(Headers, QueueName) + '/messages/' + MessageId;
Response := nil;
try
Response := IssueDeleteRequest(url, Headers, QueryParams, QueryPrefix, ResponseInfo);
Result := (Response <> nil) and (Response.ResponseCode = 204);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
FreeAndNil(QueryParams);
end;
end;
function TAzureQueueService.ClearMessages(const QueueName: String; ResponseInfo: TCloudResponseInfo): boolean;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
Response: TCloudHTTP;
begin
if (QueueName = EmptyStr) then
Exit(False);
url := Format('%s/%s/messages', [GetConnectionInfo.QueueURL, QueueName]);
Headers := TStringList.Create;
PopulateDateHeader(Headers, False);
QueryPrefix := GetQueuesQueryPrefix(Headers, QueueName) + '/messages';
Response := nil;
try
Response := IssueDeleteRequest(url, Headers, nil, QueryPrefix, ResponseInfo);
Result := (Response <> nil) and (Response.ResponseCode = 204);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
end;
end;
{ TAzureBlobService }
function TAzureBlobService.ListContainersXML(OptionalParams: TStrings;
ResponseInfo: TCloudResponseInfo): String;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
QueryParams: TStringList;
Response: TCloudHTTP;
begin
url := GetConnectionInfo.BlobURL;
Headers := TStringList.Create;
PopulateDateHeader(Headers, False);
if not GetConnectionInfo.UseDevelopmentStorage then
Headers.Values['x-ms-version'] := '2009-09-19';
QueryParams := TStringList.Create;
QueryParams.Values['comp'] := 'list';
if OptionalParams <> nil then
QueryParams.AddStrings(OptionalParams);
url := BuildQueryParameterString(url, QueryParams, False, True);
QueryPrefix := Format('/%s/', [GetConnectionInfo.AccountName]);
Response := nil;
try
Response := IssueGetRequest(url, Headers, QueryParams, QueryPrefix, ResponseInfo, Result);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(QueryParams);
FreeAndNil(Headers);
end;
end;
function TAzureBlobService.LoadChildrenAsProperties(ANode: IXMLNode): TStrings;
var
ChildNode: IXMLNode;
begin
Result := TStringList.Create;
if (ANode <> nil) and ANode.HasChildNodes then
begin
ChildNode := ANode.ChildNodes.First;
while ChildNode <> nil do
begin
try
if ChildNode.IsTextElement then
Result.Values[ChildNode.NodeName] := ChildNode.Text;
finally
ChildNode := ChildNode.NextSibling;
end;
end;
end;
end;
function TAzureBlobService.ParseContainerFromContainerNode(ContainerNode: IXMLNode): TAzureContainer;
var
Name, URL: String;
Properties, Metadata: TStrings;
ContainerItem: IXMLNode;
begin
Result := nil;
if (ContainerNode <> nil) and
AnsiSameText(ContainerNode.NodeName, 'Container') and
ContainerNode.HasChildNodes then
begin
Properties := nil;
Metadata := nil;
try
ContainerItem := ContainerNode.ChildNodes.First;
while ContainerItem <> nil do
begin
try
if AnsiSameText(ContainerItem.NodeName, 'Name') then
Name := ContainerItem.Text
else if AnsiSameText(ContainerItem.NodeName, 'URL') then
URL := ContainerItem.Text
else if AnsiSameText(ContainerItem.NodeName, 'Properties') then
Properties := LoadChildrenAsProperties(ContainerItem)
else if AnsiSameText(ContainerItem.NodeName, 'Metadata') then
Metadata := LoadChildrenAsProperties(ContainerItem);
finally
ContainerItem := ContainerItem.NextSibling;
end;
end;
if (Name <> EmptyStr) and (URL <> EmptyStr) then
Result := TAzureContainer.Create(Name, URL, Properties, Metadata);
finally
if Result = nil then
begin
FreeAndNil(Properties);
FreeAndNil(Metadata);
end;
end;
end;
end;
procedure TAzureBlobService.PopulateBlobPropertyHeaders(Headers, Properties: TStrings);
var
PropName: String;
I, Count: Integer;
begin
if (Properties <> nil) and (Headers <> nil) then
begin
Count := Properties.Count;
for I := 0 to Count - 1 do
begin
PropName := Properties.Names[I];
//if the value doesn't start with 'x-ms-blob-' then the prefix will be added.
//otherwise, the header will be added as-is, and may or may not be a valid header
if AnsiSameText(PropName, 'x-ms-blob-cache-control') or
AnsiSameText(PropName, 'Cache-Control') then
Headers.Values['x-ms-blob-cache-control'] := Properties.ValueFromIndex[I]
else if AnsiSameText(PropName, 'x-ms-blob-content-type') or
AnsiSameText(PropName, 'Content-Type') then
Headers.Values['x-ms-blob-content-type'] := Properties.ValueFromIndex[I]
else if AnsiSameText(PropName, 'x-ms-blob-content-md5') or
AnsiSameText(PropName, 'Content-MD5') then
Headers.Values['x-ms-blob-content-md5'] := Properties.ValueFromIndex[I]
else if AnsiSameText(PropName, 'x-ms-blob-content-encoding') or
AnsiSameText(PropName, 'Content-Encoding') then
Headers.Values['x-ms-blob-content-encoding'] := Properties.ValueFromIndex[I]
else if AnsiSameText(PropName, 'x-ms-blob-content-language') or
AnsiSameText(PropName, 'Content-Language') then
Headers.Values['x-ms-blob-content-language'] := Properties.ValueFromIndex[I]
else
Headers.Values[PropName] := Properties.ValueFromIndex[I];
end;
end;
end;
function TAzureBlobService.PutBlock(ContainerName, BlobName: String; const BlockId: String; Content: TBytes;
const ContentMD5, LeaseId: String;
ResponseInfo: TCloudResponseInfo): boolean;
var
url: String;
contentStream: TBytesStream;
Headers: TStringList;
QueryPrefix: String;
QueryParams: TStringList;
Response: TCloudHTTP;
begin
if (Content = nil) or (ContainerName = EmptyStr) or (BlobName = EmptyStr) or
(BlockId = EmptyStr) then
Exit(False);
ContainerName := AnsiLowerCase(ContainerName);
url := Format('%s/%s/%s', [GetConnectionInfo.BlobURL, ContainerName, URLEncode(BlobName)]);
Headers := TStringList.Create;
PopulateDateHeader(Headers, False);
if ContentMD5 <> EmptyStr then
Headers.Values['Content-MD5'] := ContentMD5;
if LeaseId <> emptyStr then
headers.Values['x-ms-lease-id'] := LeaseId;
contentStream := TBytesStream.Create(Content);
//issuing a put, so need content length
Headers.Values['Content-Length'] := IntToStr(contentStream.Size);
QueryPrefix := GetBlobContainerQueryPrefix(Headers, ContainerName, URLEncode(BlobName));
QueryParams := TStringList.Create;
QueryParams.Values['comp'] := 'block';
QueryParams.Values['blockid'] := BlockId; //Base64 encode the BlockId
url := BuildQueryParameterString(url, QueryParams, False, True);
Response := nil;
try
Response := IssuePutRequest(url, Headers, QueryParams, QueryPrefix, ResponseInfo, contentStream);
Result := (Response <> nil) and (Response.ResponseCode = 201);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(contentStream);
FreeAndNil(QueryParams);
FreeAndNil(Headers);
end;
end;
function TAzureBlobService.PutBlockBlob(ContainerName, BlobName: String; Content: TBytes; LeaseId: String;
OptionalHeaders, Metadata: TStrings;
ResponseInfo: TCloudResponseInfo): boolean;
var
url: String;
contentStream: TBytesStream;
Headers: TStringList;
QueryPrefix: String;
Response: TCloudHTTP;
begin
if (Content = nil) or (ContainerName = EmptyStr) or (BlobName = EmptyStr) then
Exit(False);
ContainerName := AnsiLowerCase(ContainerName);
url := Format('%s/%s/%s', [GetConnectionInfo.BlobURL, ContainerName, URLEncode(BlobName)]);
Headers := BuildMetadataHeaderList(MetaData);
PopulateDateHeader(Headers, False);
headers.Values['x-ms-blob-type'] := 'BlockBlob';
if OptionalHeaders <> nil then
Headers.AddStrings(OptionalHeaders);
if LeaseId <> emptyStr then
headers.Values['x-ms-lease-id'] := LeaseId;
contentStream := TBytesStream.Create(Content);
//issuing a put, so need content length
Headers.Values['Content-Length'] := IntToStr(contentStream.Size);
QueryPrefix := GetBlobContainerQueryPrefix(Headers, ContainerName, URLEncode(BlobName));
Response := nil;
try
Response := IssuePutRequest(url, Headers, nil, QueryPrefix, ResponseInfo, contentStream);
Result := (Response <> nil) and (Response.ResponseCode = 201);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(contentStream);
FreeAndNil(Headers);
end;
end;
function TAzureBlobService.PutBlockList(ContainerName, BlobName: String; BlockList: TList<TAzureBlockListItem>;
Properties, Metadata: TStrings; const LeaseId: String;
const ContentMD5: String;
ResponseInfo: TCloudResponseInfo): boolean;
var
url: String;
xml: String;
contentStream: TBytesStream;
Headers: TStringList;
QueryPrefix: String;
QueryParams: TStringList;
Response: TCloudHTTP;
Item: TAzureBlockListItem;
begin
if (ContainerName = EmptyStr) or (BlobName = EmptyStr) or
(BlockList = nil) or (BlockList.Count = 0) then
Exit(False);
url := Format('%s/%s/%s', [GetConnectionInfo.BlobURL, ContainerName, URLEncode(BlobName)]);
Headers := BuildMetadataHeaderList(Metadata);
PopulateDateHeader(Headers, False);
if LeaseId <> EmptyStr then
headers.Values['x-ms-lease-id'] := LeaseId;
if ContentMD5 <> EmptyStr then
Headers.Values['Content-MD5'] := ContentMD5;
//Populate the headers, possibly prefixing with x-ms-blob-, when appropriate.
//For example, 'Content-Type' in the Properties list would be added
//to the Headers list as 'x-ms-blob-content-type'
PopulateBlobPropertyHeaders(Headers, Properties);
QueryParams := TStringList.Create;
QueryParams.Values['comp'] := 'blocklist';
url := BuildQueryParameterString(url, QueryParams, False, True);
xml := '<?xml version="1.0" encoding="utf-8"?><BlockList>';
for Item In BlockList do
xml := xml + Item.AsXML;
xml := xml + '</BlockList>';
contentStream := TBytesStream.Create(TEncoding.UTF8.GetBytes(xml));
Headers.Values['Content-Length'] := IntToStr(contentStream.Size);
QueryPrefix := GetBlobContainerQueryPrefix(Headers, ContainerName, URLEncode(BlobName));
Response := nil;
try
Response := IssuePutRequest(url, Headers, QueryParams, QueryPrefix, ResponseInfo, contentStream);
Result := (Response <> nil) and (Response.ResponseCode = 201);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(contentStream);
FreeAndNil(QueryParams);
FreeAndNil(Headers);
end;
end;
function TAzureBlobService.PutPageInternal(ContainerName, BlobName: String; Content: TBytes; DoClear: Boolean;
StartPage, PageCount: Integer; ActionConditional: TBlobActionConditional;
const ContentMD5, LeaseId: String;
ResponseInfo: TCloudResponseInfo): boolean;
var
url: String;
contentStream: TBytesStream;
Headers: TStringList;
QueryPrefix: String;
QueryParams: TStringList;
Response: TCloudHTTP;
StartByte, EndByte: Int64;
begin
if ((ContainerName = EmptyStr) or (BlobName = EmptyStr)) or
//Content should only be nil if doing a 'clear' action on the given range
((Content = nil) and (not DoClear)) then
Exit(False);
//calculate the starting and ending byte based on the start page and page count
StartByte := StartPage * 512; //Pages must each be 512 bytes
EndByte := StartByte + (PageCount * 512 - 1); //Zero based indexing, so subtract 1 from the range
ContainerName := AnsiLowerCase(ContainerName);
url := Format('%s/%s/%s', [GetConnectionInfo.BlobURL, ContainerName, URLEncode(BlobName)]);
Headers := TStringList.Create;
PopulateDateHeader(Headers, False);
if EndByte > StartByte then
Headers.Values['x-ms-range'] := Format('bytes=%d-%d', [StartByte, EndByte]);
if ContentMD5 <> EmptyStr then
Headers.Values['Content-MD5'] := ContentMD5;
if LeaseId <> emptyStr then
headers.Values['x-ms-lease-id'] := LeaseId;
//issuing a put, so need content length
contentStream := nil;
if Content <> nil then
begin
contentStream := TBytesStream.Create(Content);
Headers.Values['Content-Length'] := IntToStr(contentStream.Size);
end
else
Headers.Values['Content-Length'] := '0';
//either an update or clear action
if DoClear then
Headers.Values['x-ms-page-write'] := 'clear'
else
Headers.Values['x-ms-page-write'] := 'update';
//add the conditional headers, if any are set
ActionConditional.PopulateHeaders(Headers);
QueryPrefix := GetBlobContainerQueryPrefix(Headers, ContainerName, URLEncode(BlobName));
QueryParams := TStringList.Create;
QueryParams.Values['comp'] := 'page';
url := BuildQueryParameterString(url, QueryParams, False, True);
Response := nil;
try
Response := IssuePutRequest(url, Headers, QueryParams, QueryPrefix, ResponseInfo, contentStream);
Result := (Response <> nil) and (Response.ResponseCode = 201);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(contentStream);
FreeAndNil(QueryParams);
FreeAndNil(Headers);
end;
end;
function TAzureBlobService.PutPage(ContainerName, BlobName: String; Content: TBytes; StartPage: Integer;
const LeaseId: String; ResponseInfo: TCloudResponseInfo): boolean;
begin
Result := PutPage(ContainerName, BlobName, Content, StartPage, TBlobActionConditional.Create, LeaseId, ResponseInfo);
end;
function TAzureBlobService.PutPage(ContainerName, BlobName: String; Content: TBytes; StartPage: Integer;
ActionConditional: TBlobActionConditional; const LeaseId: String;
ResponseInfo: TCloudResponseInfo): boolean;
var
Len: Integer;
PageCount: Int64;
LeftToPad: Int64;
begin
if Content = nil then
Exit(False);
//get the actual length of the content
Len := Length(Content);
//get the page count, which may or may not be one fewer than it needs to be
PageCount := Trunc(Len / 512);
//Determine if the current PageCount is correct, or if one more (partially filled) page is needed.
//If one more page is needed, specify how many bytes need to be added as padding on the end.
LeftToPad := 512 - (Len Mod 512);
//Increment the page count by one and pad the content with enough bytes to make (Length Mod 512) equal zero.
if (LeftToPad < 512) then
begin
Inc(PageCount);
SetLength(Content, Len + LeftToPad);
end;
Result := PutPage(ContainerName, BlobName, Content, StartPage, PageCount, ActionConditional,
EmptyStr, LeaseId, ResponseInfo);
end;
function TAzureBlobService.PutPage(ContainerName, BlobName: String; Content: TBytes;
StartPage, PageCount: Integer; ActionConditional: TBlobActionConditional;
const ContentMD5, LeaseId: String;
ResponseInfo: TCloudResponseInfo): boolean;
begin
Result := PutPageInternal(ContainerName, BlobName, Content, False, StartPage, PageCount, ActionConditional,
ContentMD5, LeaseId, ResponseInfo);
end;
function TAzureBlobService.PutPage(ContainerName, BlobName: String; Content: TBytes;
StartPage, PageCount: Integer; const LeaseId, ContentMD5: String;
ResponseInfo: TCloudResponseInfo): boolean;
begin
Result := PutPage(ContainerName, BlobName, Content, StartPage, PageCount, TBlobActionConditional.Create,
ContentMD5, LeaseId, ResponseInfo);
end;
function TAzureBlobService.ClearPage(ContainerName, BlobName: String; StartPage, PageCount: Integer;
ActionConditional: TBlobActionConditional; const LeaseId: String;
ResponseInfo: TCloudResponseInfo): boolean;
begin
Result := PutPageInternal(ContainerName, BlobName, nil, True, StartPage, PageCount, ActionConditional,
EmptyStr, LeaseId, ResponseInfo);
end;
function TAzureBlobService.ClearPage(ContainerName, BlobName: String; StartPage, PageCount: Integer;
const LeaseId: String; ResponseInfo: TCloudResponseInfo): boolean;
begin
Result := ClearPage(ContainerName, BlobName, StartPage, PageCount, TBlobActionConditional.Create,
LeaseId, ResponseInfo);
end;
function TAzureBlobService.PutPageBlob(ContainerName, BlobName: String; MaximumSize: int64; OptionalHeaders,
Metadata: TStrings; BlobSequenceNumber: int64;
ResponseInfo: TCloudResponseInfo): boolean;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
Response: TCloudHTTP;
begin
if (MaximumSize < 512) or (ContainerName = EmptyStr) or (BlobName = EmptyStr) then
Exit(False);
ContainerName := AnsiLowerCase(ContainerName);
url := Format('%s/%s/%s', [GetConnectionInfo.BlobURL, ContainerName, URLEncode(BlobName)]);
Headers := BuildMetadataHeaderList(MetaData);
PopulateDateHeader(Headers, False);
headers.Values['x-ms-blob-type'] := 'PageBlob';
if OptionalHeaders <> nil then
Headers.AddStrings(OptionalHeaders);
//issuing a put, so need content length
Headers.Values['Content-Length'] := '0';
Headers.Values['x-ms-blob-content-length'] := IntToStr(MaximumSize);
if BlobSequenceNumber > 0 then
Headers.Values['x-ms-blob-sequence-number'] := IntToStr(BlobSequenceNumber);
QueryPrefix := GetBlobContainerQueryPrefix(Headers, ContainerName, URLEncode(BlobName));
Response := nil;
try
Response := IssuePutRequest(url, Headers, nil, QueryPrefix, ResponseInfo);
Result := (Response <> nil) and (Response.ResponseCode = 201);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
end;
end;
function TAzureBlobService.SetContainerACL(ContainerName: String; const SignedIdentifierId: String;
AccessPolicy: TAccessPolicy; PublicAccess: TBlobPublicAccess; ResponseInfo: TCloudResponseInfo): boolean;
var
SignedIdentifiers: TList<TSignedIdentifier>;
SignedIdentifier: TSignedIdentifier;
begin
SignedIdentifiers := TList<TSignedIdentifier>.Create;
try
//create a signed identifier list with the single signed identifier,
//then call the function that takes a list.
SignedIdentifier := TSignedIdentifier.Create(ContainerName, AccessPolicy, SignedIdentifierId);
SignedIdentifiers.Add(SignedIdentifier);
Result := SetContainerACL(ContainerName, SignedIdentifiers, PublicAccess, ResponseInfo);
finally
FreeAndNil(SignedIdentifier);
FreeAndNil(SignedIdentifiers);
end;
end;
function TAzureBlobService.SetBlobMetadata(ContainerName, BlobName: String; Metadata: TStrings;
LeaseId: String; ResponseInfo: TCloudResponseInfo): boolean;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
QueryParams: TStringList;
Response: TCloudHTTP;
begin
if (ContainerName = EmptyStr) or (BlobName = EmptyStr) then
Exit(False);
ContainerName := AnsiLowerCase(ContainerName);
url := Format('%s/%s/%s', [GetConnectionInfo.BlobURL, ContainerName, URLEncode(BlobName)]);
Headers := BuildMetadataHeaderList(MetaData);
PopulateDateHeader(Headers, False);
//issuing a put, so need content length. But all data is passed in headers, so content length is 0
Headers.Values['Content-Length'] := '0';
QueryPrefix := GetBlobContainerQueryPrefix(Headers, ContainerName, URLEncode(BlobName));
QueryParams := TStringList.Create;
QueryParams.Values['comp'] := 'metadata';
url := BuildQueryParameterString(url, QueryParams, False, True);
Response := nil;
try
Response := IssuePutRequest(url, Headers, QueryParams, QueryPrefix, ResponseInfo);
Result := (Response <> nil) and (Response.ResponseCode = 200);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(QueryParams);
FreeAndNil(Headers);
end;
end;
function TAzureBlobService.SetBlobProperties(ContainerName, BlobName: String; Properties: TStrings;
const LeaseId: String; ResponseInfo: TCloudResponseInfo): boolean;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
QueryParams: TStringList;
Response: TCloudHTTP;
begin
if (ContainerName = EmptyStr) or (BlobName = EmptyStr) then
Exit(False);
ContainerName := AnsiLowerCase(ContainerName);
url := Format('%s/%s/%s', [GetConnectionInfo.BlobURL, ContainerName, URLEncode(BlobName)]);
Headers := TStringList.Create;
PopulateDateHeader(Headers, False);
if LeaseId <> EmptyStr then
headers.Values['x-ms-lease-id'] := LeaseId;
//issuing a put, so need content length. But all data is passed in headers, so content length is 0
Headers.Values['Content-Length'] := '0';
//Populate the headers, possibly prefixing with x-ms-blob-, when appropriate.
//For example, 'Content-Type' in the Properties list would be added
//to the Headers list as 'x-ms-blob-content-type'
PopulateBlobPropertyHeaders(Headers, Properties);
QueryPrefix := GetBlobContainerQueryPrefix(Headers, ContainerName, URLEncode(BlobName));
QueryParams := TStringList.Create;
QueryParams.Values['comp'] := 'properties';
url := BuildQueryParameterString(url, QueryParams, False, True);
Response := nil;
try
Response := IssuePutRequest(url, Headers, QueryParams, QueryPrefix, ResponseInfo);
Result := (Response <> nil) and (Response.ResponseCode = 200);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(QueryParams);
FreeAndNil(Headers);
end;
end;
function TAzureBlobService.SetContainerACL(ContainerName: String; SignedIdentifiers: TList<TSignedIdentifier>;
PublicAccess: TBlobPublicAccess; ResponseInfo: TCloudResponseInfo): boolean;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
QueryParams: TStringList;
Response: TCloudHTTP;
ContentString: String;
I, Count: Integer;
ContentStream: TBytesStream;
begin
if SignedIdentifiers = nil then
Exit(False);
ContainerName := AnsiLowerCase(ContainerName);
url := Format('%s/%s', [GetConnectionInfo.BlobURL, ContainerName]);
Headers := TStringList.Create;
PopulateDateHeader(Headers, False);
//Create the XML representation of the SignedIdentifiers list, to 'PUT' to the server
ContentString := '<?xml version="1.0" encoding="utf-8"?><SignedIdentifiers>';
Count := SignedIdentifiers.Count;
for I := 0 to Count - 1 do
ContentString := ContentString + SignedIdentifiers[I].AsXML;
ContentString := ContentString + '</SignedIdentifiers>';
ContentStream := TBytesStream.Create(TEncoding.UTF8.GetBytes(ContentString));
//Add the XML's length as the Content-Length of the request
Headers.Values['Content-Length'] := IntToStr(ContentStream.Size);
if GetConnectionInfo.UseDevelopmentStorage then
Headers.Values['x-ms-prop-publicaccess'] := 'true'
else
Headers.Values['x-ms-blob-public-access'] := GetPublicAccessString(PublicAccess);
QueryPrefix := GetBlobContainerQueryPrefix(Headers, ContainerName);
QueryParams := TStringList.Create;
QueryParams.Values['restype'] := 'container';
QueryParams.Values['comp'] := 'acl';
url := BuildQueryParameterString(url, QueryParams, False, True);
Response := nil;
try
Response := IssuePutRequest(url, Headers, QueryParams, QueryPrefix, ResponseInfo, ContentStream);
Result := (Response <> nil) and (Response.ResponseCode = 200);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(ContentStream);
FreeAndNil(QueryParams);
FreeAndNil(Headers);
end;
end;
function TAzureBlobService.SetContainerMetadata(ContainerName: String; const Metadata: TStrings;
ResponseInfo: TCloudResponseInfo): boolean;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
QueryParams: TStringList;
Response: TCloudHTTP;
begin
ContainerName := AnsiLowerCase(ContainerName);
url := Format('%s/%s', [GetConnectionInfo.BlobURL, ContainerName]);
Headers := BuildMetadataHeaderList(MetaData);
PopulateDateHeader(Headers, False);
//issuing a put, so need content length. But all data is passed in headers, so content length is 0
Headers.Values['Content-Length'] := '0';
QueryPrefix := GetBlobContainerQueryPrefix(Headers, ContainerName);
QueryParams := TStringList.Create;
QueryParams.Values['restype'] := 'container';
QueryParams.Values['comp'] := 'metadata';
url := BuildQueryParameterString(url, QueryParams, False, True);
Response := nil;
try
Response := IssuePutRequest(url, Headers, QueryParams, QueryPrefix, ResponseInfo);
Result := (Response <> nil) and (Response.ResponseCode = 200);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(QueryParams);
FreeAndNil(Headers);
end;
end;
function TAzureBlobService.SnapshotBlob(ContainerName, BlobName: String; out SnapshotId: String;
const LeaseId: String; Metadata: TStrings;
ResponseInfo: TCloudResponseInfo): boolean;
begin
Result := SnapshotBlob(ContainerName, BlobName, TBlobActionConditional.Create, SnapshotId, LeaseId,
Metadata, ResponseInfo);
end;
function TAzureBlobService.SnapshotBlob(ContainerName, BlobName: String;
SnapshotConditionals: TBlobActionConditional;
out SnapshotId: String; const LeaseId: String;
Metadata: TStrings; ResponseInfo: TCloudResponseInfo): boolean;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
QueryParams: TStringList;
Response: TCloudHTTP;
FreeResponseInfo: Boolean;
begin
if (ContainerName = EmptyStr) or (BlobName = EmptyStr) then
Exit(False);
url := Format('%s/%s/%s', [GetConnectionInfo.BlobURL, ContainerName, URLEncode(BlobName)]);
Headers := BuildMetadataHeaderList(Metadata);
PopulateDateHeader(Headers, False);
Headers.Values['Content-Length'] := '0';
SnapshotConditionals.PopulateHeaders(Headers);
if LeaseId <> EmptyStr then
headers.Values['x-ms-lease-id'] := LeaseId;
QueryParams := TStringList.Create;
QueryParams.Values['comp'] := 'snapshot';
url := BuildQueryParameterString(url, QueryParams, False, True);
QueryPrefix := GetBlobContainerQueryPrefix(Headers, ContainerName, URLEncode(BlobName));
FreeResponseInfo := ResponseInfo = nil;
if FreeResponseInfo then
ResponseInfo := TCloudResponseInfo.Create;
Response := nil;
try
try
Response := IssuePutRequest(url, Headers, QueryParams, QueryPrefix, ResponseInfo);
Result := (Response <> nil) and (Response.ResponseCode = 201);
if Result then
SnapshotId := ResponseInfo.Headers.Values['x-ms-snapshot'];
except
Result := false;
end;
finally
if Assigned(Response) then
FreeAndNil(Response);
if FreeResponseInfo then
ResponseInfo.Free;
FreeAndNil(QueryParams);
FreeAndNil(Headers);
end;
end;
function TAzureBlobService.BuildMetadataHeaderList(const Metadata: TStrings): TStringList;
var
I, Count: Integer;
MetaName: String;
begin
Result := TStringList.Create;
//add the specified metadata into the headers, prefixing each
//metadata header name with 'x-ms-meta-' if it wasn't already.
if MetaData <> nil then
begin
Count := MetaData.Count;
for I := 0 to Count - 1 do
begin
MetaName := MetaData.Names[I];
if not AnsiStartsText('x-ms-meta-', MetaName) then
MetaName := 'x-ms-meta-' + MetaName;
Result.Values[MetaName] := MetaData.ValueFromIndex[I];
end;
end;
end;
function TAzureBlobService.CopyBlobInternal(TargetContainerName, TargetBlobName, SourceContainerName,
SourceBlobName: String; const SourceSnapshot, TargetLeaseId: String;
CopyConditionals: TBlobActionConditional;
Metadata: TStrings;
ResponseInfo: TCloudResponseInfo): boolean;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
Response: TCloudHTTP;
CopySourceVal: String;
begin
if (TargetContainerName = EmptyStr) or (TargetBlobName = EmptyStr) or
(SourceContainerName = EmptyStr) or (SourceBlobName = EmptyStr) then
Exit(False);
url := Format('%s/%s/%s', [GetConnectionInfo.BlobURL, TargetContainerName, URLEncode(TargetBlobName)]);
Headers := BuildMetadataHeaderList(Metadata);
PopulateDateHeader(Headers, False);
Headers.Values['Content-Length'] := '0';
if (SourceContainerName = EmptyStr) or (SourceContainerName = ROOT_CONTAINER) then
CopySourceVal := Format('/%s/%s', [GetConnectionInfo.AccountName, SourceBlobName])
else
CopySourceVal := Format('/%s/%s/%s', [GetConnectionInfo.AccountName, SourceContainerName, SourceBlobName]);
if SourceSnapshot <> EmptyStr then
CopySourceVal := CopySourceVal + '?snapshot=' + SourceSnapshot;
Headers.Values['x-ms-copy-source'] := CopySourceVal;
CopyConditionals.PopulateHeaders(Headers);
QueryPrefix := GetBlobContainerQueryPrefix(Headers, TargetContainerName, URLEncode(TargetBlobName));
Response := nil;
try
try
Response := IssuePutRequest(url, Headers, nil, QueryPrefix, ResponseInfo);
Result := (Response <> nil) and (Response.ResponseCode = 201);
except
Result := false;
end;
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
end;
end;
function TAzureBlobService.CopyBlob(TargetContainerName, TargetBlobName, SourceContainerName,
SourceBlobName: String; CopyConditionals: TBlobActionConditional;
const TargetLeaseId: String; Metadata: TStrings;
ResponseInfo: TCloudResponseInfo): boolean;
begin
Result := CopyBlobInternal(TargetContainerName, TargetBlobName, SourceContainerName,
SourceBlobName, '', TargetLeaseId,
CopyConditionals, Metadata, ResponseInfo);
end;
function TAzureBlobService.CopyBlob(TargetContainerName, TargetBlobName, SourceContainerName,
SourceBlobName: String; const TargetLeaseId: String;
Metadata: TStrings; ResponseInfo: TCloudResponseInfo): boolean;
begin
Result := CopyBlob(TargetContainerName, TargetBlobName, SourceContainerName, SourceBlobName,
TBlobActionConditional.Create, TargetLeaseId, Metadata, ResponseInfo);
end;
function TAzureBlobService.CopySnapshotToBlob(TargetContainerName, TargetBlobName, SourceContainerName,
SourceBlobName: String; const SourceSnapshot: String;
CopyConditionals: TBlobActionConditional;
Metadata: TStrings;
ResponseInfo: TCloudResponseInfo): boolean;
begin
Result := CopyBlobInternal(TargetContainerName, TargetBlobName, SourceContainerName,
SourceBlobName, SourceSnapshot, '',
CopyConditionals, Metadata, ResponseInfo);
end;
function TAzureBlobService.CopySnapshotToBlob(TargetContainerName, TargetBlobName, SourceContainerName,
SourceBlobName: String; const SourceSnapshot: String;
Metadata: TStrings;
ResponseInfo: TCloudResponseInfo): boolean;
begin
Result := CopySnapshotToBlob(TargetContainerName, TargetBlobName, SourceContainerName,
SourceBlobName, SourceSnapshot, TBlobActionConditional.Create, Metadata,
ResponseInfo);
end;
function TAzureBlobService.CreateContainer(ContainerName: string;
MetaData: TStrings;
PublicAccess: TBlobPublicAccess;
ResponseInfo: TCloudResponseInfo): boolean;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
QueryParams: TStringList;
Response: TCloudHTTP;
begin
ContainerName := AnsiLowerCase(ContainerName);
url := Format('%s/%s', [GetConnectionInfo.BlobURL, ContainerName]);
Headers := BuildMetadataHeaderList(MetaData);
PopulateDateHeader(Headers, False);
if PublicAccess = bpaContainer then
Headers.Values['x-ms-blob-public-access'] := 'container'
else if PublicAccess = bpaBlob then
Headers.Values['x-ms-blob-public-access'] := 'blob';
//issuing a put, so need content length. But all data is passed in headers, so content length is 0
Headers.Values['Content-Length'] := '0';
QueryPrefix := GetBlobContainerQueryPrefix(Headers, ContainerName);
QueryParams := TStringList.Create;
QueryParams.Values['restype'] := 'container';
url := BuildQueryParameterString(url, QueryParams, False, True);
Response := nil;
try
Response := IssuePutRequest(url, Headers, QueryParams, QueryPrefix, ResponseInfo);
Result := (Response <> nil) and (Response.ResponseCode = 201);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(QueryParams);
FreeAndNil(Headers);
end;
end;
function TAzureBlobService.CreateRootContainer(MetaData: TStrings; PublicAccess: TBlobPublicAccess;
ResponseInfo: TCloudResponseInfo): boolean;
begin
Result := CreateContainer(ROOT_CONTAINER, MetaData, PublicAccess, ResponseInfo);
end;
function TAzureBlobService.DeleteBlob(ContainerName, BlobName: String; OnlySnapshots: Boolean;
LeaseId: String; ResponseInfo: TCloudResponseInfo): boolean;
begin
Result := DeleteBlobInternal(ContainerName, BlobName, '', OnlySnapshots, LeaseId, ResponseInfo);
end;
function TAzureBlobService.DeleteBlobSnapshot(ContainerName, BlobName, SnapShot, LeaseId: String;
ResponseInfo: TCloudResponseInfo): boolean;
begin
if SnapShot = EmptyStr then
Exit(False);
Result := DeleteBlobInternal(ContainerName, BlobName, SnapShot, True, LeaseId, ResponseInfo);
end;
function TAzureBlobService.DeleteBlobInternal(ContainerName, BlobName, SnapShot: String;
OnlySnapshots: Boolean; LeaseId: String;
ResponseInfo: TCloudResponseInfo): boolean;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
QueryParams: TStringList;
Response: TCloudHTTP;
begin
if (ContainerName = EmptyStr) or (BlobName = EmptyStr) then
Exit(False);
ContainerName := AnsiLowerCase(ContainerName);
url := Format('%s/%s/%s', [GetConnectionInfo.BlobURL, ContainerName, URLEncode(BlobName)]);
Headers := TStringList.Create;
PopulateDateHeader(Headers, False);
QueryPrefix := GetBlobContainerQueryPrefix(Headers, ContainerName, URLEncode(BlobName));
QueryParams := nil;
if SnapShot <> EmptyStr then
begin
QueryParams := TStringList.Create;
QueryParams.Values['snapshot'] := 'SnapShot';
url := BuildQueryParameterString(url, QueryParams, False, True);
end
else
begin
//Controls if only the snapshots should be deleted, or the whole blob
if OnlySnapshots then
Headers.Values['x-ms-delete-snapshots'] := 'only'
else
Headers.Values['x-ms-delete-snapshots'] := 'include';
end;
Response := nil;
try
Response := IssueDeleteRequest(url, Headers, QueryParams, QueryPrefix, ResponseInfo);
Result := (Response <> nil) and (Response.ResponseCode = 202);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(QueryParams);
FreeAndNil(Headers);
end;
end;
function TAzureBlobService.DeleteContainer(ContainerName: String;
ResponseInfo: TCloudResponseInfo): boolean;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
QueryParams: TStringList;
Response: TCloudHTTP;
begin
ContainerName := AnsiLowerCase(ContainerName);
url := Format('%s/%s', [GetConnectionInfo.BlobURL, ContainerName]);
Headers := TStringList.Create;
PopulateDateHeader(Headers, False);
QueryPrefix := GetBlobContainerQueryPrefix(Headers, ContainerName);
QueryParams := TStringList.Create;
QueryParams.Values['restype'] := 'container';
url := BuildQueryParameterString(url, QueryParams, False, True);
Response := nil;
try
Response := IssueDeleteRequest(url, Headers, QueryParams, QueryPrefix, ResponseInfo);
Result := (Response <> nil) and (Response.ResponseCode = 202);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(QueryParams);
FreeAndNil(Headers);
end;
end;
function TAzureBlobService.DeleteRootContainer(ResponseInfo: TCloudResponseInfo): boolean;
begin
Result := DeleteContainer(ROOT_CONTAINER, ResponseInfo);
end;
function TAzureBlobService.GetBlobInternal(ContainerName, BlobName, Snapshot, LeaseId: String;
out Metadata, Properties: TStrings;
ResponseContent: TStream;
StartByte, EndByte: int64; GetAsHash: boolean;
ResponseInfo: TCloudResponseInfo): boolean;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
QueryParams: TStringList;
Response: TCloudHTTP;
FreeResponseInfo: Boolean;
I, Count: Integer;
CurrentHeaderName: String;
begin
Metadata := nil;
Properties := nil;
if (ContainerName = EmptyStr) or (BlobName = EmptyStr) then
Exit(False);
ContainerName := AnsiLowerCase(ContainerName);
url := Format('%s/%s/%s', [GetConnectionInfo.BlobURL, ContainerName, URLEncode(BlobName)]);
Headers := TStringList.Create;
PopulateDateHeader(Headers, False);
if LeaseId <> EmptyStr then
headers.Values['x-ms-lease-id'] := LeaseId;
QueryPrefix := GetBlobContainerQueryPrefix(Headers, ContainerName, URLEncode(BlobName));
QueryParams := nil;
if Snapshot <> EmptyStr then
begin
QueryParams := TStringList.Create;
QueryParams.Values['snapshot'] := 'Snapshot';
url := BuildQueryParameterString(url, QueryParams, False, True);
end;
//Populate Range, and possibly also x-ms-range-get-content-md5
if EndByte > StartByte then
begin
headers.Values['x-ms-range'] := Format('bytes=%d-%d', [StartByte, EndByte]);
if GetAsHash then
headers.Values['x-ms-range-get-content-md5'] := 'true'
end;
FreeResponseInfo := ResponseInfo = nil;
if FreeResponseInfo then
ResponseInfo := TCloudResponseInfo.Create;
Response := nil;
try
Response := IssueGetRequest(url, Headers, QueryParams, QueryPrefix, ResponseInfo, ResponseContent);
Result := (Response <> nil) and (Response.ResponseCode = 200);
//If the request was successful, populate the metadata and properties lists
if Result then
begin
Metadata := TStringList.Create;
Properties := TStringList.Create;
Count := ResponseInfo.Headers.Count;
for I := 0 to Count - 1 do
begin
CurrentHeaderName := ResponseInfo.Headers.Names[I];
if AnsiStartsText('x-ms-meta-', CurrentHeaderName) then
begin
//strip the "x-ms-meta-" prefix from the name of the header,
//to get the original metadata name, as entered by the user.
CurrentHeaderName := Copy(CurrentHeaderName, 11);
Metadata.Values[CurrentHeaderName] := ResponseInfo.Headers.ValueFromIndex[I];
end
else
Properties.Values[CurrentHeaderName] := ResponseInfo.Headers.ValueFromIndex[I];
end;
end;
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(QueryParams);
FreeAndNil(Headers);
if FreeResponseInfo then
ResponseInfo.Free;
end;
end;
function TAzureBlobService.GetBlob(ContainerName, BlobName: String; BlobStream: TStream; StartByte,
EndByte: int64; GetAsHash: boolean; const LeaseId: String;
ResponseInfo: TCloudResponseInfo): boolean;
var
Metadata: TStrings;
Properties: TStrings;
begin
try
Result := GetBlob(ContainerName, BlobName, BlobStream, Properties, Metadata,
StartByte, EndByte, GetAsHash, LeaseId, ResponseInfo);
finally
FreeAndNil(Metadata);
FreeAndNil(Properties);
end;
end;
function TAzureBlobService.GetBlob(ContainerName, BlobName: String; BlobStream: TStream; out Properties,
Metadata: TStrings; StartByte, EndByte: int64;
GetAsHash: boolean; const LeaseId: String;
ResponseInfo: TCloudResponseInfo): boolean;
begin
Result := GetBlobInternal(ContainerName, BlobName, '', LeaseId, Metadata, Properties,
BlobStream, StartByte, EndByte, GetAsHash, ResponseInfo);
end;
function TAzureBlobService.GetBlob(ContainerName, BlobName: String; BlobStream: TStream;
const LeaseId: String; ResponseInfo: TCloudResponseInfo): boolean;
var
Metadata: TStrings;
Properties: TStrings;
begin
try
Result := GetBlob(ContainerName, BlobName, BlobStream, Properties, Metadata, LeaseId, ResponseInfo);
finally
FreeAndNil(Metadata);
FreeAndNil(Properties);
end;
end;
function TAzureBlobService.GetBlob(ContainerName, BlobName: String; BlobStream: TStream;
out Properties, Metadata: TStrings; const LeaseId: String;
ResponseInfo: TCloudResponseInfo): boolean;
begin
Result := GetBlobInternal(ContainerName, BlobName, '', LeaseId, Metadata, Properties,
BlobStream, 0, 0, False, ResponseInfo);
end;
function TAzureBlobService.GetBlobSnapshot(ContainerName, BlobName, Snapshot: String; SnapshotStream: TStream;
StartByte, EndByte: int64; GetAsHash: boolean;
ResponseInfo: TCloudResponseInfo): boolean;
var
Metadata: TStrings;
Properties: TStrings;
begin
try
Result := GetBlobSnapshot(ContainerName, BlobName, Snapshot, SnapshotStream, Properties, Metadata,
StartByte, EndByte, GetAsHash, ResponseInfo);
finally
FreeAndNil(Metadata);
FreeAndNil(Properties);
end;
end;
function TAzureBlobService.GetBlobSnapshot(ContainerName, BlobName, Snapshot: String; SnapshotStream: TStream;
out Properties, Metadata: TStrings; StartByte, EndByte: int64;
GetAsHash: boolean;
ResponseInfo: TCloudResponseInfo): boolean;
begin
Result := GetBlobInternal(ContainerName, BlobName, Snapshot, '', Metadata, Properties,
SnapshotStream, StartByte, EndByte, GetAsHash, ResponseInfo);
end;
function TAzureBlobService.GetBlockListXML(ContainerName, BlobName: String;
BlockType: TAzureQueryIncludeBlockType;
const SnapShot, LeaseId: String; ResponseInfo: TCloudResponseInfo): String;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
QueryParams: TStringList;
Response: TCloudHTTP;
begin
if (ContainerName = EmptyStr) or (BlobName = EmptyStr) then
Exit(EmptyStr);
ContainerName := AnsiLowerCase(ContainerName);
Headers := TStringList.Create;
PopulateDateHeader(Headers, False);
if LeaseId <> EmptyStr then
Headers.Values['x-ms-lease-id'] := LeaseId;
QueryParams := TStringList.Create;
QueryParams.Values['comp'] := 'blocklist';
if Snapshot <> EmptyStr then
QueryParams.Values['snapshot'] := Snapshot;
if BlockType = aqbtUncommitted then
QueryParams.Values['blocklisttype'] := 'uncommitted'
else if BlockType = aqbtCommitted then
QueryParams.Values['blocklisttype'] := 'committed'
else if BlockType = aqbtAll then
QueryParams.Values['blocklisttype'] := 'all';
url := Format('%s/%s/%s', [GetConnectionInfo.BlobURL, ContainerName, URLEncode(BlobName)]);
url := BuildQueryParameterString(url, QueryParams, False, True);
QueryPrefix := GetBlobContainerQueryPrefix(Headers, ContainerName, URLEncode(BlobName));
Response := nil;
try
Response := IssueGetRequest(url, Headers, QueryParams, QueryPrefix, ResponseInfo, Result);
if (Response = nil) or (Response.ResponseCode <> 200) then
Result := '';
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(QueryParams);
FreeAndNil(Headers);
end;
end;
function TAzureBlobService.GetBlockList(ContainerName, BlobName: String;
BlockType: TAzureQueryIncludeBlockType;
const SnapShot, LeaseId: String;
ResponseInfo: TCloudResponseInfo): TList<TAzureBlockListItem>;
var
xml: String;
xmlDoc: IXMLDocument;
RootNode, ContainerNode: IXMLNode;
begin
Result := nil;
xml := GetBlockListXML(ContainerName, BlobName, BlockType, Snapshot, LeaseId, ResponseInfo);
if xml <> EmptyStr then
begin
Result := TList<TAzureBlockListItem>.Create;
xmlDoc := TXMLDocument.Create(nil);
xmlDoc.LoadFromXML(xml);
RootNode := xmlDoc.DocumentElement;
ContainerNode := GetFirstMatchingChildNode(RootNode, 'CommittedBlocks');
AddBlockItems(ContainerNode, Result, abtCommitted);
ContainerNode := GetFirstMatchingChildNode(RootNode, 'UncommittedBlocks');
AddBlockItems(ContainerNode, Result, abtUncommitted);
end;
end;
procedure TAzureBlobService.AddBlockItems(BlocksNode: IXMLNode; BlockList: TList<TAzureBlockListItem>;
BlockType: TAzureBlockType);
var
BlockNode, SubNode: IXMLNode;
Name, Size: String;
begin
if (BlockList = nil) or (BlocksNode = nil) or (not BlocksNode.HasChildNodes) then
Exit;
BlockNode := BlocksNode.ChildNodes.First;
while BlockNode <> nil do
begin
Name := '';
Size := '';
try
if BlockNode.HasChildNodes then
begin
SubNode := BlockNode.ChildNodes.First;
while SubNode <> nil do
begin
try
if AnsiSameText(SubNode.NodeName, 'Name') then
Name := SubNode.Text
else if AnsiSameText(SubNode.NodeName, 'Size') then
Size := SubNode.Text;
finally
SubNode := SubNode.NextSibling;
end;
end;
end;
finally
if (Name <> EmptyStr) and (Size <> EmptyStr) then
BlockList.Add(TAzureBlockListItem.Create(Name, BlockType, Size));
BlockNode := BlockNode.NextSibling;
end;
end;
end;
function TAzureBlobService.GetBlobSnapshot(ContainerName, BlobName, Snapshot: String; SnapshotStream: TStream;
ResponseInfo: TCloudResponseInfo): boolean;
var
Metadata: TStrings;
Properties: TStrings;
begin
try
Result := GetBlobSnapshot(ContainerName, BlobName, Snapshot, SnapshotStream, Properties, Metadata,
ResponseInfo);
finally
FreeAndNil(Metadata);
FreeAndNil(Properties);
end;
end;
function TAzureBlobService.GetBlobSnapshot(ContainerName, BlobName, Snapshot: String; SnapshotStream: TStream;
out Properties, Metadata: TStrings;
ResponseInfo: TCloudResponseInfo): boolean;
begin
Result := GetBlobInternal(ContainerName, BlobName, Snapshot, '', Metadata, Properties,
SnapshotStream, 0, 0, False, ResponseInfo);
end;
function TAzureBlobService.GetContainerProperties(ContainerName: String; out Properties: TStrings;
ResponseInfo: TCloudResponseInfo): boolean;
var
Metadata: TStrings;
begin
Result := GetContainerProperties(Containername, Properties, Metadata, ResponseInfo);
if Result then
FreeAndNil(Metadata);
end;
function TAzureBlobService.GetBlobContainerQueryPrefix(Headers: TStrings; ContainerName: String;
BlobName: String): String;
begin
if GetConnectionInfo.UseDevelopmentStorage then
Result := Format('/%s/%s/%s', [GetConnectionInfo.AccountName, GetConnectionInfo.AccountName, ContainerName])
else
begin
Headers.Values['x-ms-version'] := '2009-09-19';
Result := Format('/%s/%s', [GetConnectionInfo.AccountName, ContainerName]);
end;
if BlobName <> EmptyStr then
begin
Result := Result + '/' + BlobName;
end;
end;
function TAzureBlobService.GetBlobMetadata(ContainerName, BlobName: String; out Metadata: TStrings;
const Snapshot, LeaseId: String;
ResponseInfo: TCloudResponseInfo): boolean;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
QueryParams: TStringList;
Response: TCloudHTTP;
FreeResponseInfo: Boolean;
I, Count: Integer;
CurrentHeaderName: String;
begin
Metadata := nil;
ContainerName := AnsiLowerCase(ContainerName);
url := Format('%s/%s/%s', [GetConnectionInfo.BlobURL, ContainerName, URLEncode(BlobName)]);
Headers := TStringList.Create;
PopulateDateHeader(Headers, False);
if LeaseId <> EmptyStr then
headers.Values['x-ms-lease-id'] := LeaseId;
QueryPrefix := GetBlobContainerQueryPrefix(Headers, ContainerName, URLEncode(BlobName));
QueryParams := TStringList.Create;
QueryParams.Values['comp'] := 'metadata';
if Snapshot <> EmptyStr then
QueryParams.Values['snapshot'] := 'Snapshot';
url := BuildQueryParameterString(url, QueryParams, False, True);
FreeResponseInfo := ResponseInfo = nil;
if FreeResponseInfo then
ResponseInfo := TCloudResponseInfo.Create;
Response := nil;
try
Response := IssueGetRequest(url, Headers, QueryParams, QueryPrefix, ResponseInfo);
Result := (Response <> nil) and (Response.ResponseCode = 200);
if Result then
begin
Metadata := TStringList.Create;
Count := ResponseInfo.Headers.Count;
for I := 0 to Count - 1 do
begin
CurrentHeaderName := ResponseInfo.Headers.Names[I];
if AnsiStartsText('x-ms-meta-', CurrentHeaderName) then
begin
//strip the "x-ms-meta-" prefix from the name of the header,
//to get the original metadata header name, as entered by the user.
CurrentHeaderName := Copy(CurrentHeaderName, 11);
Metadata.Values[CurrentHeaderName] := ResponseInfo.Headers.ValueFromIndex[I];
end;
end;
end;
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(QueryParams);
FreeAndNil(Headers);
if FreeResponseInfo then
ResponseInfo.Free;
end;
end;
function TAzureBlobService.GetBlobProperties(ContainerName, BlobName: String; out Properties: TStrings;
const Snapshot, LeaseId: String;
ResponseInfo: TCloudResponseInfo): boolean;
var
Metadata: TStrings;
begin
Result := GetBlobProperties(ContainerName, BlobName, Properties, Metadata, Snapshot, LeaseId, ResponseInfo);
//We don't care about the Metadata, so free it.
FreeAndNil(Metadata);
end;
function TAzureBlobService.GetBlobProperties(ContainerName, BlobName: String; out Properties,
Metadata: TStrings; const Snapshot, LeaseId: String;
ResponseInfo: TCloudResponseInfo): boolean;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
QueryParams: TStringList;
Response: TCloudHTTP;
FreeResponseInfo: Boolean;
I, Count: Integer;
HeaderName: String;
begin
Properties := nil;
Metadata := nil;
if (ContainerName = EmptyStr) or (BlobName = EmptyStr) then
Exit(False);
ContainerName := AnsiLowerCase(ContainerName);
url := Format('%s/%s/%s', [GetConnectionInfo.BlobURL, ContainerName, URLEncode(BlobName)]);
Headers := TStringList.Create;
PopulateDateHeader(Headers, False);
if LeaseId <> EmptyStr then
headers.Values['x-ms-lease-id'] := LeaseId;
QueryPrefix := GetBlobContainerQueryPrefix(Headers, ContainerName, URLEncode(BlobName));
QueryParams := nil;
if Snapshot <> EmptyStr then
begin
QueryParams := TStringList.Create;
QueryParams.Values['snapshot'] := Snapshot;
end;
url := BuildQueryParameterString(url, QueryParams, False, True);
FreeResponseInfo := ResponseInfo = nil;
if FreeResponseInfo then
ResponseInfo := TCloudResponseInfo.Create;
Response := nil;
try
Response := IssueGetRequest(url, Headers, QueryParams, QueryPrefix, ResponseInfo);
Result := (Response <> nil) and (Response.ResponseCode = 200);
if Result then
begin
Properties := TStringList.Create;
Metadata := TStringList.Create;
//Populate the result lists based on the returned headers from the request
Count := ResponseInfo.Headers.Count;
for I := 0 to Count - 1 do
begin
HeaderName := ResponseInfo.Headers.Names[I];
//if a header name starts with x-ms-meta- then it is a metadata header.
//exclude the metadata header name prefix from the name returned as the metadata name
if AnsiStartsText('x-ms-meta-', HeaderName) and (Length(HeaderName) > 11) then
Metadata.Values[Copy(HeaderName, 11)] := ResponseInfo.Headers.ValueFromIndex[I]
else if not AnsiStartsText('x-ms-', HeaderName) then
Properties.Values[HeaderName] := ResponseInfo.Headers.ValueFromIndex[I];
end;
end;
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(QueryParams);
FreeAndNil(Headers);
if FreeResponseInfo then
ResponseInfo.Free;
end;
end;
function TAzureBlobService.GetContainerACLXML(ContainerName: String; out PublicAccess: TBlobPublicAccess;
ResponseInfo: TCloudResponseInfo): String;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
QueryParams: TStringList;
Response: TCloudHTTP;
PublicAccessString: String;
FreeResponseInfo: Boolean;
begin
PublicAccess := bpaPrivate;
ContainerName := AnsiLowerCase(ContainerName);
url := Format('%s/%s', [GetConnectionInfo.BlobURL, ContainerName]);
Headers := TStringList.Create;
PopulateDateHeader(Headers, False);
QueryPrefix := GetBlobContainerQueryPrefix(Headers, ContainerName);
QueryParams := TStringList.Create;
QueryParams.Values['restype'] := 'container';
QueryParams.Values['comp'] := 'acl';
url := BuildQueryParameterString(url, QueryParams, False, True);
FreeResponseInfo := ResponseInfo = nil;
if FreeResponseInfo then
ResponseInfo := TCloudResponseInfo.Create;
Response := nil;
try
Response := IssueGetRequest(url, Headers, QueryParams, QueryPrefix, ResponseInfo, Result);
PublicAccessString := ResponseInfo.Headers.Values['x-ms-blob-public-access'];
if PublicAccessString = 'container' then
PublicAccess := bpaContainer
else if PublicAccessString = 'blob' then
PublicAccess := bpaBlob;
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(QueryParams);
FreeAndNil(Headers);
if FreeResponseInfo then
ResponseInfo.Free;
end;
end;
function TAzureBlobService.GetContainerACL(ContainerName: String; out PublicAccess: TBlobPublicAccess;
ResponseInfo: TCloudResponseInfo): TList<TSignedIdentifier>;
var
xml: String;
xmlDoc: IXMLDocument;
RootNode, SidNode, ChildNode, SubChildNode: IXMLNode;
SignedIdentifier: TSignedIdentifier;
begin
Result := nil;
xml := GetContainerACLXML(ContainerName, PublicAccess, ResponseInfo);
if xml <> emptyStr then
begin
xmlDoc := TXMLDocument.Create(nil);
xmlDoc.LoadFromXML(xml);
RootNode := xmlDoc.DocumentElement;
if not RootNode.HasChildNodes then
Exit(nil);
Result := TList<TSignedIdentifier>.Create;
SidNode := RootNode.ChildNodes.First;
(*
The XML looks like this:
<SignedIdentifiers>
<SignedIdentifier>
<Id>unique-value</Id>
<AccessPolicy>
<Start>start-time</Start>
<Expiry>expiry-time</Expiry>
<Permission>abbreviated-permission-list</Permission>
</AccessPolicy>
</SignedIdentifier>
</SignedIdentifiers>
*)
while SidNode <> nil do
begin
try
if AnsiSameText(SidNode.NodeName, 'SignedIdentifier') then
begin
ChildNode := GetFirstMatchingChildNode(SidNode, 'Id');
if ChildNode <> nil then
begin
SignedIdentifier := TSignedIdentifier.Create(ContainerName);
SignedIdentifier.Id := ChildNode.Text;
Result.Add(SignedIdentifier);
ChildNode := GetFirstMatchingChildNode(SidNode, 'AccessPolicy');
if (ChildNode <> nil) and (ChildNode.HasChildNodes) then
begin
SubChildNode := ChildNode.ChildNodes.First;
while SubChildNode <> nil do
begin
try
if AnsiSameText(SubChildNode.NodeName, 'Start') then
SignedIdentifier.AccessPolicy.Start := SubChildNode.Text
else if AnsiSameText(SubChildNode.NodeName, 'Expiry') then
SignedIdentifier.AccessPolicy.Expiry := SubChildNode.Text
else if AnsiSameText(SubChildNode.NodeName, 'Permission') then
SignedIdentifier.AccessPolicy.Permission := SubChildNode.Text;
finally
SubChildNode := SubChildNode.NextSibling;
end;
end;
end;
end;
end;
finally
SidNode := SidNode.NextSibling;
end;
end;
end;
end;
function TAzureBlobService.GetContainerMetadata(ContainerName: String; out Metadata: TStrings;
ResponseInfo: TCloudResponseInfo): boolean;
var
Properties: TStrings;
begin
(*
Choosing to get all properties instead of just metadata, to reuse existing code.
As far as I can tell, the request and responses are identical, except that a call to get
metadata includes "&comp=metadata" in the URL and query parameters... even though all
headers are returned anyway, not just the metadata ones.
*)
Result := GetContainerProperties(Containername, Properties, Metadata, ResponseInfo);
if Result then
FreeAndNil(Properties);
end;
function TAzureBlobService.GetContainerProperties(ContainerName: String; out Properties,
Metadata: TStrings; ResponseInfo: TCloudResponseInfo): boolean;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
QueryParams: TStringList;
Response: TCloudHTTP;
FreeResponseInfo: Boolean;
I, Count: Integer;
HeaderName: String;
begin
if (ContainerName = EmptyStr) then
Exit(False);
Properties := nil;
Metadata := nil;
ContainerName := AnsiLowerCase(ContainerName);
url := Format('%s/%s', [GetConnectionInfo.BlobURL, ContainerName]);
Headers := TStringList.Create;
PopulateDateHeader(Headers, False);
QueryPrefix := GetBlobContainerQueryPrefix(Headers, ContainerName);
QueryParams := TStringList.Create;
QueryParams.Values['restype'] := 'container';
url := BuildQueryParameterString(url, QueryParams, False, True);
FreeResponseInfo := ResponseInfo = nil;
if FreeResponseInfo then
ResponseInfo := TCloudResponseInfo.Create;
Response := nil;
try
Response := IssueGetRequest(url, Headers, QueryParams, QueryPrefix, ResponseInfo);
Result := (Response <> nil) and (Response.ResponseCode = 200);
if Result then
begin
Properties := TStringList.Create;
Metadata := TStringList.Create;
//Populate the result lists based on the returned headers from the request
Count := ResponseInfo.Headers.Count;
for I := 0 to Count - 1 do
begin
HeaderName := ResponseInfo.Headers.Names[I];
//if a header name starts with x-ms-meta- then it is a metadata header.
//exclude the metadata header name prefix from the name returned as the metadata name
if AnsiStartsText('x-ms-meta-', HeaderName) and (Length(HeaderName) > 11) then
Metadata.Values[Copy(HeaderName, 11)] := ResponseInfo.Headers.ValueFromIndex[I]
else if not AnsiStartsText('x-ms-', HeaderName) then
Properties.Values[HeaderName] := ResponseInfo.Headers.ValueFromIndex[I];
end;
end;
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(QueryParams);
FreeAndNil(Headers);
if FreeResponseInfo then
ResponseInfo.Free;
end;
end;
function TAzureBlobService.GetPageRegionsXML(ContainerName, BlobName: String; const Snapshot, LeaseId: String;
ResponseInfo: TCloudResponseInfo): String;
begin
Result := GetPageRegionsXML(ContainerName, BlobName, 0, 0, Snapshot, LeaseId, ResponseInfo);
end;
function TAzureBlobService.GetPageRegionsXML(ContainerName, BlobName: String; StartByte, EndByte: Int64;
const Snapshot, LeaseId: String;
ResponseInfo: TCloudResponseInfo): String;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
QueryParams: TStringList;
Response: TCloudHTTP;
begin
if (ContainerName = EmptyStr) or (BlobName = EmptyStr) then
Result := '';
ContainerName := AnsiLowerCase(ContainerName);
url := Format('%s/%s/%s', [GetConnectionInfo.BlobURL, ContainerName, URLEncode(BlobName)]);
Headers := TStringList.Create;
PopulateDateHeader(Headers, False);
if LeaseId <> EmptyStr then
headers.Values['x-ms-lease-id'] := LeaseId;
if (StartByte >= 0) and (EndByte > StartByte) then
Headers.Values['x-ms-range'] := Format('bytes=%d-%d', [StartByte, EndByte]);
QueryPrefix := GetBlobContainerQueryPrefix(Headers, ContainerName, URLEncode(BlobName));
QueryParams := TStringList.Create;
QueryParams.Values['comp'] := 'pagelist';
//development storiage doesn't support the snapshot query parameter
if (Snapshot <> EmptyStr) and (not GetConnectionInfo.UseDevelopmentStorage) then
QueryParams.Values['snapshot'] := Snapshot;
url := BuildQueryParameterString(url, QueryParams, False, True);
Response := nil;
try
Response := IssueGetRequest(url, Headers, QueryParams, QueryPrefix, ResponseInfo, Result);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(QueryParams);
FreeAndNil(Headers);
end;
end;
function TAzureBlobService.GetPageRegions(ContainerName, BlobName: String; StartByte, EndByte: Int64;
const Snapshot, LeaseId: String;
ResponseInfo: TCloudResponseInfo): TList<TAzureBlobPageRange>;
var
xml: String;
xmlDoc: IXMLDocument;
RootNode, PRNode, StartNode, EndNode: IXMLNode;
StartS, EndS: String;
Item: TAzureBlobPageRange;
begin
Result := nil;
xml := GetPageRegionsXML(ContainerName, BlobName, StartByte, EndByte, Snapshot, LeaseId, ResponseInfo);
if xml <> EmptyStr then
begin
Result := TList<TAzureBlobPageRange>.Create;
xmlDoc := TXMLDocument.Create(nil);
xmlDoc.LoadFromXML(xml);
RootNode := xmlDoc.DocumentElement;
if (RootNode <> nil) and (RootNode.HasChildNodes) then
begin
PRNode := GetFirstMatchingChildNode(RootNode, 'PageRange');
while PRNode <> nil do
begin
try
StartNode := GetFirstMatchingChildNode(PRNode, 'Start');
EndNode := GetFirstMatchingChildNode(PRNode, 'End');
if (StartNode <> nil) and (EndNode <> nil) then
begin
StartS := StartNode.Text;
EndS := EndNode.Text;
try
Item := TAzureBlobPageRange.Create(StrToInt64(StartS), StrToInt64(EndS));
Result.Add(Item);
except
end;
end;
finally
PRNode := PRNode.NextSibling;
end;
end;
end;
end;
end;
function TAzureBlobService.GetPageRegions(ContainerName, BlobName: String; const Snapshot, LeaseId: String;
ResponseInfo: TCloudResponseInfo): TList<TAzureBlobPageRange>;
begin
Result := GetPageRegions(ContainerName, BlobName, 0, 0, Snapshot, LeaseId, ResponseInfo);
end;
function TAzureBlobService.GetPublicAccessString(PublicAccess: TBlobPublicAccess): String;
begin
if PublicAccess = bpaContainer then
Exit('container');
if PublicAccess = bpaBlob then
Exit('blob');
end;
function TAzureBlobService.HandleBlobLease(ContainerName, BlobName: String; const LeaseAction,
LeaseId: String; SuccessCode: Integer; out Success: boolean;
ResponseInfo: TCloudResponseInfo): String;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
QueryParams: TStringList;
Response: TCloudHTTP;
FreeResponseInfo: Boolean;
begin
Success := False;
if (ContainerName = EmptyStr) or (BlobName = EmptyStr) then
Exit('');
ContainerName := AnsiLowerCase(ContainerName);
url := Format('%s/%s/%s', [GetConnectionInfo.BlobURL, ContainerName, URLEncode(BlobName)]);
Headers := TStringList.Create;
PopulateDateHeader(Headers, False);
headers.Values['Content-Length'] := '0';
headers.Values['x-ms-lease-action'] := LeaseAction;
if LeaseId <> EmptyStr then
headers.Values['x-ms-lease-id'] := LeaseId;
QueryPrefix := GetBlobContainerQueryPrefix(Headers, ContainerName, URLEncode(BlobName));
QueryParams := TStringList.Create;
QueryParams.Values['comp'] := 'lease';
url := BuildQueryParameterString(url, QueryParams, False, True);
FreeResponseInfo := ResponseInfo = nil;
if FreeResponseInfo then
ResponseInfo := TCloudResponseInfo.Create;
Response := nil;
try
Response := IssuePutRequest(url, Headers, QueryParams, QueryPrefix, ResponseInfo);
Success := Response.ResponseCode = SuccessCode;
if Success then
Result := ResponseInfo.Headers.Values['x-ms-lease-id'];
finally
if Assigned(Response) then
FreeAndNil(Response);
if FreeResponseInfo then
ResponseInfo.Free;
FreeAndNil(QueryParams);
FreeAndNil(Headers);
end;
end;
function TAzureBlobService.AcquireBlobLease(ContainerName, BlobName: String; out LeaseId: String;
ResponseInfo: TCloudResponseInfo): boolean;
begin
LeaseId := HandleBlobLease(ContainerName, BlobName, 'acquire', '', 201, Result, ResponseInfo);
end;
function TAzureBlobService.RenewBlobLease(ContainerName, BlobName: String; const LeaseId: String;
ResponseInfo: TCloudResponseInfo): boolean;
begin
HandleBlobLease(ContainerName, BlobName, 'renew', LeaseId, 200, Result, ResponseInfo);
end;
function TAzureBlobService.ReleaseBlobLease(ContainerName, BlobName: String; const LeaseId: String;
ResponseInfo: TCloudResponseInfo): boolean;
begin
HandleBlobLease(ContainerName, BlobName, 'release', LeaseId, 200, Result, ResponseInfo);
end;
function TAzureBlobService.BreakBlobLease(ContainerName, BlobName: String; out LeaseTimeRemaining: Integer;
ResponseInfo: TCloudResponseInfo): boolean;
var
FreeResponseInfo: Boolean;
TimeRemaining: String;
begin
LeaseTimeRemaining := -1;
FreeResponseInfo := ResponseInfo = nil;
if FreeResponseInfo then
ResponseInfo := TCloudResponseInfo.Create;
try
HandleBlobLease(ContainerName, BlobName, 'break', '', 202, Result, ResponseInfo);
if Result then
begin
TimeRemaining := ResponseInfo.Headers.Values['x-ms-lease-time: seconds'];
if TimeRemaining <> EmptyStr then
try
LeasetimeRemaining := StrToInt(TimeRemaining);
except
end;
end;
finally
if FreeResponseInfo then
ResponseInfo.Free;
end;
end;
function TAzureBlobService.ListBlobs(ContainerName: String; OptionalParams: TStrings;
ResponseInfo: TCloudResponseInfo): TList<TAzureBlob>;
var
NextMarker: String;
begin
Result := ListBlobs(ContainerName, NextMarker, OptionalParams, ResponseInfo);
end;
function TAzureBlobService.ListBlobs(ContainerName: String; out NextMarker: String;
OptionalParams: TStrings;
ResponseInfo: TCloudResponseInfo): TList<TAzureBlob>;
var
xml: String;
xmlDoc: IXMLDocument;
RootNode, BlobsNode, BlobNode, Aux: IXMLNode;
ABlob: TAzureBlob;
BlobName, BlobURL, BlobSnapshot: String;
BlobType: TAzureBlobType;
Properties, Metadata: TStrings;
LeaseStatus: TAzureLeaseStatus;
AuxString: String;
begin
Result := nil;
Properties := nil;
Metadata := nil;
xml := ListBlobsXML(ContainerName, OptionalParams, ResponseInfo);
if xml <> EmptyStr then
begin
Result := TList<TAzureBlob>.Create;
xmlDoc := TXMLDocument.Create(nil);
xmlDoc.LoadFromXML(xml);
RootNode := xmlDoc.DocumentElement;
//First load the continuation token, if there is any.
Aux := GetFirstMatchingChildNode(RootNode, 'NextMarker');
if (Aux <> nil) and (Aux.IsTextElement) then
NextMarker := Aux.Text;
//Then iterate the list of blobs
BlobsNode := GetFirstMatchingChildNode(RootNode, 'Blobs');
if (BlobsNode <> nil) and (BlobsNode.HasChildNodes) then
begin
BlobNode := BlobsNode.ChildNodes.First;
while BlobNode <> nil do
begin
try
//If the node is a 'BlobPrefix' node, instead of a full blob, just get the prefix name
//this is used for virtual-drectory iteration througha blob list, using 'prefix' and 'delimiter'
if AnsiSameText(BlobNode.NodeName, 'BlobPrefix') then
begin
Aux := GetFirstMatchingChildNode(BlobNode, 'Name');
if (Aux <> nil) and Aux.IsTextElement then
begin
//create a 'prefix' blob and add it to the result
//this is a placeholder for all blobs that have names starting
//with the specified prefix, and containing the specified delimiter
Result.Add(TAzureBlob.Create(Aux.Text, abtPrefix));
end;
end
//Otherwise, if it is a regular blob element, parse a full blob
else if AnsiSameText(BlobNode.NodeName, 'Blob') then
begin
Aux := BlobNode.ChildNodes.First;
while Aux <> nil do
begin
try
if AnsiSameText(Aux.NodeName, 'Name') then
BlobName := Aux.Text
else if AnsiSameText(Aux.NodeName, 'Snapshot') then
BlobSnapshot := Aux.Text
else if AnsiSameText(Aux.NodeName, 'Url') then
BlobURL := Aux.Text
else if AnsiSameText(Aux.NodeName, 'Properties') then
Properties := LoadChildrenAsProperties(Aux)
else if AnsiSameText(Aux.NodeName, 'Metadata') then
Metadata := LoadChildrenAsProperties(Aux);
finally
Aux := Aux.NextSibling;
end;
end;
//take the values passed in, read 'BlobType' and 'LeaseStatus' from the properties list,
//build the blob object, and add it to the result.
if (BlobName <> EmptyStr) and (BlobURL <> EmptyStr) and (Properties <> nil) then
begin
BlobType := abtBlock;
LeaseStatus := alsUnlocked;
//get the BlobType from the properties
AuxString := Properties.Values['BlobType'];
if AnsiSameText(AuxString, 'PageBlob') then
BlobType := abtPage;
//get the LeaseStatus from the properties
AuxString := Properties.Values['LeaseStatus'];
if AnsiSameText(AuxString, 'locked') then
LeaseStatus := alsLocked;
ABlob := TAzureBlob.Create(BlobName, BlobType, BlobURL, LeaseStatus, BlobSnapshot);
ABlob.Properties.AddStrings(Properties);
if Metadata <> nil then
ABlob.Metadata.AddStrings(Metadata);
//Add the blob to the list of blobs
Result.Add(ABlob);
end;
end;
finally
FreeAndNil(Metadata);
FreeAndNil(Properties);
BlobNode := BlobNode.NextSibling;
end;
end;
end;
end;
end;
function TAzureBlobService.ListBlobsXML(ContainerName: String; OptionalParams: TStrings;
ResponseInfo: TCloudResponseInfo): String;
var
url: String;
Headers: TStringList;
QueryPrefix: String;
QueryParams: TStringList;
Response: TCloudHTTP;
begin
ContainerName := AnsiLowerCase(ContainerName);
url := Format('%s/%s', [GetConnectionInfo.BlobURL, ContainerName]);
Headers := TStringList.Create;
PopulateDateHeader(Headers, False);
QueryPrefix := GetBlobContainerQueryPrefix(Headers, ContainerName);
QueryParams := TStringList.Create;
if OptionalParams <> nil then
QueryParams.AddStrings(OptionalParams);
QueryParams.Values['restype'] := 'container';
QueryParams.Values['comp'] := 'list';
url := BuildQueryParameterString(url, QueryParams, False, True);
Response := nil;
try
Response := IssueGetRequest(url, Headers, QueryParams, QueryPrefix, ResponseInfo, Result);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(QueryParams);
FreeAndNil(Headers);
end;
end;
function TAzureBlobService.ListContainers(OptionalParams: TStrings;
ResponseInfo: TCloudResponseInfo): TList<TAzureContainer>;
var
NextMarker: String;
begin
Result := ListContainers(NextMarker, OptionalParams, ResponseInfo);
end;
function TAzureBlobService.ListContainers(out NextMarker: String; OptionalParams: TStrings;
ResponseInfo: TCloudResponseInfo): TList<TAzureContainer>;
var
xml: String;
xmlDoc: IXMLDocument;
RootNode, ContainersNode, ContainerNode: IXMLNode;
Container: TAzureContainer;
begin
Result := nil;
xml := ListContainersXML(OptionalParams, ResponseInfo);
if xml <> EmptyStr then
begin
Result := TList<TAzureContainer>.Create;
xmlDoc := TXMLDocument.Create(nil);
xmlDoc.LoadFromXML(xml);
RootNode := xmlDoc.DocumentElement;
if (RootNode <> nil) and (RootNode.HasChildNodes) then
begin
ContainersNode := GetFirstMatchingChildNode(RootNode, 'Containers');
if (ContainersNode <> nil) and ContainersNode.HasChildNodes then
begin
ContainerNode := ContainersNode.ChildNodes.First;
while ContainerNode <> nil do
begin
try
Container := ParseContainerFromContainerNode(ContainerNode);
if Container <> nil then
Result.Add(Container);
finally
ContainerNode := ContainerNode.NextSibling;
end;
end;
end;
end;
end;
end;
{ TAzureContainer }
constructor TAzureContainer.Create(const Name, URL: String; Properties, Metadata: TStrings);
begin
FName := Name;
FURL := URL;
if Properties = nil then
FProperties := TStringList.Create
else
FProperties := Properties;
if Metadata = nil then
FMetadata := TStringList.Create
else
FMetadata := Metadata;
end;
destructor TAzureContainer.Destroy;
begin
FreeAndNil(FProperties);
FreeAndNil(FMetadata);
inherited;
end;
function TAzureContainer.IsRoot: Boolean;
begin
Result := Name = ROOT_CONTAINER;
end;
{ TAccessPolicy }
class function TAccessPolicy.Create: TAccessPolicy;
var
ap: TAccessPolicy;
begin
ap.Start := FormatDateTime('yyyy-mm-dd', Now);
ap.SetPermission('r');
Exit(ap);
end;
function TAccessPolicy.AsXML: String;
begin
Result := '<AccessPolicy><Start>' + Start + '</Start><Expiry>' + Expiry +
'</Expiry><Permission>' + Permission + '</Permission></AccessPolicy>';
end;
function TAccessPolicy.GetPermission: String;
begin
Result := '';
if PermRead then
Result := Result + 'r';
if PermWrite then
Result := Result + 'w';
if PermDelete then
Result := Result + 'd';
if PermList then
Result := Result + 'l';
end;
procedure TAccessPolicy.SetPermission(const rwdl: String);
var
i, count: Integer;
begin
count := Length(rwdl);
PermRead := false;
PermWrite := false;
PermDelete := false;
PermList := false;
for i := 1 to count do
if rwdl[i] = 'r' then
PermRead := true
else if rwdl[i] = 'w' then
PermWrite := true
else if rwdl[i] = 'd' then
PermDelete := true
else if rwdl[i] = 'l' then
PermList := true;
end;
{ TSignedIdentifier }
constructor TSignedIdentifier.Create(const Resource: String);
begin
FResource := Resource;
AccessPolicy.PermRead := false;
AccessPolicy.PermWrite := false;
AccessPolicy.PermDelete := false;
AccessPolicy.PermList := false;
end;
constructor TSignedIdentifier.Create(const Resource: String; Policy: TAccessPolicy; UniqueId: String);
begin
FResource := Resource;
AccessPolicy := Policy;
FId := UniqueId;
end;
function TSignedIdentifier.AsXML: String;
begin
Result := '<SignedIdentifier><Id>' + Id + '</Id>' + AccessPolicy.AsXML + '</SignedIdentifier>';
end;
{ TAzureBlob }
constructor TAzureBlob.Create(const Name: String; BlobType: TAzureBlobType; const Url: String;
LeaseStatus: TAzureLeaseStatus; const Snapshot: String);
begin
FName := Name;
FBlobType := BlobType;
FUrl := Url;
FLeaseStatus := LeaseStatus;
FSnapshot := Snapshot;
FProperties := TStringList.Create;
FMetadata := TStringList.Create;
end;
destructor TAzureBlob.Destroy;
begin
FreeAndNil(FProperties);
FreeAndnil(FMetadata);
inherited;
end;
{ TBlobActionConditional }
class function TBlobActionConditional.Create: TBlobActionConditional;
var
Inst: TBlobActionConditional;
begin
Exit(Inst);
end;
procedure TBlobActionConditional.PopulateHeaders(Headers: TStrings);
begin
if Headers <> nil then
begin
if IfSourceModifiedSince <> EmptyStr then
Headers.Values['x-ms-source-if-modified-since'] := IfSourceModifiedSince;
if IfSourceUnmodifiedSince <> EmptyStr then
Headers.Values['x-ms-source-if-unmodified-since'] := IfSourceUnmodifiedSince;
if IfSourceMatch <> EmptyStr then
Headers.Values['x-ms-source-if-match'] := IfSourceMatch;
if IfSourceNoneMatch <> EmptyStr then
Headers.Values['x-ms-source-if-none-match'] := IfSourceNoneMatch;
if IfModifiedSince <> EmptyStr then
Headers.Values['If-Modified-Since'] := IfModifiedSince;
if IfUnmodifiedSince <> EmptyStr then
Headers.Values['If-Unmodified-Since'] := IfUnmodifiedSince;
if IfMatch <> EmptyStr then
Headers.Values['If-Match'] := IfMatch;
if IfNoneMatch <> EmptyStr then
Headers.Values['If-None-Match'] := IfNoneMatch;
if IfSequenceNumberLessThanOrEqual <> EmptyStr then
Headers.Values['x-ms-if-sequence-number-lte'] := IfSequenceNumberLessThanOrEqual;
if IfSequenceNumberLessThan <> EmptyStr then
Headers.Values['x-ms-if-sequence-number-lt'] := IfSequenceNumberLessThan;
if IfSequenceNumberEquals <> EmptyStr then
Headers.Values['x-ms-if-sequence-number-eq'] := IfSequenceNumberEquals;
end;
end;
{ TAzureBlockListItem }
class function TAzureBlockListItem.Create(ABlockId: String; ABlockType: TAzureBlockType;
ASize: String): TAzureBlockListItem;
var
abli: TAzureBlockListItem;
begin
abli.BlockId := ABlockId;
abli.BlockType := ABlockType;
abli.Size := ASize;
Result := abli;
end;
function TAzureBlockListItem.AsXML: String;
var
TagName: String;
begin
case BlockType of
abtUncommitted: TagName := 'Uncommitted';
abtLatest: TagName := 'Latest';
else
TagName := 'Committed';
end;
Result := Format('<%s>%s</%0:s>', [TagName, XMLEscape(BlockId)]);
end;
{ TAzureBlobPageRange }
class function TAzureBlobPageRange.Create(StartByte, EndByte: Int64): TAzureBlobPageRange;
var
res: TAzureBlobPageRange;
begin
res.StartByte := StartByte;
res.EndByte := EndByte;
Exit(res);
end;
function TAzureBlobPageRange.GetPageCount: Integer;
var
ByteCount: Int64;
begin
ByteCount := EndByte - StartByte;
//get the page count, which may or may not be one fewer than it needs to be
Result := Trunc(ByteCount / 512);
//Determine if the current PageCount is correct, or if one more page is needed.
if (ByteCount Mod 512) <> 0 then
Inc(Result);
end;
function TAzureBlobPageRange.GetStartPage: Integer;
begin
Result := Trunc(StartByte / 512);
end;
end.
|
unit MapFieldsUnit;
interface
uses System.Generics.Collections;
type
TFieldsMap = class(TObject)
private
FMapDictionary: TDictionary<String, String>;
public
constructor Create(AFieldsMap: string);
destructor Destroy; override;
function Map(const ASourceFieldName: String): string;
end;
implementation
uses System.SysUtils;
constructor TFieldsMap.Create(AFieldsMap: string);
var
m: TArray<String>;
m2: TArray<String>;
S: string;
begin
inherited Create;
FMapDictionary := TDictionary<String, String>.Create;
m := AFieldsMap.Split([';']);
for S in m do
begin
m2 := S.Split(['->']);
// Каждый переход поля состоит из двух названий полей
Assert(Length(m2) = 2);
// Добавляем переход в словарь
FMapDictionary.Add(m2[0].ToUpper, m2[1].ToUpper);
end;
end;
destructor TFieldsMap.Destroy;
begin
inherited;
FreeAndNil(FMapDictionary);
end;
function TFieldsMap.Map(const ASourceFieldName: String): string;
begin
Assert(not ASourceFieldName.IsEmpty);
Result := ASourceFieldName.ToUpper;
if FMapDictionary.ContainsKey(Result) then
Result := FMapDictionary[Result].ToUpper;
end;
end.
|
unit luahelp;
interface
uses sysutils, System.Generics.Collections;
type
TNameFileMap = TDictionary<string, string>;
var
luaWorkScripts: TNameFileMap;
procedure InitLuaScriptFiles;
implementation
uses classes, myutils, StrUtils, System.Types;
function LuaPath: string;
begin
result := ExtractFileDir(ParamStr(0));
end;
function TrimLeadingCommentSymbols(s: string): string;
begin
while (length(s) > 0) AND (s[1] = '-') do
s := Copy(s, 2, length(s) - 1);
result := Trim(s);
end;
function ReadFirstLine(filename: string): string;
var
AFile: TStreamReader;
begin
result := '';
AFile := TStreamReader.Create(filename, TEncoding.UTF8, True);
try
result := AFile.ReadLine;
finally
AFile.Free;
end;
end;
function joinStrsAt(xs: TStringDynArray; n: integer): string;
begin
result := string.Join(': ', xs, n, length(xs) - n);
end;
procedure InitLuaScriptFiles;
var
SR: TSearchRec;
AFiles: Tarray<string>;
AFileName2, AStr, AFileName, ALine, AScripType: string;
xs: TStringDynArray;
I: integer;
AMap: TNameFileMap;
begin
luaWorkScripts := TNameFileMap.Create;
AFiles := myutils.FindAllFilesInDir(LuaPath, '*.*');
for AFileName in AFiles do
begin
if ExtractFileExt(AFileName) <> '.lua' then
continue;
ALine := ReadFirstLine(AFileName);
xs := StrUtils.SplitString(TrimLeadingCommentSymbols(ALine), ':');
if length(xs) < 3 then
continue;
for I := 0 to length(xs) - 1 do
xs[I] := Trim(xs[I]);
if Trim(xs[0]) <> 'atool' then
continue;
AStr := joinStrsAt(xs, 2);
AMap := nil;
AScripType := Trim(xs[1]);
if AScripType = 'work' then
AMap := luaWorkScripts;
if AMap <> nil then
begin
if AMap.TryGetValue(AStr, AFileName2) then
begin
if AFileName = AFileName2 then
continue;
raise Exception.Create('Дублирование метаданных скрипта: '#10#10
+ ALine + #10#10 + AFileName + #10#10 + AFileName2);
end;
AMap.Add(AStr, AFileName);
end;
end;
end;
end.
|
unit Ths.Erp.Database.Table.ParaBirimi;
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
TParaBirimi = class(TTable)
private
FKod: TFieldDB;
FSembol: TFieldDB;
FAciklama: TFieldDB;
FIsVarsayilan: TFieldDB;
protected
procedure BusinessUpdate(pPermissionControl: Boolean);override;
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 Kod: TFieldDB read FKod write FKod;
property Sembol: TFieldDB read FSembol write FSembol;
property Aciklama: TFieldDB read FAciklama write FAciklama;
property IsVarsayilan: TFieldDB read FIsVarsayilan write FIsVarsayilan;
end;
implementation
uses
Ths.Erp.Constants,
Ths.Erp.Database.Singleton;
constructor TParaBirimi.Create(OwnerDatabase:TDatabase);
begin
inherited Create(OwnerDatabase);
TableName := 'para_birimi';
SourceCode := '1000';
FKod := TFieldDB.Create('kod', ftString, '');
FSembol := TFieldDB.Create('sembol', ftString, '');
FAciklama := TFieldDB.Create('aciklama', ftString, '');
FIsVarsayilan := TFieldDB.Create('is_varsayilan', ftBoolean, False);
end;
procedure TParaBirimi.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 + '.' + FKod.FieldName,
TableName + '.' + FSembol.FieldName,
TableName + '.' + FAciklama.FieldName,
TableName + '.' + FIsVarsayilan.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
Active := True;
Self.DataSource.DataSet.FindField(Self.Id.FieldName).DisplayLabel := 'ID';
Self.DataSource.DataSet.FindField(FKod.FieldName).DisplayLabel := 'Kod';
Self.DataSource.DataSet.FindField(FSembol.FieldName).DisplayLabel := 'Sembol';
Self.DataSource.DataSet.FindField(FAciklama.FieldName).DisplayLabel := 'Açıklama';
Self.DataSource.DataSet.FindField(FIsVarsayilan.FieldName).DisplayLabel := 'Varsayılan?';
end;
end;
end;
procedure TParaBirimi.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 + '.' + FKod.FieldName,
TableName + '.' + FSembol.FieldName,
TableName + '.' + FAciklama.FieldName,
TableName + '.' + FIsVarsayilan.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);
FKod.Value := FormatedVariantVal(FieldByName(FKod.FieldName).DataType, FieldByName(FKod.FieldName).Value);
FSembol.Value := FormatedVariantVal(FieldByName(FSembol.FieldName).DataType, FieldByName(FSembol.FieldName).Value);
FAciklama.Value := FormatedVariantVal(FieldByName(FAciklama.FieldName).DataType, FieldByName(FAciklama.FieldName).Value);
FIsVarsayilan.Value := FormatedVariantVal(FieldByName(FIsVarsayilan.FieldName).DataType, FieldByName(FIsVarsayilan.FieldName).Value);
List.Add(Self.Clone());
Next;
end;
EmptyDataSet;
Close;
end;
end;
end;
procedure TParaBirimi.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, [
FKod.FieldName,
FSembol.FieldName,
FAciklama.FieldName,
FIsVarsayilan.FieldName
]);
NewParamForQuery(QueryOfInsert, FKod);
NewParamForQuery(QueryOfInsert, FSembol);
NewParamForQuery(QueryOfInsert, FAciklama);
NewParamForQuery(QueryOfInsert, FIsVarsayilan);
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 TParaBirimi.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, [
FKod.FieldName,
FSembol.FieldName,
FAciklama.FieldName,
FIsVarsayilan.FieldName
]);
NewParamForQuery(QueryOfUpdate, FKod);
NewParamForQuery(QueryOfUpdate, FSembol);
NewParamForQuery(QueryOfUpdate, FAciklama);
NewParamForQuery(QueryOfUpdate, FIsVarsayilan);
NewParamForQuery(QueryOfUpdate, Id);
ExecSQL;
Close;
end;
Self.notify;
end;
end;
procedure TParaBirimi.BusinessUpdate(pPermissionControl: Boolean);
var
vPara: TParaBirimi;
n1: Integer;
begin
if (IsVarsayilan.Value) then
begin
vPara := TParaBirimi.Create(Database);
try
vPara.SelectToList('', False, False);
for n1 := 0 to vPara.List.Count-1 do
begin
TParaBirimi(vPara.List[n1]).IsVarsayilan.Value := False;
TParaBirimi(vPara.List[n1]).Update;
end;
finally
vPara.Free;
end;
end;
Self.Update();
end;
function TParaBirimi.Clone():TTable;
begin
Result := TParaBirimi.Create(Database);
Self.Id.Clone(TParaBirimi(Result).Id);
FKod.Clone(TParaBirimi(Result).FKod);
FSembol.Clone(TParaBirimi(Result).FSembol);
FAciklama.Clone(TParaBirimi(Result).FAciklama);
FIsVarsayilan.Clone(TParaBirimi(Result).FIsVarsayilan);
end;
end.
|
unit IdFTPListParsePCTCP;
interface
{$i IdCompilerDefines.inc}
uses
Classes,
IdFTPList, IdFTPListParseBase;
type
TIdPCTCPFTPListItem = class(TIdFTPListItem);
TIdFTPLPPCTCPNet = class(TIdFTPListBase)
protected
class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override;
class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override;
public
class function GetIdent : String; override;
class function CheckListing(AListing : TStrings; const ASysDescript : String = ''; const ADetails : Boolean = True): Boolean; override;
end;
(*HPPEMIT '#pragma link "IdFTPListParseWinQVTNET"'*)
// RLebeau 2/14/09: this forces C++Builder to link to this unit so
// RegisterFTPListParser can be called correctly at program startup...
(*$HPPEMIT '#pragma link "IdFTPListParseWinQVTNET"'*)
{
THis is a parser for "PC/TCP v 2.11 ftpsrv.exe". This was a part of the PC/TCP
suite from FTP Software Inc.
based on
http://www.farmanager.com/viewvc/plugins/ftp/trunk/lib/DirList/pr_pctcp.cpp?revision=275&view=markup&pathrev=788
Note that no source-code was used, just the listing data.
PC/TCP ftpsrv.exe
looks like
1 2 3 4 5 6
0123456789012345678901234567890123456789012345678901234567890
-------------------------------------------------------------
1 2 3 4 5 6
123456789012345678901234567890123456789012345678901234567890
-------------------------------------------------------------
40774 IO.SYS Tue May 31 06:22:00 1994
38138 MSDOS.SYS Tue May 31 06:22:00 1994
54645 COMMAND.COM Tue May 31 06:22:00 1994
<dir> UTIL Thu Feb 20 09:55:02 2003
}
implementation
uses
IdGlobal, IdFTPCommon, IdGlobalProtocols,
SysUtils;
{ TIdFTPLPPCTCPNet }
class function TIdFTPLPPCTCPNet.CheckListing(AListing: TStrings;
const ASysDescript: String; const ADetails: Boolean): Boolean;
var
LData : String;
begin
Result := False;
if AListing.Count > 0 then begin
LData := AListing[0];
//size or dir
Result := (LData ='<dir>') or IsNumeric(Trim(Copy(LData,1,10)));
//file name
if Result then begin
Result := Trim(Copy(LData,11,19))<> '';
end;
//day of week
if Result then begin
Result := StrToDay(Trim(Copy(LData,31,7))) > 0;
end;
//month
if Result then begin
Result := StrToMonth(Copy(LData,38,3)) > 0;
end;
//day
if Result then begin
Result := StrToIntDef(Copy(LData,42,2),0) > 0;
end;
//time
if Result then begin
Result := IsHHMMSS(Copy(LData,45,8),':');
end;
//year
if Result then begin
Result := IsNumeric(Trim(Copy(LData,54,4)));
end;
end;
end;
class function TIdFTPLPPCTCPNet.GetIdent: String;
begin
Result := 'PC/TCP ftpsrv.exe';
end;
class function TIdFTPLPPCTCPNet.MakeNewItem(
AOwner: TIdFTPListItems): TIdFTPListItem;
begin
Result := TIdPCTCPFTPListItem.Create(AOwner);
end;
class function TIdFTPLPPCTCPNet.ParseLine(const AItem: TIdFTPListItem;
const APath: String): Boolean;
var LData : String;
LPt : String;
LMonth : Word;
LDay : Word;
LYear : Word;
begin
Result := False;
LData := TrimLeft(AItem.Data);
LPt := Fetch(LData);
//dir or file size
if LPt = '<dir>' then begin
AItem.ItemType := ditDirectory;
AItem.SizeAvail := False;
end else begin
if IsNumeric(LPt) then begin
AItem.Size := StrToIntDef(LPt,0);
AItem.SizeAvail := True;
end else begin
exit;
end;
end;
//file name
LData := TrimLeft(LData);
LPt := Fetch(LData);
if LPt = '' then begin
Exit;
end else begin
AItem.FileName := LPt;
end;
//Day of week
LData := TrimLeft(LData);
LPt := Fetch(LData);
if StrToDay(LPt) < 1 then begin
exit;
end;
//month
LData := TrimLeft(LData);
LPt := Fetch(LData);
LMOnth := StrToMonth(LPt);
if LMonth < 1 then begin
exit;
end;
//day
LData := TrimLeft(LData);
LPt := Fetch(LData);
LDay := StrToIntDef(LPt,0);
if LDay = 0 then begin
exit;
end;
//time
LData := TrimLeft(LData);
LPt := Fetch(LData);
if not IsHHMMSS(LPt,':') then begin
exit;
end;
AItem.ModifiedDate := TimeHHMMSS(LPt);
//year
LData := TrimLeft(LData);
LPt := Fetch(LData);
LYear := StrToIntDef(LPt,$FFFF);
if LYear = $FFFF then begin
Exit;
end;
LYear := Y2Year(LYear);
AItem.ModifiedDate := AItem.ModifiedDate + EncodeDate(LYear,LMonth,LDay);
AItem.ModifiedAvail := True;
Result := True;
end;
initialization
RegisterFTPListParser(TIdFTPLPPCTCPNet);
finalization
UnRegisterFTPListParser(TIdFTPLPPCTCPNet);
end.
|
unit UntDMGeral;
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.MySQL,
FireDAC.Phys.MySQLDef, FireDAC.VCLUI.Wait, FireDAC.Stan.StorageJSON, Data.DB,
FireDAC.Comp.Client,
IniFiles, FireDAC.Comp.UI;
type
TDMGeral = class(TDataModule)
fdConn: TFDConnection;
fdDriverMySQL: TFDPhysMySQLDriverLink;
fdStorageJSON: TFDStanStorageJSONLink;
FDGUIxWaitCursor1: TFDGUIxWaitCursor;
procedure DataModuleCreate(Sender: TObject);
private
{ Private declarations }
FIP : String;
FPorta : Integer;
FDatabase : String;
FUsuario : String;
FSenha : String;
FLib : String;
procedure LerConfig;
public
{ Public declarations }
property IP : String read FIP write FIP;
property Porta : Integer read FPorta write FPorta;
property Database : String read FDatabase write FDatabase;
property Usuario : String read FUsuario write FUsuario;
property Senha : String read FSenha write FSenha;
property Lib : String read FLib write FLib;
end;
var
DMGeral: TDMGeral;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
{ TDMGeral }
procedure TDMGeral.DataModuleCreate(Sender: TObject);
begin
LerConfig;
end;
procedure TDMGeral.LerConfig;
var
IniFile : TIniFile;
begin
//
try
try
IniFile := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'Config.ini');
IP := IniFile.ReadString('DATABASE', 'DatabasePath', EmptyStr);
Porta := IniFile.ReadInteger('DATABASE', 'DatabasePort', 0);
Database := IniFile.ReadString('DATABASE', 'DatabaseName', EmptyStr);
Usuario := IniFile.ReadString('DATABASE', 'DatabaseUser', EmptyStr);
Senha := IniFile.ReadString('DATABASE', 'DatabasePass', EmptyStr);
Lib := IniFile.ReadString('DATABASE', 'DatabaseLib', EmptyStr);
fdConn.Connected := False;
fdConn.Params.Values['Database'] := Database;
fdConn.Params.Values['Server'] := IP;
fdConn.Params.Values['Port'] := Porta.ToString;
fdConn.Params.Values['User_Name'] := Usuario;
fdConn.Params.Values['Password'] := Senha;
fdDriverMySQL.VendorLib := Lib;
except on E:Exception do
begin
end;
end;
finally
//FreeAndNil(IniFile);
IniFile.Free;
IniFile := nil;
end;
end;
end.
|
{*******************************************************}
{ }
{ Borland Visibroker for Delphi Naming Service }
{ }
{ Copyright (C) 2000 Inprise Corporation }
{ }
{*******************************************************}
unit CosNaming;
interface
uses
Corba;
type
BindingType = (nobject, ncontext);
NamingContext_NotFoundReason = (missing_node, not_context, not_object);
{Interfaces Defined}
NameComponent = interface;
Binding = interface;
BindingIterator = interface;
NamingContext = interface;
NamingContextFactory = interface;
ExtendedNamingContextFactory = interface;
LNameComponent = interface;
LName = interface;
LNameFactory = interface;
LogRecord = interface;
Log = interface;
Istring = AnsiString;
Name = array of CosNaming.NameComponent;
BindingList = array of CosNaming.Binding;
NameComponent = interface
['{1F97A052-327B-946B-DDC7-8546E892923D}']
function _get_id : CosNaming.Istring;
procedure _set_id(const id : CosNaming.Istring);
function _get_kind : CosNaming.Istring;
procedure _set_kind(const kind : CosNaming.Istring);
property id : CosNaming.Istring read _get_id write _set_id;
property kind : CosNaming.Istring read _get_kind write _set_kind;
end;
Binding = interface
['{D5179672-5716-C953-DE66-A7EB2E831A5C}']
function _get_binding_name : CosNaming.Name;
procedure _set_binding_name(const binding_name : CosNaming.Name);
function _get_binding_type : CosNaming.BindingType;
procedure _set_binding_type(const binding_type : CosNaming.BindingType);
property binding_name : CosNaming.Name read _get_binding_name write _set_binding_name;
property binding_type : CosNaming.BindingType read _get_binding_type write _set_binding_type;
end;
BindingIterator = interface
['{D33A454D-62FB-2BF8-7C70-AB76C61BD0AE}']
function next_one(out b : CosNaming.Binding): Boolean;
function next_n(const how_many : Cardinal; out b : CosNaming.BindingList): Boolean;
procedure _destroy;
end;
NamingContext = interface
['{7DFA1D2B-16FD-AFBF-C509-0FFF155A2060}']
procedure bind(const n : CosNaming.Name; const obj : CORBAObject);
procedure rebind(const n : CosNaming.Name; const obj : CORBAObject);
procedure bind_context(const n : CosNaming.Name; const nc : CosNaming.NamingContext);
procedure rebind_context(const n : CosNaming.Name; const nc : CosNaming.NamingContext);
function resolve(const n : CosNaming.Name): CORBAObject;
procedure unbind(const n : CosNaming.Name);
function new_context : CosNaming.NamingContext;
function bind_new_context(const n : CosNaming.Name): CosNaming.NamingContext;
procedure _destroy;
procedure list (const how_many : Cardinal;
out bl : CosNaming.BindingList;
out bi : CosNaming.BindingIterator);
end;
NamingContextFactory = interface
['{30E560EF-F2EC-9ABC-93BD-4321F386D4B3}']
function create_context : CosNaming.NamingContext;
procedure shutdown;
end;
ExtendedNamingContextFactory = interface (CosNaming.NamingContextFactory)
['{D2B9CC00-9B01-8924-355D-56DE44A0DE9E}']
function root_context : CosNaming.NamingContext;
end;
LNameComponent = interface
['{02653203-62A5-477A-D8B5-A13FBE308CDC}']
function get_id : AnsiString;
procedure set_id (const id : AnsiString);
function get_kind : AnsiString;
procedure set_kind (const kind : AnsiString);
procedure _destroy;
end;
LName = interface
['{DCB614BC-ACE3-BDD2-5771-48D03E51CF58}']
function insert_component(const index : Cardinal;
const nameComponent : CosNaming.LNameComponent): CosNaming.LName;
function get_component(const index : Cardinal): CosNaming.LNameComponent;
function delete_component(const index : Cardinal): CosNaming.LNameComponent;
function num_components : Cardinal;
function equal(const name : CosNaming.LName): Boolean;
function less_than(const name : CosNaming.LName): Boolean;
function to_idl_form : CosNaming.Name;
procedure from_idl_form(const name : CosNaming.Name);
procedure _destroy;
end;
LNameFactory = interface
['{DF081B46-1C07-FD26-CAF3-E4740EC8AD45}']
function create_lname : CosNaming.LName;
function create_lname_component : CosNaming.LNameComponent;
end;
LogRecord = interface
['{5445F096-9F0D-C147-F5F9-55645F3EC4D5}']
function _get_operation_key : Char;
procedure _set_operation_key(const operation_key : Char);
function _get_context_index : Integer;
procedure _set_context_index(const context_index : Integer);
function _get_name : CosNaming.Name;
procedure _set_name(const name : CosNaming.Name);
function _get_target_object : CORBAObject;
procedure _set_target_object(const target_object : CORBAObject);
function _get_target_context : CosNaming.NamingContext;
procedure _set_target_context(const target_context : CosNaming.NamingContext);
function _get_target_context_index : Integer;
procedure _set_target_context_index(const target_context_index : Integer);
property operation_key : Char read _get_operation_key write _set_operation_key;
property context_index : Integer read _get_context_index write _set_context_index;
property name : CosNaming.Name read _get_name write _set_name;
property target_object : CORBAObject read _get_target_object write _set_target_object;
property target_context : CosNaming.NamingContext read _get_target_context write _set_target_context;
property target_context_index : Integer read _get_target_context_index write _set_target_context_index;
end;
Log = interface
['{48C8F8E9-F0E6-63A7-1EA0-A185B4871ADD}']
procedure bind(const ctx : CosNaming.NamingContext;
const n : CosNaming.Name;
const obj : CORBAObject);
procedure bind_context(const ctx : CosNaming.NamingContext;
const n : CosNaming.Name;
const nc : CosNaming.NamingContext);
procedure unbind(const ctx : CosNaming.NamingContext;
const n : CosNaming.Name);
procedure new_context(const ctx : CosNaming.NamingContext);
procedure _destroy(const ctx : CosNaming.NamingContext);
end;
{Classes Defined}
TIstringHelper = class;
TNameComponentHelper = class;
TNameComponent = class;
TNameHelper = class;
TBindingTypeHelper = class;
TBindingHelper = class;
TBinding = class;
TBindingListHelper = class;
TBindingIteratorHelper = class;
TBindingIteratorStub = class;
TNamingContextHelper = class;
TNamingContextStub = class;
TNamingContext_NotFoundReasonHelper = class;
ENamingContext_NotFound = class;
ENamingContext_CannotProceed = class;
ENamingContext_InvalidName = class;
ENamingContext_AlreadyBound = class;
ENamingContext_NotEmpty = class;
TNamingContextFactoryHelper = class;
TNamingContextFactoryStub = class;
TExtendedNamingContextFactoryHelper = class;
TExtendedNamingContextFactoryStub = class;
TLNameComponentHelper = class;
TLNameComponentStub = class;
ELNameComponent_NotSet = class;
TLNameHelper = class;
TLNameStub = class;
ELName_NoComponent = class;
ELName_OverFlow = class;
ELName_InvalidName = class;
TLNameFactoryHelper = class;
TLNameFactoryStub = class;
TLogRecordHelper = class;
TLogRecord = class;
TLogHelper = class;
TLogStub = class;
TIstringHelper = class
class procedure Insert(var _A: CORBA.Any; const _Value : CosNaming.Istring);
class function Extract(const _A: CORBA.Any): CosNaming.Istring;
class function TypeCode : CORBA.TypeCode;
class function RepositoryId: string;
class function Read(const _Input : CORBA.InputStream) : CosNaming.Istring;
class procedure Write(const _Output : CORBA.OutputStream; const _Value : CosNaming.Istring);
end;
TNameComponentHelper = class
class procedure Insert (var _A: CORBA.Any; const _Value : CosNaming.NameComponent);
class function Extract(const _A: CORBA.Any): CosNaming.NameComponent;
class function TypeCode : CORBA.TypeCode;
class function RepositoryId: string;
class function Read(const _Input : CORBA.InputStream) : CosNaming.NameComponent;
class procedure Write(const _Output : CORBA.OutputStream; const _Value : CosNaming.NameComponent);
end;
TNameComponent = class (TInterfacedObject, CosNaming.NameComponent)
private
id : CosNaming.Istring;
kind : CosNaming.Istring;
constructor Create; overload;
public
function _get_id : CosNaming.Istring; virtual;
procedure _set_id(const _value : CosNaming.Istring ); virtual;
function _get_kind : CosNaming.Istring; virtual;
procedure _set_kind(const _value : CosNaming.Istring ); virtual;
constructor Create (const id : CosNaming.Istring; const kind : CosNaming.Istring ); overload;
end;
TNameHelper = class
class procedure Insert(var _A: CORBA.Any; const _Value : CosNaming.Name);
class function Extract(const _A: CORBA.Any): CosNaming.Name;
class function TypeCode : CORBA.TypeCode;
class function RepositoryId: string;
class function Read(const _Input : CORBA.InputStream) : CosNaming.Name;
class procedure Write(const _Output : CORBA.OutputStream; const _Value : CosNaming.Name);
end;
TBindingTypeHelper = class
class procedure Insert(var _A: CORBA.Any; const _Value : CosNaming.BindingType);
class function Extract(const _A: CORBA.Any): CosNaming.BindingType;
class function TypeCode : CORBA.TypeCode;
class function RepositoryId: string;
class function Read(const _Input : CORBA.InputStream) : CosNaming.BindingType;
class procedure Write(const _Output : CORBA.OutputStream; const _Value : CosNaming.BindingType);
end;
TBindingHelper = class
class procedure Insert(var _A: CORBA.Any; const _Value : CosNaming.Binding);
class function Extract(const _A: CORBA.Any): CosNaming.Binding;
class function TypeCode : CORBA.TypeCode;
class function RepositoryId: string;
class function Read(const _Input : CORBA.InputStream) : CosNaming.Binding;
class procedure Write(const _Output : CORBA.OutputStream; const _Value : CosNaming.Binding);
end;
TBinding = class (TInterfacedObject, CosNaming.Binding)
private
binding_name : CosNaming.Name;
binding_type : CosNaming.BindingType;
constructor Create; overload;
public
function _get_binding_name : CosNaming.Name; virtual;
procedure _set_binding_name(const _value : CosNaming.Name ); virtual;
function _get_binding_type : CosNaming.BindingType; virtual;
procedure _set_binding_type(const _value : CosNaming.BindingType ); virtual;
constructor Create(const binding_name : CosNaming.Name; const binding_type : CosNaming.BindingType); overload;
end;
TBindingListHelper = class
class procedure Insert(var _A: CORBA.Any; const _Value : CosNaming.BindingList);
class function Extract(const _A: CORBA.Any): CosNaming.BindingList;
class function TypeCode : CORBA.TypeCode;
class function RepositoryId: string;
class function Read(const _Input : CORBA.InputStream) : CosNaming.BindingList;
class procedure Write(const _Output : CORBA.OutputStream; const _Value : CosNaming.BindingList);
end;
TBindingIteratorHelper = class
class procedure Insert(var _A: CORBA.Any; const _Value : CosNaming.BindingIterator);
class function Extract(var _A: CORBA.Any) : CosNaming.BindingIterator;
class function TypeCode : CORBA.TypeCode;
class function RepositoryId : string;
class function Read(const _Input : CORBA.InputStream) : CosNaming.BindingIterator;
class procedure Write(const _Output : CORBA.OutputStream; const _Value : CosNaming.BindingIterator);
class function Narrow(const _Obj : CORBA.CORBAObject; _IsA : Boolean = False) : CosNaming.BindingIterator;
class function Bind(const _InstanceName : string = ''; _HostName : string = '') : CosNaming.BindingIterator; overload;
class function Bind(_Options : BindOptions; const _InstanceName : string = ''; _HostName: string = '') : CosNaming.BindingIterator; overload;
end;
TBindingIteratorStub = class(CORBA.TCORBAObject, CosNaming.BindingIterator)
public
function next_one(out b : CosNaming.Binding): Boolean; virtual;
function next_n(const how_many : Cardinal; out b : CosNaming.BindingList): Boolean; virtual;
procedure _destroy; virtual;
end;
TNamingContextHelper = class
class procedure Insert(var _A: CORBA.Any; const _Value : CosNaming.NamingContext);
class function Extract(var _A: CORBA.Any) : CosNaming.NamingContext;
class function TypeCode : CORBA.TypeCode;
class function RepositoryId : string;
class function Read(const _Input : CORBA.InputStream) : CosNaming.NamingContext;
class procedure Write(const _Output : CORBA.OutputStream; const _Value : CosNaming.NamingContext);
class function Narrow(const _Obj : CORBA.CORBAObject; _IsA : Boolean = False) : CosNaming.NamingContext;
class function Bind(const _InstanceName : string = ''; _HostName : string = '') : CosNaming.NamingContext; overload;
class function Bind(_Options : BindOptions; const _InstanceName : string = ''; _HostName: string = '') : CosNaming.NamingContext; overload;
end;
TNamingContextStub = class(CORBA.TCORBAObject, CosNaming.NamingContext)
public
procedure bind(const n : CosNaming.Name; const obj : CORBAObject); virtual;
procedure rebind(const n : CosNaming.Name; const obj : CORBAObject); virtual;
procedure bind_context(const n : CosNaming.Name; const nc : CosNaming.NamingContext); virtual;
procedure rebind_context(const n : CosNaming.Name; const nc : CosNaming.NamingContext); virtual;
function resolve(const n : CosNaming.Name): CORBAObject; virtual;
procedure unbind(const n : CosNaming.Name); virtual;
function new_context : CosNaming.NamingContext; virtual;
function bind_new_context(const n : CosNaming.Name): CosNaming.NamingContext; virtual;
procedure _destroy; virtual;
procedure list(const how_many : Cardinal;
out bl : CosNaming.BindingList;
out bi : CosNaming.BindingIterator); virtual;
end;
TNamingContext_NotFoundReasonHelper = class
class procedure Insert(var _A: CORBA.Any; const _Value : CosNaming.NamingContext_NotFoundReason);
class function Extract(const _A: CORBA.Any): CosNaming.NamingContext_NotFoundReason;
class function TypeCode : CORBA.TypeCode;
class function RepositoryId: string;
class function Read(const _Input : CORBA.InputStream) : CosNaming.NamingContext_NotFoundReason;
class procedure Write(const _Output : CORBA.OutputStream; const _Value : CosNaming.NamingContext_NotFoundReason);
end;
ENamingContext_NotFound = class(UserException)
private
Fwhy : CosNaming.NamingContext_NotFoundReason;
Frest_of_name : CosNaming.Name;
protected
function _get_why : CosNaming.NamingContext_NotFoundReason; virtual;
function _get_rest_of_name : CosNaming.Name; virtual;
public
property why : CosNaming.NamingContext_NotFoundReason read _get_why;
property rest_of_name : CosNaming.Name read _get_rest_of_name;
constructor Create; overload;
constructor Create(const why : CosNaming.NamingContext_NotFoundReason;
const rest_of_name : CosNaming.Name); overload;
procedure Copy(const _Input : InputStream); override;
procedure WriteExceptionInfo(var _Output : OutputStream); override;
end;
ENamingContext_CannotProceed = class(UserException)
private
Fcxt : CosNaming.NamingContext;
Frest_of_name : CosNaming.Name;
protected
function _get_cxt : CosNaming.NamingContext; virtual;
function _get_rest_of_name : CosNaming.Name; virtual;
public
property cxt : CosNaming.NamingContext read _get_cxt;
property rest_of_name : CosNaming.Name read _get_rest_of_name;
constructor Create; overload;
constructor Create(const cxt : CosNaming.NamingContext;
const rest_of_name : CosNaming.Name); overload;
procedure Copy(const _Input : InputStream); override;
procedure WriteExceptionInfo(var _Output : OutputStream); override;
end;
ENamingContext_InvalidName = class(UserException)
public
constructor Create; overload;
procedure Copy(const _Input : InputStream); override;
procedure WriteExceptionInfo(var _Output : OutputStream); override;
end;
ENamingContext_AlreadyBound = class(UserException)
public
constructor Create; overload;
procedure Copy(const _Input : InputStream); override;
procedure WriteExceptionInfo(var _Output : OutputStream); override;
end;
ENamingContext_NotEmpty = class(UserException)
public
constructor Create; overload;
procedure Copy(const _Input : InputStream); override;
procedure WriteExceptionInfo(var _Output : OutputStream); override;
end;
TNamingContextFactoryHelper = class
class procedure Insert(var _A: CORBA.Any; const _Value : CosNaming.NamingContextFactory);
class function Extract(var _A: CORBA.Any) : CosNaming.NamingContextFactory;
class function TypeCode : CORBA.TypeCode;
class function RepositoryId : string;
class function Read(const _Input : CORBA.InputStream) : CosNaming.NamingContextFactory;
class procedure Write(const _Output : CORBA.OutputStream; const _Value : CosNaming.NamingContextFactory);
class function Narrow(const _Obj : CORBA.CORBAObject; _IsA : Boolean = False) : CosNaming.NamingContextFactory;
class function Bind(const _InstanceName : string = ''; _HostName : string = '') : CosNaming.NamingContextFactory; overload;
class function Bind(_Options : BindOptions; const _InstanceName : string = ''; _HostName: string = '') : CosNaming.NamingContextFactory; overload;
end;
TNamingContextFactoryStub = class(CORBA.TCORBAObject, CosNaming.NamingContextFactory)
public
function create_context : CosNaming.NamingContext; virtual;
procedure shutdown; virtual;
end;
TExtendedNamingContextFactoryHelper = class
class procedure Insert(var _A: CORBA.Any; const _Value : CosNaming.ExtendedNamingContextFactory);
class function Extract(var _A: CORBA.Any) : CosNaming.ExtendedNamingContextFactory;
class function TypeCode : CORBA.TypeCode;
class function RepositoryId : string;
class function Read(const _Input : CORBA.InputStream) : CosNaming.ExtendedNamingContextFactory;
class procedure Write(const _Output : CORBA.OutputStream; const _Value : CosNaming.ExtendedNamingContextFactory);
class function Narrow(const _Obj : CORBA.CORBAObject; _IsA : Boolean = False) : CosNaming.ExtendedNamingContextFactory;
class function Bind(const _InstanceName : string = ''; _HostName : string = '') : CosNaming.ExtendedNamingContextFactory; overload;
class function Bind(_Options : BindOptions; const _InstanceName : string = ''; _HostName: string = '') : CosNaming.ExtendedNamingContextFactory; overload;
end;
TExtendedNamingContextFactoryStub = class(CORBA.TCORBAObject, CosNaming.ExtendedNamingContextFactory)
public
function root_context : CosNaming.NamingContext; virtual;
function create_context : CosNaming.NamingContext; virtual;
procedure shutdown ; virtual;
end;
TLNameComponentHelper = class
class procedure Insert(var _A: CORBA.Any; const _Value : CosNaming.LNameComponent);
class function Extract(var _A: CORBA.Any) : CosNaming.LNameComponent;
class function TypeCode : CORBA.TypeCode;
class function RepositoryId : string;
class function Read (const _Input : CORBA.InputStream) : CosNaming.LNameComponent;
class procedure Write(const _Output : CORBA.OutputStream; const _Value : CosNaming.LNameComponent);
class function Narrow(const _Obj : CORBA.CORBAObject; _IsA : Boolean = False) : CosNaming.LNameComponent;
class function Bind(const _InstanceName : string = ''; _HostName : string = '') : CosNaming.LNameComponent; overload;
class function Bind(_Options : BindOptions; const _InstanceName : string = ''; _HostName: string = '') : CosNaming.LNameComponent; overload;
end;
TLNameComponentStub = class(CORBA.TCORBAObject, CosNaming.LNameComponent)
public
function get_id : AnsiString; virtual;
procedure set_id(const id : AnsiString); virtual;
function get_kind : AnsiString; virtual;
procedure set_kind(const kind : AnsiString); virtual;
procedure _destroy; virtual;
end;
ELNameComponent_NotSet = class(UserException)
public
constructor Create; overload;
procedure Copy(const _Input : InputStream); override;
procedure WriteExceptionInfo(var _Output : OutputStream); override;
end;
TLNameHelper = class
class procedure Insert(var _A: CORBA.Any; const _Value : CosNaming.LName);
class function Extract(var _A: CORBA.Any) : CosNaming.LName;
class function TypeCode : CORBA.TypeCode;
class function RepositoryId : string;
class function Read(const _Input : CORBA.InputStream) : CosNaming.LName;
class procedure Write(const _Output : CORBA.OutputStream; const _Value : CosNaming.LName);
class function Narrow(const _Obj : CORBA.CORBAObject; _IsA : Boolean = False) : CosNaming.LName;
class function Bind(const _InstanceName : string = ''; _HostName : string = '') : CosNaming.LName; overload;
class function Bind(_Options : BindOptions; const _InstanceName : string = ''; _HostName: string = '') : CosNaming.LName; overload;
end;
TLNameStub = class(CORBA.TCORBAObject, CosNaming.LName)
public
function insert_component( const index : Cardinal;
const nameComponent : CosNaming.LNameComponent): CosNaming.LName; virtual;
function get_component(const index : Cardinal): CosNaming.LNameComponent; virtual;
function delete_component( const index : Cardinal): CosNaming.LNameComponent; virtual;
function num_components : Cardinal; virtual;
function equal(const name : CosNaming.LName): Boolean; virtual;
function less_than(const name : CosNaming.LName): Boolean; virtual;
function to_idl_form : CosNaming.Name; virtual;
procedure from_idl_form(const name : CosNaming.Name); virtual;
procedure _destroy; virtual;
end;
ELName_NoComponent = class(UserException)
public
constructor Create; overload;
procedure Copy(const _Input : InputStream); override;
procedure WriteExceptionInfo(var _Output : OutputStream); override;
end;
ELName_OverFlow = class(UserException)
public
constructor Create; overload;
procedure Copy(const _Input : InputStream); override;
procedure WriteExceptionInfo(var _Output : OutputStream); override;
end;
ELName_InvalidName = class(UserException)
public
constructor Create; overload;
procedure Copy(const _Input : InputStream); override;
procedure WriteExceptionInfo(var _Output : OutputStream); override;
end;
TLNameFactoryHelper = class
class procedure Insert(var _A: CORBA.Any; const _Value : CosNaming.LNameFactory);
class function Extract(var _A: CORBA.Any) : CosNaming.LNameFactory;
class function TypeCode : CORBA.TypeCode;
class function RepositoryId : string;
class function Read(const _Input : CORBA.InputStream) : CosNaming.LNameFactory;
class procedure Write(const _Output : CORBA.OutputStream; const _Value : CosNaming.LNameFactory);
class function Narrow(const _Obj : CORBA.CORBAObject; _IsA : Boolean = False) : CosNaming.LNameFactory;
class function Bind(const _InstanceName : string = ''; _HostName : string = '') : CosNaming.LNameFactory; overload;
class function Bind(_Options : BindOptions; const _InstanceName : string = ''; _HostName: string = '') : CosNaming.LNameFactory; overload;
end;
TLNameFactoryStub = class(CORBA.TCORBAObject, CosNaming.LNameFactory)
public
function create_lname : CosNaming.LName; virtual;
function create_lname_component : CosNaming.LNameComponent; virtual;
end;
TLogRecordHelper = class
class procedure Insert(var _A: CORBA.Any; const _Value : CosNaming.LogRecord);
class function Extract(const _A: CORBA.Any): CosNaming.LogRecord;
class function TypeCode : CORBA.TypeCode;
class function RepositoryId: string;
class function Read(const _Input : CORBA.InputStream) : CosNaming.LogRecord;
class procedure Write(const _Output : CORBA.OutputStream; const _Value : CosNaming.LogRecord);
end;
TLogRecord = class (TInterfacedObject, CosNaming.LogRecord)
private
operation_key : Char;
context_index : Integer;
name : CosNaming.Name;
target_object : CORBAObject;
target_context : CosNaming.NamingContext;
target_context_index : Integer;
constructor Create; overload;
public
function _get_operation_key : Char; virtual;
procedure _set_operation_key(const _value : Char); virtual;
function _get_context_index : Integer; virtual;
procedure _set_context_index(const _value : Integer); virtual;
function _get_name : CosNaming.Name; virtual;
procedure _set_name(const _value : CosNaming.Name); virtual;
function _get_target_object : CORBAObject; virtual;
procedure _set_target_object(const _value : CORBAObject); virtual;
function _get_target_context : CosNaming.NamingContext; virtual;
procedure _set_target_context(const _value : CosNaming.NamingContext); virtual;
function _get_target_context_index : Integer; virtual;
procedure _set_target_context_index(const _value : Integer); virtual;
constructor Create (const operation_key : Char;
const context_index : Integer;
const name : CosNaming.Name;
const target_object : CORBAObject;
const target_context : CosNaming.NamingContext;
const target_context_index : Integer); overload;
end;
TLogHelper = class
class procedure Insert (var _A: CORBA.Any; const _Value : CosNaming.Log);
class function Extract(var _A: CORBA.Any) : CosNaming.Log;
class function TypeCode : CORBA.TypeCode;
class function RepositoryId : string;
class function Read(const _Input : CORBA.InputStream) : CosNaming.Log;
class procedure Write(const _Output : CORBA.OutputStream; const _Value : CosNaming.Log);
class function Narrow(const _Obj : CORBA.CORBAObject; _IsA : Boolean = False) : CosNaming.Log;
class function Bind(const _InstanceName : string = ''; _HostName : string = '') : CosNaming.Log; overload;
class function Bind(_Options : BindOptions; const _InstanceName : string = ''; _HostName: string = '') : CosNaming.Log; overload;
end;
TLogStub = class(CORBA.TCORBAObject, CosNaming.Log)
public
procedure bind(const ctx : CosNaming.NamingContext;
const n : CosNaming.Name;
const obj : CORBAObject); virtual;
procedure bind_context(const ctx : CosNaming.NamingContext;
const n : CosNaming.Name;
const nc : CosNaming.NamingContext); virtual;
procedure unbind(const ctx : CosNaming.NamingContext; const n : CosNaming.Name); virtual;
procedure new_context ( const ctx : CosNaming.NamingContext); virtual;
procedure _destroy(const ctx : CosNaming.NamingContext); virtual;
end;
implementation
var
NamingContext_NotFoundDesc : PExceptionDescription;
NamingContext_CannotProceedDesc : PExceptionDescription;
NamingContext_InvalidNameDesc : PExceptionDescription;
NamingContext_AlreadyBoundDesc : PExceptionDescription;
NamingContext_NotEmptyDesc : PExceptionDescription;
LNameComponent_NotSetDesc : PExceptionDescription;
LName_NoComponentDesc : PExceptionDescription;
LName_OverFlowDesc : PExceptionDescription;
LName_InvalidNameDesc : PExceptionDescription;
class procedure TIstringHelper.Insert(var _A : CORBA.Any; const _Value : CosNaming.Istring);
begin
_A := _Value;
end;
class function TIstringHelper.Extract(const _A : CORBA.Any) : CosNaming.Istring;
var
_Input : InputStream;
_Temp : AnsiString;
begin
Orb.GetAny(_A, _Input);
_Input.ReadString(_Temp);
Result := CosNaming.Istring(_Temp);
end;
class function TIstringHelper.TypeCode : CORBA.TypeCode;
begin
Result := ORB.CreateAliasTC(RepositoryId, 'Istring', ORB.CreateTC(Integer(0)));
end;
class function TIstringHelper.RepositoryId : string;
begin
Result := 'IDL:omg.org/CosNaming/Istring:1.0';
end;
class function TIstringHelper.Read(const _Input: CORBA.InputStream) : CosNaming.Istring;
begin
_Input.ReadString(Result);
end;
class procedure TIstringHelper.Write(const _Output : CORBA.OutputStream; const _Value :CosNaming.Istring);
begin
_Output.WriteString(_Value);
end;
class procedure TNameComponentHelper.Insert(var _A : CORBA.Any; const _Value : CosNaming.NameComponent);
var
_Output : CORBA.OutputStream;
begin
_Output := ORB.CreateOutputStream;
TNameComponentHelper.Write(_Output, _Value);
ORB.PutAny(_A, TNameComponentHelper.TypeCode, _Output);
end;
class function TNameComponentHelper.Extract(const _A : CORBA.Any) : CosNaming.NameComponent;
var
_Input : CORBA.InputStream;
begin
Orb.GetAny(_A, _Input);
Result := TNameComponentHelper.Read(_Input);
end;
class function TNameComponentHelper.TypeCode : CORBA.TypeCode;
var
_Seq: StructMemberSeq;
begin
SetLength(_Seq, 2);
_Seq[0].Name := 'id';
_Seq[0].TC := CosNaming.TIstringHelper.TypeCode;
_Seq[1].Name := 'kind';
_Seq[1].TC := CosNaming.TIstringHelper.TypeCode;
Result := ORB.MakeStructureTypecode(RepositoryID, 'NameComponent', _Seq);
end;
class function TNameComponentHelper.RepositoryId : string;
begin
Result := 'IDL:omg.org/CosNaming/NameComponent:1.0';
end;
class function TNameComponentHelper.Read(const _Input : CORBA.InputStream) : CosNaming.NameComponent;
var
_Value : CosNaming.TNameComponent;
begin
_Value := CosNaming.TNameComponent.Create;
_Value.id := CosNaming.TIstringHelper.Read(_Input);
_Value.kind := CosNaming.TIstringHelper.Read(_Input);
Result := _Value;
end;
class procedure TNameComponentHelper.Write(const _Output : CORBA.OutputStream; const _Value : CosNaming.NameComponent);
begin
CosNaming.TIstringHelper.Write(_Output, _Value.id);
CosNaming.TIstringHelper.Write(_Output, _Value.kind);
end;
constructor TNameComponent.Create;
begin
inherited Create;
end;
constructor TNameComponent.Create(const id: CosNaming.Istring;
const kind: CosNaming.Istring);
begin
Self.id := id;
Self.kind := kind;
end;
function TNameComponent._get_id: CosNaming.Istring;
begin
Result := id;
end;
procedure TNameComponent._set_id(const _Value : CosNaming.Istring);
begin
id := _Value;
end;
function TNameComponent._get_kind: CosNaming.Istring;
begin
Result := kind;
end;
procedure TNameComponent._set_kind(const _Value : CosNaming.Istring);
begin
kind := _Value;
end;
class procedure TNameHelper.Insert(var _A : CORBA.Any; const _Value : CosNaming.Name);
var
_Output : CORBA.OutputStream;
begin
_Output := ORB.CreateOutputStream;
TNameHelper.Write(_Output, _Value);
ORB.PutAny(_A, TNameHelper.TypeCode, _Output);
end;
class function TNameHelper.Extract(const _A : CORBA.Any): CosNaming.Name;
var
_Input : InputStream;
begin
Orb.GetAny(_A, _Input);
Result := TNameHelper.Read(_Input);
end;
class function TNameHelper.TypeCode: CORBA.TypeCode;
begin
Result := ORB.CreateSequenceTC(0, CosNaming.TNameComponentHelper.TypeCode());
end;
class function TNameHelper.RepositoryId: string;
begin
Result := 'IDL:omg.org/CosNaming/Name:1.0';
end;
class function TNameHelper.Read(const _Input : CORBA.InputStream) : CosNaming.Name;
var
L0 : Cardinal;
I0 : Cardinal;
begin
_Input.ReadULong(L0);
SetLength(Result, L0);
if (L0 > 0) then
begin
for I0 := 0 to High(Result) do
begin
Result[I0] := CosNaming.TNameComponentHelper.Read(_Input);
end;
end;
end;
class procedure TNameHelper.Write(const _Output: CORBA.OutputStream; const _Value: CosNaming.Name);
var
L0 : Cardinal;
I0 : Cardinal;
begin
L0 := Length(_Value);
_Output.WriteULong(L0);
if (L0 > 0) then
begin
for I0 := 0 to High(_Value) do
begin
CosNaming.TNameComponentHelper.Write(_Output, _Value[I0]);
end;
end;
end;
class procedure TBindingTypeHelper.Insert(var _A : CORBA.Any; const _Value : CosNaming.BindingType);
begin
_A := _Value;
end;
class function TBindingTypeHelper.Extract(const _A : CORBA.Any) : CosNaming.BindingType;
begin
Result := CosNaming.BindingType(_A);
end;
class function TBindingTypeHelper.TypeCode : CORBA.TypeCode;
begin
Result := ORB.CreateEnumTC(RepositoryId, 'BindingType', ['nobject', 'ncontext']);
end;
class function TBindingTypeHelper.RepositoryId: string;
begin
Result := 'IDL:omg.org/CosNaming/BindingType:1.0';
end;
class function TBindingTypeHelper.Read(const _Input : CORBA.InputStream) : CosNaming.BindingType;
var
_Temp: Cardinal;
begin
_Input.ReadULong(_Temp);
Result := CosNaming.BindingType(_Temp);
end;
class procedure TBindingTypeHelper.Write(const _Output : CORBA.OutputStream; const _Value : CosNaming.BindingType);
begin
_Output.WriteULong(Cardinal(_Value));
end;
class procedure TBindingHelper.Insert(var _A : CORBA.Any; const _Value : CosNaming.Binding);
var
_Output : CORBA.OutputStream;
begin
_Output := ORB.CreateOutputStream;
TBindingHelper.Write(_Output, _Value);
ORB.PutAny(_A, TBindingHelper.TypeCode, _Output);
end;
class function TBindingHelper.Extract(const _A : CORBA.Any) : CosNaming.Binding;
var
_Input : CORBA.InputStream;
begin
Orb.GetAny(_A, _Input);
Result := TBindingHelper.Read(_Input);
end;
class function TBindingHelper.TypeCode : CORBA.TypeCode;
var
_Seq: StructMemberSeq;
begin
SetLength(_Seq, 2);
_Seq[0].Name := 'binding_name';
_Seq[0].TC := CosNaming.TNameHelper.TypeCode;
_Seq[1].Name := 'binding_type';
_Seq[1].TC := CosNaming.TBindingTypeHelper.TypeCode;
Result := ORB.MakeStructureTypecode(RepositoryID, 'Binding', _Seq);
end;
class function TBindingHelper.RepositoryId : string;
begin
Result := 'IDL:omg.org/CosNaming/Binding:1.0';
end;
class function TBindingHelper.Read(const _Input : CORBA.InputStream) : CosNaming.Binding;
var
_Value : CosNaming.TBinding;
begin
_Value := CosNaming.TBinding.Create;
_Value.binding_name := CosNaming.TNameHelper.Read(_Input);
_Value.binding_type := CosNaming.TBindingTypeHelper.Read(_Input);
Result := _Value;
end;
class procedure TBindingHelper.Write(const _Output : CORBA.OutputStream; const _Value : CosNaming.Binding);
begin
CosNaming.TNameHelper.Write(_Output, _Value.binding_name);
CosNaming.TBindingTypeHelper.Write(_Output, _Value.binding_type);
end;
constructor TBinding.Create;
begin
inherited Create;
end;
constructor TBinding.Create(const binding_name: CosNaming.Name;
const binding_type: CosNaming.BindingType);
begin
Self.binding_name := binding_name;
Self.binding_type := binding_type;
end;
function TBinding._get_binding_name: CosNaming.Name;
begin
Result := binding_name;
end;
procedure TBinding._set_binding_name(const _Value : CosNaming.Name);
begin
binding_name := _Value;
end;
function TBinding._get_binding_type: CosNaming.BindingType;
begin
Result := binding_type;
end;
procedure TBinding._set_binding_type(const _Value : CosNaming.BindingType);
begin
binding_type := _Value;
end;
class procedure TBindingListHelper.Insert(var _A : CORBA.Any; const _Value : CosNaming.BindingList);
var
_Output : CORBA.OutputStream;
begin
_Output := ORB.CreateOutputStream;
TBindingListHelper.Write(_Output, _Value);
ORB.PutAny(_A, TBindingListHelper.TypeCode, _Output);
end;
class function TBindingListHelper.Extract(const _A : CORBA.Any): CosNaming.BindingList;
var
_Input : InputStream;
begin
Orb.GetAny(_A, _Input);
Result := TBindingListHelper.Read(_Input);
end;
class function TBindingListHelper.TypeCode: CORBA.TypeCode;
begin
Result := ORB.CreateSequenceTC(0, CosNaming.TBindingHelper.TypeCode());
end;
class function TBindingListHelper.RepositoryId: string;
begin
Result := 'IDL:omg.org/CosNaming/BindingList:1.0';
end;
class function TBindingListHelper.Read(const _Input : CORBA.InputStream) : CosNaming.BindingList;
var
L0 : Cardinal;
I0 : Cardinal;
begin
_Input.ReadULong(L0);
SetLength(Result, L0);
if (L0 > 0) then
begin
for I0 := 0 to High(Result) do
begin
Result[I0] := CosNaming.TBindingHelper.Read(_Input);
end;
end;
end;
class procedure TBindingListHelper.Write(const _Output: CORBA.OutputStream; const _Value: CosNaming.BindingList);
var
L0 : Cardinal;
I0 : Cardinal;
begin
L0 := Length(_Value);
_Output.WriteULong(L0);
if (L0 > 0) then
begin
for I0 := 0 to High(_Value) do
begin
CosNaming.TBindingHelper.Write(_Output, _Value[I0]);
end;
end;
end;
class procedure TBindingIteratorHelper.Insert(var _A : CORBA.Any; const _Value : CosNaming.BindingIterator);
begin
_A := Orb.MakeObjectRef( TBindingIteratorHelper.TypeCode, _Value as CORBA.CORBAObject);
end;
class function TBindingIteratorHelper.Extract(var _A : CORBA.Any): CosNaming.BindingIterator;
var
_obj : Corba.CorbaObject;
begin
_obj := Orb.GetObjectRef(_A);
Result := TBindingIteratorHelper.Narrow(_obj, True);
end;
class function TBindingIteratorHelper.TypeCode : CORBA.TypeCode;
begin
Result := ORB.CreateInterfaceTC(RepositoryId, 'BindingIterator');
end;
class function TBindingIteratorHelper.RepositoryId : string;
begin
Result := 'IDL:omg.org/CosNaming/BindingIterator:1.0';
end;
class function TBindingIteratorHelper.Read(const _Input : CORBA.InputStream) : CosNaming.BindingIterator;
var
_Obj : CORBA.CORBAObject;
begin
_Input.ReadObject(_Obj);
Result := Narrow(_Obj, True)
end;
class procedure TBindingIteratorHelper.Write(const _Output : CORBA.OutputStream; const _Value : CosNaming.BindingIterator);
begin
_Output.WriteObject(_Value as CORBA.CORBAObject);
end;
class function TBindingIteratorHelper.Narrow(const _Obj : CORBA.CORBAObject; _IsA : Boolean) : CosNaming.BindingIterator;
begin
Result := nil;
if (_Obj = nil) or (_Obj.QueryInterface(CosNaming.BindingIterator, Result) = 0)
then Exit;
if _IsA and _Obj._IsA(RepositoryId) then
Result := TBindingIteratorStub.Create(_Obj);
end;
class function TBindingIteratorHelper.Bind(const _InstanceName : string = ''; _HostName: string = '') : CosNaming.BindingIterator;
begin
Result := Narrow(ORB.bind(RepositoryId, _InstanceName, _HostName), True);
end;
class function TBindingIteratorHelper.Bind(_Options : BindOptions; const _InstanceName : string = ''; _HostName : string = '') : CosNaming.BindingIterator;
begin
Result := Narrow(ORB.bind(RepositoryId, _Options, _InstanceName, _HostName), True);
end;
function TBindingIteratorStub.next_one(out b : CosNaming.Binding): Boolean;
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('next_one',True, _Output);
inherited _Invoke(_Output, _Input);
_Input.ReadBoolean(Result);
b := CosNaming.TBindingHelper.Read(_Input);
end;
function TBindingIteratorStub.next_n(const how_many : Cardinal;
out b : CosNaming.BindingList): Boolean;
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('next_n',True, _Output);
_Output.WriteULong(how_many);
inherited _Invoke(_Output, _Input);
_Input.ReadBoolean(Result);
b := CosNaming.TBindingListHelper.Read(_Input);
end;
procedure TBindingIteratorStub._destroy;
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('destroy',True, _Output);
inherited _Invoke(_Output, _Input);
end;
class procedure TNamingContextHelper.Insert(var _A : CORBA.Any; const _Value : CosNaming.NamingContext);
begin
_A := Orb.MakeObjectRef( TNamingContextHelper.TypeCode, _Value as CORBA.CORBAObject);
end;
class function TNamingContextHelper.Extract(var _A : CORBA.Any): CosNaming.NamingContext;
var
_obj : Corba.CorbaObject;
begin
_obj := Orb.GetObjectRef(_A);
Result := TNamingContextHelper.Narrow(_obj, True);
end;
class function TNamingContextHelper.TypeCode : CORBA.TypeCode;
begin
Result := ORB.CreateInterfaceTC(RepositoryId, 'NamingContext');
end;
class function TNamingContextHelper.RepositoryId : string;
begin
Result := 'IDL:omg.org/CosNaming/NamingContext:1.0';
end;
class function TNamingContextHelper.Read(const _Input : CORBA.InputStream) : CosNaming.NamingContext;
var
_Obj : CORBA.CORBAObject;
begin
_Input.ReadObject(_Obj);
Result := Narrow(_Obj, True)
end;
class procedure TNamingContextHelper.Write(const _Output : CORBA.OutputStream; const _Value : CosNaming.NamingContext);
begin
_Output.WriteObject(_Value as CORBA.CORBAObject);
end;
class function TNamingContextHelper.Narrow(const _Obj : CORBA.CORBAObject; _IsA : Boolean) : CosNaming.NamingContext;
begin
Result := nil;
if (_Obj = nil) or (_Obj.QueryInterface(CosNaming.NamingContext, Result) = 0)
then Exit;
if _IsA and _Obj._IsA(RepositoryId) then
Result := TNamingContextStub.Create(_Obj);
end;
class function TNamingContextHelper.Bind(const _InstanceName : string = ''; _HostName: string = '') : CosNaming.NamingContext;
begin
Result := Narrow(ORB.bind(RepositoryId, _InstanceName, _HostName), True);
end;
class function TNamingContextHelper.Bind(_Options : BindOptions; const _InstanceName : string = ''; _HostName : string = '') : CosNaming.NamingContext;
begin
Result := Narrow(ORB.bind(RepositoryId, _Options, _InstanceName, _HostName), True);
end;
procedure TNamingContextStub.bind(const n : CosNaming.Name; const obj : CORBAObject);
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('bind',True, _Output);
CosNaming.TNameHelper.Write(_Output, n);
_Output.WriteObject(obj);
inherited _Invoke(_Output, _Input);
end;
procedure TNamingContextStub.rebind(const n : CosNaming.Name; const obj : CORBAObject);
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('rebind',True, _Output);
CosNaming.TNameHelper.Write(_Output, n);
_Output.WriteObject(obj);
inherited _Invoke(_Output, _Input);
end;
procedure TNamingContextStub.bind_context(const n : CosNaming.Name; const nc : CosNaming.NamingContext);
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('bind_context',True, _Output);
CosNaming.TNameHelper.Write(_Output, n);
CosNaming.TNamingContextHelper.Write(_Output, nc);
inherited _Invoke(_Output, _Input);
end;
procedure TNamingContextStub.rebind_context(const n : CosNaming.Name; const nc : CosNaming.NamingContext);
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('rebind_context',True, _Output);
CosNaming.TNameHelper.Write(_Output, n);
CosNaming.TNamingContextHelper.Write(_Output, nc);
inherited _Invoke(_Output, _Input);
end;
function TNamingContextStub.resolve(const n : CosNaming.Name): CORBAObject;
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('resolve',True, _Output);
CosNaming.TNameHelper.Write(_Output, n);
inherited _Invoke(_Output, _Input);
_Input.ReadObject(Result);
end;
procedure TNamingContextStub.unbind(const n : CosNaming.Name);
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('unbind',True, _Output);
CosNaming.TNameHelper.Write(_Output, n);
inherited _Invoke(_Output, _Input);
end;
function TNamingContextStub.new_context : CosNaming.NamingContext;
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('new_context',True, _Output);
inherited _Invoke(_Output, _Input);
Result := CosNaming.TNamingContextHelper.Read(_Input);
end;
function TNamingContextStub.bind_new_context(const n : CosNaming.Name): CosNaming.NamingContext;
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('bind_new_context',True, _Output);
CosNaming.TNameHelper.Write(_Output, n);
inherited _Invoke(_Output, _Input);
Result := CosNaming.TNamingContextHelper.Read(_Input);
end;
procedure TNamingContextStub._destroy;
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('destroy',True, _Output);
inherited _Invoke(_Output, _Input);
end;
procedure TNamingContextStub.list(const how_many : Cardinal;
out bl : CosNaming.BindingList;
out bi : CosNaming.BindingIterator);
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('list',True, _Output);
_Output.WriteULong(how_many);
inherited _Invoke(_Output, _Input);
bl := CosNaming.TBindingListHelper.Read(_Input);
bi := CosNaming.TBindingIteratorHelper.Read(_Input);
end;
class procedure TNamingContext_NotFoundReasonHelper.Insert(var _A : CORBA.Any; const _Value : CosNaming.NamingContext_NotFoundReason);
begin
_A := _Value;
end;
class function TNamingContext_NotFoundReasonHelper.Extract(const _A : CORBA.Any) : CosNaming.NamingContext_NotFoundReason;
begin
Result := CosNaming.NamingContext_NotFoundReason(_A);
end;
class function TNamingContext_NotFoundReasonHelper.TypeCode : CORBA.TypeCode;
begin
Result := ORB.CreateEnumTC(RepositoryId, 'NamingContext_NotFoundReason', ['missing_node', 'not_context', 'not_object']);
end;
class function TNamingContext_NotFoundReasonHelper.RepositoryId: string;
begin
Result := 'IDL:omg.org/CosNaming/NamingContext/NotFoundReason:1.0';
end;
class function TNamingContext_NotFoundReasonHelper.Read(const _Input : CORBA.InputStream) : CosNaming.NamingContext_NotFoundReason;
var
_Temp: Cardinal;
begin
_Input.ReadULong(_Temp);
Result := CosNaming.NamingContext_NotFoundReason(_Temp);
end;
class procedure TNamingContext_NotFoundReasonHelper.Write(const _Output : CORBA.OutputStream; const _Value : CosNaming.NamingContext_NotFoundReason);
begin
_Output.WriteULong(Cardinal(_Value));
end;
{Not Found Exception}
function ENamingContext_NotFound._get_why : CosNaming.NamingContext_NotFoundReason;
begin
Result := Fwhy;
end;
function ENamingContext_NotFound._get_rest_of_name : CosNaming.Name;
begin
Result := Frest_of_name;
end;
constructor ENamingContext_NotFound.Create;
begin
inherited Create;
end;
constructor ENamingContext_NotFound.Create(const why : CosNaming.NamingContext_NotFoundReason;
const rest_of_name : CosNaming.Name);
begin
inherited Create;
Fwhy := why;
Frest_of_name := rest_of_name;
end;
procedure ENamingContext_NotFound.Copy(const _Input: InputStream);
begin
Fwhy := CosNaming.TNamingContext_NotFoundReasonHelper.Read(_Input);
Frest_of_name := CosNaming.TNameHelper.Read(_Input);
end;
procedure ENamingContext_NotFound.WriteExceptionInfo(var _Output : OutputStream);
begin
_Output.WriteString('IDL:omg.org/CosNaming/NamingContext/NotFound:1.0');
CosNaming.TNamingContext_NotFoundReasonHelper.Write(_Output, Fwhy);
CosNaming.TNameHelper.Write(_Output, Frest_of_name);
end;
function NamingContext_NotFound_Factory: PExceptionProxy; cdecl;
begin
with CosNaming.ENamingContext_NotFound.Create() do Result := Proxy;
end;
{Cannot Proceed Exception}
function ENamingContext_CannotProceed._get_cxt : CosNaming.NamingContext;
begin
Result := Fcxt;
end;
function ENamingContext_CannotProceed._get_rest_of_name : CosNaming.Name;
begin
Result := Frest_of_name;
end;
constructor ENamingContext_CannotProceed.Create;
begin
inherited Create;
end;
constructor ENamingContext_CannotProceed.Create(const cxt : CosNaming.NamingContext;
const rest_of_name : CosNaming.Name);
begin
inherited Create;
Fcxt := cxt;
Frest_of_name := rest_of_name;
end;
procedure ENamingContext_CannotProceed.Copy(const _Input: InputStream);
begin
Fcxt := CosNaming.TNamingContextHelper.Read(_Input);
Frest_of_name := CosNaming.TNameHelper.Read(_Input);
end;
procedure ENamingContext_CannotProceed.WriteExceptionInfo(var _Output : OutputStream);
begin
_Output.WriteString('IDL:omg.org/CosNaming/NamingContext/CannotProceed:1.0');
CosNaming.TNamingContextHelper.Write(_Output, Fcxt);
CosNaming.TNameHelper.Write(_Output, Frest_of_name);
end;
function NamingContext_CannotProceed_Factory: PExceptionProxy; cdecl;
begin
with CosNaming.ENamingContext_CannotProceed.Create() do Result := Proxy;
end;
{Invalid Name Exception}
constructor ENamingContext_InvalidName.Create;
begin
inherited Create;
end;
procedure ENamingContext_InvalidName.Copy(const _Input: InputStream);
begin
end;
procedure ENamingContext_InvalidName.WriteExceptionInfo(var _Output : OutputStream);
begin
_Output.WriteString('IDL:omg.org/CosNaming/NamingContext/InvalidName:1.0');
end;
function NamingContext_InvalidName_Factory: PExceptionProxy; cdecl;
begin
with CosNaming.ENamingContext_InvalidName.Create() do Result := Proxy;
end;
{Already Bound Exception}
constructor ENamingContext_AlreadyBound.Create;
begin
inherited Create;
end;
procedure ENamingContext_AlreadyBound.Copy(const _Input: InputStream);
begin
end;
procedure ENamingContext_AlreadyBound.WriteExceptionInfo(var _Output : OutputStream);
begin
_Output.WriteString('IDL:omg.org/CosNaming/NamingContext/AlreadyBound:1.0');
end;
function NamingContext_AlreadyBound_Factory: PExceptionProxy; cdecl;
begin
with CosNaming.ENamingContext_AlreadyBound.Create() do Result := Proxy;
end;
{Not Empty Exception}
constructor ENamingContext_NotEmpty.Create;
begin
inherited Create;
end;
procedure ENamingContext_NotEmpty.Copy(const _Input: InputStream);
begin
end;
procedure ENamingContext_NotEmpty.WriteExceptionInfo(var _Output : OutputStream);
begin
_Output.WriteString('IDL:omg.org/CosNaming/NamingContext/NotEmpty:1.0');
end;
function NamingContext_NotEmpty_Factory: PExceptionProxy; cdecl;
begin
with CosNaming.ENamingContext_NotEmpty.Create() do Result := Proxy;
end;
{Naming Context Factory Helper}
class procedure TNamingContextFactoryHelper.Insert(var _A : CORBA.Any; const _Value : CosNaming.NamingContextFactory);
begin
_A := Orb.MakeObjectRef( TNamingContextFactoryHelper.TypeCode, _Value as CORBA.CORBAObject);
end;
class function TNamingContextFactoryHelper.Extract(var _A : CORBA.Any): CosNaming.NamingContextFactory;
var
_obj : Corba.CorbaObject;
begin
_obj := Orb.GetObjectRef(_A);
Result := TNamingContextFactoryHelper.Narrow(_obj, True);
end;
class function TNamingContextFactoryHelper.TypeCode : CORBA.TypeCode;
begin
Result := ORB.CreateInterfaceTC(RepositoryId, 'NamingContextFactory');
end;
class function TNamingContextFactoryHelper.RepositoryId : string;
begin
Result := 'IDL:omg.org/CosNaming/NamingContextFactory:1.0';
end;
class function TNamingContextFactoryHelper.Read(const _Input : CORBA.InputStream) : CosNaming.NamingContextFactory;
var
_Obj : CORBA.CORBAObject;
begin
_Input.ReadObject(_Obj);
Result := Narrow(_Obj, True)
end;
class procedure TNamingContextFactoryHelper.Write(const _Output : CORBA.OutputStream; const _Value : CosNaming.NamingContextFactory);
begin
_Output.WriteObject(_Value as CORBA.CORBAObject);
end;
class function TNamingContextFactoryHelper.Narrow(const _Obj : CORBA.CORBAObject; _IsA : Boolean) : CosNaming.NamingContextFactory;
begin
Result := nil;
if (_Obj = nil) or (_Obj.QueryInterface(CosNaming.NamingContextFactory, Result) = 0)
then Exit;
if _IsA and _Obj._IsA(RepositoryId) then
Result := TNamingContextFactoryStub.Create(_Obj);
end;
class function TNamingContextFactoryHelper.Bind(const _InstanceName : string = ''; _HostName: string = '') : CosNaming.NamingContextFactory;
begin
Result := Narrow(ORB.bind(RepositoryId, _InstanceName, _HostName), True);
end;
class function TNamingContextFactoryHelper.Bind(_Options : BindOptions; const _InstanceName : string = ''; _HostName : string = '') : CosNaming.NamingContextFactory;
begin
Result := Narrow(ORB.bind(RepositoryId, _Options, _InstanceName, _HostName), True);
end;
{Naming Context Factory Stub}
function TNamingContextFactoryStub.create_context : CosNaming.NamingContext;
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('create_context',True, _Output);
inherited _Invoke(_Output, _Input);
Result := CosNaming.TNamingContextHelper.Read(_Input);
end;
procedure TNamingContextFactoryStub.shutdown ;
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('shutdown',False, _Output);
inherited _Invoke(_Output, _Input);
end;
{Extended Naming Context Factory Helper}
class procedure TExtendedNamingContextFactoryHelper.Insert(var _A : CORBA.Any; const _Value : CosNaming.ExtendedNamingContextFactory);
begin
_A := Orb.MakeObjectRef( TExtendedNamingContextFactoryHelper.TypeCode, _Value as CORBA.CORBAObject);
end;
class function TExtendedNamingContextFactoryHelper.Extract(var _A : CORBA.Any): CosNaming.ExtendedNamingContextFactory;
var
_obj : Corba.CorbaObject;
begin
_obj := Orb.GetObjectRef(_A);
Result := TExtendedNamingContextFactoryHelper.Narrow(_obj, True);
end;
class function TExtendedNamingContextFactoryHelper.TypeCode : CORBA.TypeCode;
begin
Result := ORB.CreateInterfaceTC(RepositoryId, 'ExtendedNamingContextFactory');
end;
class function TExtendedNamingContextFactoryHelper.RepositoryId : string;
begin
Result := 'IDL:omg.org/CosNaming/ExtendedNamingContextFactory:1.0';
end;
class function TExtendedNamingContextFactoryHelper.Read(const _Input : CORBA.InputStream) : CosNaming.ExtendedNamingContextFactory;
var
_Obj : CORBA.CORBAObject;
begin
_Input.ReadObject(_Obj);
Result := Narrow(_Obj, True)
end;
class procedure TExtendedNamingContextFactoryHelper.Write(const _Output : CORBA.OutputStream; const _Value : CosNaming.ExtendedNamingContextFactory);
begin
_Output.WriteObject(_Value as CORBA.CORBAObject);
end;
class function TExtendedNamingContextFactoryHelper.Narrow(const _Obj : CORBA.CORBAObject; _IsA : Boolean) : CosNaming.ExtendedNamingContextFactory;
begin
Result := nil;
if (_Obj = nil) or (_Obj.QueryInterface(CosNaming.ExtendedNamingContextFactory, Result) = 0)
then Exit;
if _IsA and _Obj._IsA(RepositoryId) then
Result := TExtendedNamingContextFactoryStub.Create(_Obj);
end;
class function TExtendedNamingContextFactoryHelper.Bind(const _InstanceName : string = ''; _HostName: string = '') : CosNaming.ExtendedNamingContextFactory;
begin
Result := Narrow(ORB.bind(RepositoryId, _InstanceName, _HostName), True);
end;
class function TExtendedNamingContextFactoryHelper.Bind(_Options : BindOptions; const _InstanceName : string = ''; _HostName : string = '') : CosNaming.ExtendedNamingContextFactory;
begin
Result := Narrow(ORB.bind(RepositoryId, _Options, _InstanceName, _HostName), True);
end;
{Extended Naming Context Factory Stub}
function TExtendedNamingContextFactoryStub.root_context : CosNaming.NamingContext;
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('root_context',True, _Output);
inherited _Invoke(_Output, _Input);
Result := CosNaming.TNamingContextHelper.Read(_Input);
end;
function TExtendedNamingContextFactoryStub.create_context : CosNaming.NamingContext;
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('create_context',True, _Output);
inherited _Invoke(_Output, _Input);
Result := CosNaming.TNamingContextHelper.Read(_Input);
end;
procedure TExtendedNamingContextFactoryStub.shutdown ;
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('shutdown',False, _Output);
inherited _Invoke(_Output, _Input);
end;
{LName Component Helper}
class procedure TLNameComponentHelper.Insert(var _A : CORBA.Any; const _Value : CosNaming.LNameComponent);
begin
_A := Orb.MakeObjectRef( TLNameComponentHelper.TypeCode, _Value as CORBA.CORBAObject);
end;
class function TLNameComponentHelper.Extract(var _A : CORBA.Any): CosNaming.LNameComponent;
var
_obj : Corba.CorbaObject;
begin
_obj := Orb.GetObjectRef(_A);
Result := TLNameComponentHelper.Narrow(_obj, True);
end;
class function TLNameComponentHelper.TypeCode : CORBA.TypeCode;
begin
Result := ORB.CreateInterfaceTC(RepositoryId, 'LNameComponent');
end;
class function TLNameComponentHelper.RepositoryId : string;
begin
Result := 'IDL:omg.org/CosNaming/LNameComponent:1.0';
end;
class function TLNameComponentHelper.Read(const _Input : CORBA.InputStream) : CosNaming.LNameComponent;
var
_Obj : CORBA.CORBAObject;
begin
_Input.ReadObject(_Obj);
Result := Narrow(_Obj, True)
end;
class procedure TLNameComponentHelper.Write(const _Output : CORBA.OutputStream; const _Value : CosNaming.LNameComponent);
begin
_Output.WriteObject(_Value as CORBA.CORBAObject);
end;
class function TLNameComponentHelper.Narrow(const _Obj : CORBA.CORBAObject; _IsA : Boolean) : CosNaming.LNameComponent;
begin
Result := nil;
if (_Obj = nil) or (_Obj.QueryInterface(CosNaming.LNameComponent, Result) = 0)
then Exit;
if _IsA and _Obj._IsA(RepositoryId) then
Result := TLNameComponentStub.Create(_Obj);
end;
class function TLNameComponentHelper.Bind(const _InstanceName : string = ''; _HostName: string = '') : CosNaming.LNameComponent;
begin
Result := Narrow(ORB.bind(RepositoryId, _InstanceName, _HostName), True);
end;
class function TLNameComponentHelper.Bind(_Options : BindOptions; const _InstanceName : string = ''; _HostName : string = '') : CosNaming.LNameComponent;
begin
Result := Narrow(ORB.bind(RepositoryId, _Options, _InstanceName, _HostName), True);
end;
{LName Component Stub}
function TLNameComponentStub.get_id : AnsiString;
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('get_id',True, _Output);
inherited _Invoke(_Output, _Input);
_Input.ReadString(Result);
end;
procedure TLNameComponentStub.set_id ( const id : AnsiString);
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('set_id',True, _Output);
_Output.WriteString(id);
inherited _Invoke(_Output, _Input);
end;
function TLNameComponentStub.get_kind : AnsiString;
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('get_kind',True, _Output);
inherited _Invoke(_Output, _Input);
_Input.ReadString(Result);
end;
procedure TLNameComponentStub.set_kind ( const kind : AnsiString);
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('set_kind',True, _Output);
_Output.WriteString(kind);
inherited _Invoke(_Output, _Input);
end;
procedure TLNameComponentStub._destroy ;
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('destroy',True, _Output);
inherited _Invoke(_Output, _Input);
end;
{LName Component Not Set Exception}
constructor ELNameComponent_NotSet.Create;
begin
inherited Create;
end;
procedure ELNameComponent_NotSet.Copy(const _Input: InputStream);
begin
end;
procedure ELNameComponent_NotSet.WriteExceptionInfo(var _Output : OutputStream);
begin
_Output.WriteString('IDL:omg.org/CosNaming/LNameComponent/NotSet:1.0');
end;
function LNameComponent_NotSet_Factory: PExceptionProxy; cdecl;
begin
with CosNaming.ELNameComponent_NotSet.Create() do Result := Proxy;
end;
{LName Helper}
class procedure TLNameHelper.Insert(var _A : CORBA.Any; const _Value : CosNaming.LName);
begin
_A := Orb.MakeObjectRef( TLNameHelper.TypeCode, _Value as CORBA.CORBAObject);
end;
class function TLNameHelper.Extract(var _A : CORBA.Any): CosNaming.LName;
var
_obj : Corba.CorbaObject;
begin
_obj := Orb.GetObjectRef(_A);
Result := TLNameHelper.Narrow(_obj, True);
end;
class function TLNameHelper.TypeCode : CORBA.TypeCode;
begin
Result := ORB.CreateInterfaceTC(RepositoryId, 'LName');
end;
class function TLNameHelper.RepositoryId : string;
begin
Result := 'IDL:omg.org/CosNaming/LName:1.0';
end;
class function TLNameHelper.Read(const _Input : CORBA.InputStream) : CosNaming.LName;
var
_Obj : CORBA.CORBAObject;
begin
_Input.ReadObject(_Obj);
Result := Narrow(_Obj, True)
end;
class procedure TLNameHelper.Write(const _Output : CORBA.OutputStream; const _Value : CosNaming.LName);
begin
_Output.WriteObject(_Value as CORBA.CORBAObject);
end;
class function TLNameHelper.Narrow(const _Obj : CORBA.CORBAObject; _IsA : Boolean) : CosNaming.LName;
begin
Result := nil;
if (_Obj = nil) or (_Obj.QueryInterface(CosNaming.LName, Result) = 0)
then Exit;
if _IsA and _Obj._IsA(RepositoryId) then
Result := TLNameStub.Create(_Obj);
end;
class function TLNameHelper.Bind(const _InstanceName : string = ''; _HostName: string = '') : CosNaming.LName;
begin
Result := Narrow(ORB.bind(RepositoryId, _InstanceName, _HostName), True);
end;
class function TLNameHelper.Bind(_Options : BindOptions; const _InstanceName : string = ''; _HostName : string = '') : CosNaming.LName;
begin
Result := Narrow(ORB.bind(RepositoryId, _Options, _InstanceName, _HostName), True);
end;
{LName Stub}
function TLNameStub.insert_component(const index : Cardinal;
const nameComponent : CosNaming.LNameComponent): CosNaming.LName;
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('insert_component',True, _Output);
_Output.WriteULong(index);
CosNaming.TLNameComponentHelper.Write(_Output, nameComponent);
inherited _Invoke(_Output, _Input);
Result := CosNaming.TLNameHelper.Read(_Input);
end;
function TLNameStub.get_component(const index : Cardinal): CosNaming.LNameComponent;
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('get_component',True, _Output);
_Output.WriteULong(index);
inherited _Invoke(_Output, _Input);
Result := CosNaming.TLNameComponentHelper.Read(_Input);
end;
function TLNameStub.delete_component(const index : Cardinal): CosNaming.LNameComponent;
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('delete_component',True, _Output);
_Output.WriteULong(index);
inherited _Invoke(_Output, _Input);
Result := CosNaming.TLNameComponentHelper.Read(_Input);
end;
function TLNameStub.num_components : Cardinal;
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('num_components',True, _Output);
inherited _Invoke(_Output, _Input);
_Input.ReadULong(Result);
end;
function TLNameStub.equal(const name : CosNaming.LName): Boolean;
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('equal',True, _Output);
CosNaming.TLNameHelper.Write(_Output, name);
inherited _Invoke(_Output, _Input);
_Input.ReadBoolean(Result);
end;
function TLNameStub.less_than(const name : CosNaming.LName): Boolean;
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('less_than',True, _Output);
CosNaming.TLNameHelper.Write(_Output, name);
inherited _Invoke(_Output, _Input);
_Input.ReadBoolean(Result);
end;
function TLNameStub.to_idl_form : CosNaming.Name;
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('to_idl_form',True, _Output);
inherited _Invoke(_Output, _Input);
Result := CosNaming.TNameHelper.Read(_Input);
end;
procedure TLNameStub.from_idl_form(const name : CosNaming.Name);
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('from_idl_form',True, _Output);
CosNaming.TNameHelper.Write(_Output, name);
inherited _Invoke(_Output, _Input);
end;
procedure TLNameStub._destroy;
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('destroy',True, _Output);
inherited _Invoke(_Output, _Input);
end;
{LName Exception No Component}
constructor ELName_NoComponent.Create;
begin
inherited Create;
end;
procedure ELName_NoComponent.Copy(const _Input: InputStream);
begin
end;
procedure ELName_NoComponent.WriteExceptionInfo(var _Output : OutputStream);
begin
_Output.WriteString('IDL:omg.org/CosNaming/LName/NoComponent:1.0');
end;
function LName_NoComponent_Factory: PExceptionProxy; cdecl;
begin
with CosNaming.ELName_NoComponent.Create() do Result := Proxy;
end;
{LName Exception OverFlow}
constructor ELName_OverFlow.Create;
begin
inherited Create;
end;
procedure ELName_OverFlow.Copy(const _Input: InputStream);
begin
end;
procedure ELName_OverFlow.WriteExceptionInfo(var _Output : OutputStream);
begin
_Output.WriteString('IDL:omg.org/CosNaming/LName/OverFlow:1.0');
end;
function LName_OverFlow_Factory: PExceptionProxy; cdecl;
begin
with CosNaming.ELName_OverFlow.Create() do Result := Proxy;
end;
{LName Exception Invalid Name}
constructor ELName_InvalidName.Create;
begin
inherited Create;
end;
procedure ELName_InvalidName.Copy(const _Input: InputStream);
begin
end;
procedure ELName_InvalidName.WriteExceptionInfo(var _Output : OutputStream);
begin
_Output.WriteString('IDL:omg.org/CosNaming/LName/InvalidName:1.0');
end;
function LName_InvalidName_Factory: PExceptionProxy; cdecl;
begin
with CosNaming.ELName_InvalidName.Create() do Result := Proxy;
end;
{LName Factory Helper}
class procedure TLNameFactoryHelper.Insert(var _A : CORBA.Any; const _Value : CosNaming.LNameFactory);
begin
_A := Orb.MakeObjectRef( TLNameFactoryHelper.TypeCode, _Value as CORBA.CORBAObject);
end;
class function TLNameFactoryHelper.Extract(var _A : CORBA.Any): CosNaming.LNameFactory;
var
_obj : Corba.CorbaObject;
begin
_obj := Orb.GetObjectRef(_A);
Result := TLNameFactoryHelper.Narrow(_obj, True);
end;
class function TLNameFactoryHelper.TypeCode : CORBA.TypeCode;
begin
Result := ORB.CreateInterfaceTC(RepositoryId, 'LNameFactory');
end;
class function TLNameFactoryHelper.RepositoryId : string;
begin
Result := 'IDL:omg.org/CosNaming/LNameFactory:1.0';
end;
class function TLNameFactoryHelper.Read(const _Input : CORBA.InputStream) : CosNaming.LNameFactory;
var
_Obj : CORBA.CORBAObject;
begin
_Input.ReadObject(_Obj);
Result := Narrow(_Obj, True)
end;
class procedure TLNameFactoryHelper.Write(const _Output : CORBA.OutputStream; const _Value : CosNaming.LNameFactory);
begin
_Output.WriteObject(_Value as CORBA.CORBAObject);
end;
class function TLNameFactoryHelper.Narrow(const _Obj : CORBA.CORBAObject; _IsA : Boolean) : CosNaming.LNameFactory;
begin
Result := nil;
if (_Obj = nil) or (_Obj.QueryInterface(CosNaming.LNameFactory, Result) = 0)
then Exit;
if _IsA and _Obj._IsA(RepositoryId) then
Result := TLNameFactoryStub.Create(_Obj);
end;
class function TLNameFactoryHelper.Bind(const _InstanceName : string = ''; _HostName: string = '') : CosNaming.LNameFactory;
begin
Result := Narrow(ORB.bind(RepositoryId, _InstanceName, _HostName), True);
end;
class function TLNameFactoryHelper.Bind(_Options : BindOptions; const _InstanceName : string = ''; _HostName : string = '') : CosNaming.LNameFactory;
begin
Result := Narrow(ORB.bind(RepositoryId, _Options, _InstanceName, _HostName), True);
end;
function TLNameFactoryStub.create_lname : CosNaming.LName;
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('create_lname',True, _Output);
inherited _Invoke(_Output, _Input);
Result := CosNaming.TLNameHelper.Read(_Input);
end;
function TLNameFactoryStub.create_lname_component : CosNaming.LNameComponent;
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('create_lname_component',True, _Output);
inherited _Invoke(_Output, _Input);
Result := CosNaming.TLNameComponentHelper.Read(_Input);
end;
{Log Record Helper}
class procedure TLogRecordHelper.Insert(var _A : CORBA.Any; const _Value : CosNaming.LogRecord);
var
_Output : CORBA.OutputStream;
begin
_Output := ORB.CreateOutputStream;
TLogRecordHelper.Write(_Output, _Value);
ORB.PutAny(_A, TLogRecordHelper.TypeCode, _Output);
end;
class function TLogRecordHelper.Extract(const _A : CORBA.Any) : CosNaming.LogRecord;
var
_Input : CORBA.InputStream;
begin
Orb.GetAny(_A, _Input);
Result := TLogRecordHelper.Read(_Input);
end;
class function TLogRecordHelper.TypeCode : CORBA.TypeCode;
var
_Seq: StructMemberSeq;
begin
SetLength(_Seq, 6);
_Seq[0].Name := 'operation_key';
_Seq[0].TC := ORB.CreateTC(Integer(tk_char));
_Seq[1].Name := 'context_index';
_Seq[1].TC := ORB.CreateTC(Integer(tk_long));
_Seq[2].Name := 'name';
_Seq[2].TC := CosNaming.TNameHelper.TypeCode;
_Seq[3].Name := 'target_object';
_Seq[3].TC := ORB.CreateTC(Integer(tk_objref));
_Seq[4].Name := 'target_context';
_Seq[4].TC := CosNaming.TNamingContextHelper.TypeCode;
_Seq[5].Name := 'target_context_index';
_Seq[5].TC := ORB.CreateTC(Integer(tk_long));
Result := ORB.MakeStructureTypecode(RepositoryID, 'LogRecord', _Seq);
end;
class function TLogRecordHelper.RepositoryId : string;
begin
Result := 'IDL:omg.org/CosNaming/LogRecord:1.0';
end;
class function TLogRecordHelper.Read(const _Input : CORBA.InputStream) : CosNaming.LogRecord;
var
_Value : CosNaming.TLogRecord;
begin
_Value := CosNaming.TLogRecord.Create;
_Input.ReadChar(_Value.operation_key);
_Input.ReadLong(_Value.context_index);
_Value.name := CosNaming.TNameHelper.Read(_Input);
_Input.ReadObject(_Value.target_object);
_Value.target_context := CosNaming.TNamingContextHelper.Read(_Input);
_Input.ReadLong(_Value.target_context_index);
Result := _Value;
end;
class procedure TLogRecordHelper.Write(const _Output : CORBA.OutputStream; const _Value : CosNaming.LogRecord);
begin
_Output.WriteChar(_Value.operation_key);
_Output.WriteLong(_Value.context_index);
CosNaming.TNameHelper.Write(_Output, _Value.name);
_Output.WriteObject(_Value.target_object);
CosNaming.TNamingContextHelper.Write(_Output, _Value.target_context);
_Output.WriteLong(_Value.target_context_index);
end;
{TLogRecord}
constructor TLogRecord.Create;
begin
inherited Create;
end;
constructor TLogRecord.Create(const operation_key: Char;
const context_index: Integer;
const name: CosNaming.Name;
const target_object: CORBAObject;
const target_context: CosNaming.NamingContext;
const target_context_index: Integer);
begin
Self.operation_key := operation_key;
Self.context_index := context_index;
Self.name := name;
Self.target_object := target_object;
Self.target_context := target_context;
Self.target_context_index := target_context_index;
end;
function TLogRecord._get_operation_key: Char;
begin
Result := operation_key;
end;
procedure TLogRecord._set_operation_key(const _Value : Char);
begin
operation_key := _Value;
end;
function TLogRecord._get_context_index: Integer;
begin
Result := context_index;
end;
procedure TLogRecord._set_context_index(const _Value : Integer);
begin
context_index := _Value;
end;
function TLogRecord._get_name: CosNaming.Name;
begin
Result := name;
end;
procedure TLogRecord._set_name(const _Value : CosNaming.Name);
begin
name := _Value;
end;
function TLogRecord._get_target_object: CORBAObject;
begin
Result := target_object;
end;
procedure TLogRecord._set_target_object(const _Value : CORBAObject);
begin
target_object := _Value;
end;
function TLogRecord._get_target_context: CosNaming.NamingContext;
begin
Result := target_context;
end;
procedure TLogRecord._set_target_context(const _Value : CosNaming.NamingContext);
begin
target_context := _Value;
end;
function TLogRecord._get_target_context_index: Integer;
begin
Result := target_context_index;
end;
procedure TLogRecord._set_target_context_index(const _Value : Integer);
begin
target_context_index := _Value;
end;
{TLogHelper}
class procedure TLogHelper.Insert(var _A : CORBA.Any; const _Value : CosNaming.Log);
begin
_A := Orb.MakeObjectRef( TLogHelper.TypeCode, _Value as CORBA.CORBAObject);
end;
class function TLogHelper.Extract(var _A : CORBA.Any): CosNaming.Log;
var
_obj : Corba.CorbaObject;
begin
_obj := Orb.GetObjectRef(_A);
Result := TLogHelper.Narrow(_obj, True);
end;
class function TLogHelper.TypeCode : CORBA.TypeCode;
begin
Result := ORB.CreateInterfaceTC(RepositoryId, 'Log');
end;
class function TLogHelper.RepositoryId : string;
begin
Result := 'IDL:omg.org/CosNaming/Log:1.0';
end;
class function TLogHelper.Read(const _Input : CORBA.InputStream) : CosNaming.Log;
var
_Obj : CORBA.CORBAObject;
begin
_Input.ReadObject(_Obj);
Result := Narrow(_Obj, True)
end;
class procedure TLogHelper.Write(const _Output : CORBA.OutputStream; const _Value : CosNaming.Log);
begin
_Output.WriteObject(_Value as CORBA.CORBAObject);
end;
class function TLogHelper.Narrow(const _Obj : CORBA.CORBAObject; _IsA : Boolean) : CosNaming.Log;
begin
Result := nil;
if (_Obj = nil) or (_Obj.QueryInterface(CosNaming.Log, Result) = 0)
then Exit;
if _IsA and _Obj._IsA(RepositoryId) then
Result := TLogStub.Create(_Obj);
end;
class function TLogHelper.Bind(const _InstanceName : string = ''; _HostName: string = '') : CosNaming.Log;
begin
Result := Narrow(ORB.bind(RepositoryId, _InstanceName, _HostName), True);
end;
class function TLogHelper.Bind(_Options : BindOptions; const _InstanceName : string = ''; _HostName : string = '') : CosNaming.Log;
begin
Result := Narrow(ORB.bind(RepositoryId, _Options, _InstanceName, _HostName), True);
end;
{TLogStub}
procedure TLogStub.bind(const ctx : CosNaming.NamingContext;
const n : CosNaming.Name;
const obj : CORBAObject);
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('bind',True, _Output);
CosNaming.TNamingContextHelper.Write(_Output, ctx);
CosNaming.TNameHelper.Write(_Output, n);
_Output.WriteObject(obj);
inherited _Invoke(_Output, _Input);
end;
procedure TLogStub.bind_context(const ctx : CosNaming.NamingContext;
const n : CosNaming.Name;
const nc : CosNaming.NamingContext);
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('bind_context',True, _Output);
CosNaming.TNamingContextHelper.Write(_Output, ctx);
CosNaming.TNameHelper.Write(_Output, n);
CosNaming.TNamingContextHelper.Write(_Output, nc);
inherited _Invoke(_Output, _Input);
end;
procedure TLogStub.unbind(const ctx : CosNaming.NamingContext;
const n : CosNaming.Name);
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('unbind',True, _Output);
CosNaming.TNamingContextHelper.Write(_Output, ctx);
CosNaming.TNameHelper.Write(_Output, n);
inherited _Invoke(_Output, _Input);
end;
procedure TLogStub.new_context(const ctx : CosNaming.NamingContext);
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('new_context',True, _Output);
CosNaming.TNamingContextHelper.Write(_Output, ctx);
inherited _Invoke(_Output, _Input);
end;
procedure TLogStub._destroy(const ctx : CosNaming.NamingContext);
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('destroy',True, _Output);
CosNaming.TNamingContextHelper.Write(_Output, ctx);
inherited _Invoke(_Output, _Input);
end;
initialization
CORBA.InterfaceIDManager.RegisterInterface(CosNaming.BindingIterator, CosNaming.TBindingIteratorHelper.RepositoryId);
CORBA.InterfaceIDManager.RegisterInterface(CosNaming.NamingContext, CosNaming.TNamingContextHelper.RepositoryId);
CORBA.InterfaceIDManager.RegisterInterface(CosNaming.NamingContextFactory, CosNaming.TNamingContextFactoryHelper.RepositoryId);
CORBA.InterfaceIDManager.RegisterInterface(CosNaming.ExtendedNamingContextFactory, CosNaming.TExtendedNamingContextFactoryHelper.RepositoryId);
CORBA.InterfaceIDManager.RegisterInterface(CosNaming.LNameComponent, CosNaming.TLNameComponentHelper.RepositoryId);
CORBA.InterfaceIDManager.RegisterInterface(CosNaming.LName, CosNaming.TLNameHelper.RepositoryId);
CORBA.InterfaceIDManager.RegisterInterface(CosNaming.LNameFactory, CosNaming.TLNameFactoryHelper.RepositoryId);
CORBA.InterfaceIDManager.RegisterInterface(CosNaming.Log, CosNaming.TLogHelper.RepositoryId);
CosNaming.NamingContext_NotFoundDesc := RegisterUserException('NotFound', 'IDL:omg.org/CosNaming/NamingContext/NotFound:1.0', @CosNaming.NamingContext_NotFound_Factory);
CosNaming.NamingContext_CannotProceedDesc := RegisterUserException('CannotProceed', 'IDL:omg.org/CosNaming/NamingContext/CannotProceed:1.0', @CosNaming.NamingContext_CannotProceed_Factory);
CosNaming.NamingContext_InvalidNameDesc := RegisterUserException('InvalidName', 'IDL:omg.org/CosNaming/NamingContext/InvalidName:1.0', @CosNaming.NamingContext_InvalidName_Factory);
CosNaming.NamingContext_AlreadyBoundDesc := RegisterUserException('AlreadyBound', 'IDL:omg.org/CosNaming/NamingContext/AlreadyBound:1.0', @CosNaming.NamingContext_AlreadyBound_Factory);
CosNaming.NamingContext_NotEmptyDesc := RegisterUserException('NotEmpty', 'IDL:omg.org/CosNaming/NamingContext/NotEmpty:1.0', @CosNaming.NamingContext_NotEmpty_Factory);
CosNaming.LNameComponent_NotSetDesc := RegisterUserException('NotSet', 'IDL:omg.org/CosNaming/LNameComponent/NotSet:1.0', @CosNaming.LNameComponent_NotSet_Factory);
CosNaming.LName_NoComponentDesc := RegisterUserException('NoComponent', 'IDL:omg.org/CosNaming/LName/NoComponent:1.0', @CosNaming.LName_NoComponent_Factory);
CosNaming.LName_OverFlowDesc := RegisterUserException('OverFlow', 'IDL:omg.org/CosNaming/LName/OverFlow:1.0', @CosNaming.LName_OverFlow_Factory);
CosNaming.LName_InvalidNameDesc := RegisterUserException('InvalidName', 'IDL:omg.org/CosNaming/LName/InvalidName:1.0', @CosNaming.LName_InvalidName_Factory);
finalization
UnRegisterUserException(CosNaming.NamingContext_NotFoundDesc);
UnRegisterUserException(CosNaming.NamingContext_CannotProceedDesc);
UnRegisterUserException(CosNaming.NamingContext_InvalidNameDesc);
UnRegisterUserException(CosNaming.NamingContext_AlreadyBoundDesc);
UnRegisterUserException(CosNaming.NamingContext_NotEmptyDesc);
UnRegisterUserException(CosNaming.LNameComponent_NotSetDesc);
UnRegisterUserException(CosNaming.LName_NoComponentDesc);
UnRegisterUserException(CosNaming.LName_OverFlowDesc);
UnRegisterUserException(CosNaming.LName_InvalidNameDesc);
end.
|
unit ReconcileProd;
interface
uses MidProd, WebComp, HTTPApp, Classes, XmlBrokr, MidItems;
type
TReconcileGrid = class;
TReconcilePageElements = class;
TReconcilePageProducer = class(TCustomMidasPageProducer)
private
FReconcileGrid: TReconcileGrid;
FXMLBroker: TXMLBroker;
procedure SetReconcileGrid(const Value: TReconcileGrid);
protected
procedure DoTagEvent(Tag: TTag; const TagString: string; TagParams: TStrings;
var ReplaceText: string); override;
procedure GeneratePageElements; override;
function CreatePageElements: TMidasPageElements; override;
procedure AddIncludes; override;
function DeclareRowSets: string; override;
procedure AddScriptComponents; override;
function DeclareXMLDocuments: string; override;
function DeclareXMLIslands: string; override;
procedure GetXMLInfo(
var XMLBrokerName, XMLErrors, XMLDelta: string;
XMLOptions: TXMLOptions);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property IncludePathURL;
property OnBeforeGetContent;
property OnAfterGetContent;
property Styles;
property StylesFile;
property WebPageItems;
property EnableXMLIslands;
property ReconcileGrid: TReconcileGrid read FReconcileGrid write SetReconcileGrid;
end;
TReconcileColumn = class;
TReconcileGrid = class(TPersistent)
private
FDisplayRows: Integer;
FTableAttributes: TGridAttributes;
FHeadingAttributes: TGridRowAttributes;
FRowAttributes: TGridRowAttributes;
FFieldNameColumn: TReconcileColumn;
FModifiedColumn: TReconcileColumn;
FConflictingColumn: TReconcileColumn;
FOriginalColumn: TReconcileColumn;
function GetColumn(I: Integer): TReconcileColumn;
function GetColumnCount: Integer;
procedure SetConflictingColumn(const Value: TReconcileColumn);
procedure SetFieldNameColumn(const Value: TReconcileColumn);
procedure SetModifiedColumn(const Value: TReconcileColumn);
procedure SetOriginalColumn(const Value: TReconcileColumn);
protected
function HTMLTableName: string;
function FormatTable(Layout: TLayoutWebContent;
Options: TWebContentOptions): string;
procedure SetTableAttributes(const Value: TGridAttributes);
procedure SetHeadingAttributes(
const Value: TGridRowAttributes);
procedure SetRowAttributes(
const Value: TGridRowAttributes);
procedure AssignTo(Dest: TPersistent); override;
public
constructor Create(AOwner: TComponent);
destructor Destroy; override;
property ColumnCount: Integer read GetColumnCount;
property Column[I: Integer]: TReconcileColumn read GetColumn;
published
property DisplayRows: Integer read FDisplayRows write FDisplayRows default 4;
property TableAttributes: TGridAttributes read FTableAttributes
write SetTableAttributes;
property HeadingAttributes: TGridRowAttributes read FHeadingAttributes
write SetHeadingAttributes;
property RowAttributes: TGridRowAttributes read FRowAttributes
write SetRowAttributes;
property ConflictingColumn: TReconcileColumn read FConflictingColumn write SetConflictingColumn;
property FieldNameColumn: TReconcileColumn read FFieldNameColumn write SetFieldNameColumn;
property ModifiedColumn: TReconcileColumn read FModifiedColumn write SetModifiedColumn;
property OriginalColumn: TReconcileColumn read FOriginalColumn write SetOriginalColumn;
end;
TReconcileColumn = class(TPersistent)
private
FCaption: string;
FStyle: string;
FStyleRule: string;
FCustom: string;
FCaptionAttributes: TCaptionAttributes;
FDisplayWidth: integer;
FMaxWidth: integer;
FName: string;
FEvents: string;
procedure SetCaptionAttributes(const Value: TCaptionAttributes);
protected
procedure AssignTo(Dest: TPersistent); override;
property Name: string read FName write FName;
property Events: string read FEvents write FEvents;
public
constructor Create(AOwner: TComponent);
destructor Destroy; override;
function ControlContent(Options: TWebContentOptions): string;
function GetHTMLControlName: string;
published
property Caption: string read FCaption write FCaption;
property Custom: string read FCustom write FCustom;
property Style: string read FStyle write FStyle;
property MaxWidth: Integer read FMaxWidth write FMaxWidth default -1;
property CaptionAttributes: TCaptionAttributes
read FCaptionAttributes write SetCaptionAttributes;
property DisplayWidth: integer read FDisplayWidth write FDisplayWidth;
property StyleRule: string read FStyleRule write FStyleRule;
end;
TFieldNameColumn = class(TReconcileColumn)
public
constructor Create(AOwner: TComponent);
end;
TModifiedColumn = class(TReconcileColumn)
public
constructor Create(AOwner: TComponent);
end;
TConflictingColumn = class(TReconcileColumn)
public
constructor Create(AOwner: TComponent);
end;
TOriginalColumn = class(TReconcileColumn)
public
constructor Create(AOwner: TComponent);
end;
TReconcilePageElements = class(TMidasPageElements)
public
ReconcileGridContent: string;
end;
implementation
uses ScrptMgr, SysUtils, WbmConst;
const
sXMLBroker = 'XMLBROKER';
sErrorPacketTag = 'ERRORPACKET';
sDeltaPacketTag = 'DELTAPACKET';
sReconcileGridTag = 'RECONCILEGRID';
sQuoteXMLAttribute = 'QUOTE';
sQuoteXML = sQuoteXMLAttribute + '="True"'; // Do not localize
sDefaultXMLBrokerName = 'XMLBroker1';
resourcestring
sFieldNameCaption = 'Field Name';
sModifiedCaption = 'Submitted Value';
sConflictingCaption = 'Conflicting Value';
sOriginalCaption = 'Original Value';
{ TReconcilePageProducer }
procedure TReconcilePageProducer.DoTagEvent(Tag: TTag;
const TagString: string; TagParams: TStrings; var ReplaceText: string);
var
XMLBroker: TXMLBroker;
XMLOptions: TXMLOptions;
begin
if not (csDesigning in ComponentState) then
if (Tag = tgCustom) and (CompareText(TagString, sDeltaPacketTag) = 0) then
begin
XMLOptions := [];
if CompareText(TagParams.Values[sQuoteXMLAttribute], 'True') = 0 then
XMLOptions := XMLOptions + [xoQuote];
XMLBroker := FindXMLBroker(TagParams);
if Assigned(XMLBroker) then
ReplaceText :=
FormatXML(XMLBroker.GetDelta(Dispatcher.Request),
XMLOptions);
Exit;
end
else if (Tag = tgCustom) and (CompareText(TagString, sErrorPacketTag) = 0) then
begin
XMLOptions := [];
if CompareText(TagParams.Values[sQuoteXMLAttribute], 'True') = 0 then
XMLOptions := XMLOptions + [xoQuote];
XMLBroker := FindXMLBroker(TagParams);
if Assigned(XMLBroker) then
ReplaceText := FormatXML(XMLBroker.GetErrors, XMLOptions);
Exit;
end;
if (Tag = tgCustom) and (CompareText(TagString, sReconcileGridTag) = 0) then
begin
if Assigned(PageElements) then
ReplaceText := (PageElements as TReconcilePageElements).ReconcileGridContent;
Exit;
end;
inherited DoTagEvent(Tag, TagString, TagParams, ReplaceText);
end;
procedure TReconcilePageProducer.AddIncludes;
var
StdIncludes: TStdIncludes;
begin
StdIncludes := [jsDb, jsErrDisp];
if not GetUseXMLIslands then
StdIncludes := StdIncludes + [jsDom];
AddStdIncludes(StdIncludes, ScriptManager.GetAddElementsIntf);
end;
function TReconcilePageProducer.CreatePageElements: TMidasPageElements;
begin
Result := TReconcilePageElements.Create;
end;
const
sErrXMLVarName = 'xmlErrStr';
sDeltaXMLVarName = 'xmlDeltaStr';
sErrDocVarName = 'xmlErrDoc';
sDeltaDocVarName = 'xmlDeltaDoc';
procedure TReconcilePageProducer.GeneratePageElements;
function FindXMLBroker: TXMLBroker;
var
I: Integer;
begin
for I := 0 to Owner.ComponentCount - 1 do
if Owner.Components[I] is TXMLBroker then
begin
Result := TXMLBroker(Owner.Components[I]);
if Result.GetErrors <> '' then Exit;
end;
Result := nil;
end;
begin
if csDesigning in ComponentState then
FXMLBroker := nil
else
FXMLBroker := FindXMLBroker;
try
inherited GeneratePageElements;
(PageElements as TReconcilePageElements).ReconcileGridContent :=
FReconcileGrid.FormatTable(nil, ScriptManager.Options);
finally
FXMLBroker := nil;
end;
end;
resourcestring
sErrorMessage = 'Error message:';
sOn = 'on';
sCancel = 'Cancel';
sCorrect = 'Correct';
sMerge = 'Merge';
sPrevRow = '<';
sNextRow = '>';
sPostNext = 'Post/Next';
sReapply = 'Reapply Updates';
sReconcileAction = 'Reconcile Action';
const
sDefaultHTMLDoc =
'<HTML>'#13#10 +
'<HEAD>'#13#10 +
'</HEAD>'#13#10 +
'<BODY>'#13#10 +
'<#INCLUDES><#STYLES><#WARNINGS>'#13#10 +
'<P>'#13#10 +
'<FORM name="FORM1">'#13#10 +
'<TABLE>'#13#10 +
'<TR>'#13#10 +
'<TD valign=top><H3>%0:s</H3></TD>'#13#10 +
'<TD valign=top><textarea name="ErrMessage" rows=2 cols=58 readonly onfocus=''blur();''></textarea></TD>'#13#10 +
'<TD valign=top><H3>%1:s</H3></TD>'#13#10 +
'<TD valign=top><input type=text name="ErrAction" size=12 readonly onfocus=''blur();''/></TD>'#13#10 +
'</TR>'#13#10 +
'</TABLE>'#13#10 +
'<P>'#13#10 +
'<#RECONCILEGRID>'#13#10 +
'</FORM>'#13#10 +
'<P>'#13#10 +
'<FORM>'#13#10 +
'<H3> %9:s </H3>'#13#10 +
'<input type=radio name="action" value="Cancel" onclick=''if(self.grid1!=null)grid1.cancel();''/> %2:s'#13#10 +
'<input type=radio name="action" value="Correct" onclick=''if(self.grid1!=null)grid1.correct();''/> %3:s'#13#10 +
'<input type=radio name="action" value="Merge" onclick=''if(self.grid1!=null)grid1.merge();''/> %4:s'#13#10 +
'<P>'#13#10 +
'<input type=button value="%5:s" onclick=''if(self.grid1!=null)grid1.up();'' />'#13#10 +
'<input type=button value="%6:s" onclick=''if(self.grid1!=null)grid1.down();'' />'#13#10 +
'<input type=button value="%7:s" onclick=''if(self.grid1!=null)grid1.post();''/>'#13#10 +
'<P>'#13#10 +
'<input type=button value="%8:s" onclick=''if(self.grid1!=null)grid1.Reapply(Submitfrm1, Submitfrm1.postdelta);''/>'#13#10 +
'</FORM>'#13#10 +
'<#FORMS><#SCRIPT>'#13#10 +
'</BODY>'#13#10 +
'</HTML>'#13#10;
constructor TReconcilePageProducer.Create(AOwner: TComponent);
begin
inherited;
FReconcileGrid := TReconcileGrid.Create(Self);
HTMLDoc.Text := Format(sDefaultHTMLDoc,
[sErrorMessage, sOn, sCancel, sCorrect, sMerge,
sPrevRow, sNextRow, sPostNext, sReapply, sReconcileAction]);
end;
destructor TReconcilePageProducer.Destroy;
begin
inherited;
FReconcileGrid.Free;
end;
procedure TReconcilePageProducer.GetXMLInfo(
var XMLBrokerName, XMLErrors, XMLDelta: string;
XMLOptions: TXMLOptions);
begin
XMLErrors := '';
XMLDelta := '';
if Assigned(FXMLBroker) then
begin
XMLErrors := FormatXML(FXMLBroker.GetErrors, XMLOptions);
if Assigned(Dispatcher) and Assigned(Dispatcher.Request) then
XMLDelta := FormatXML(FXMLBroker.GetDelta(Dispatcher.Request),
XMLOptions);
XMLBrokerName := FXMLBroker.Name;
end
else
XMLBrokerName := sDefaultXMLBrokerName;
end;
function TReconcilePageProducer.DeclareXMLDocuments: string;
function DeclareXMLDocument(const XMLBrokerName, XmlVarName, DocVarName,
TagName, XMLData: string): string;
begin
Result := '';
Result := Format('%svar %s = '#13#10, [Result, XMLVarName]);
if (csDesigning in ComponentState) or (XMLData = '') then
Result := Format('%s<#%s %s=%s %s>;'#13#10,
[Result, TagName, sXMLBroker, XMLBrokerName, sQuoteXML])
else
Result := Format('%s%s;'#13#10, [Result, XMLData]);;
Result := Format('%svar %s = new Document(%s);'#13#10,
[Result, DocVarName, XMLVarName]);
end;
var
XMLBrokerName: string;
XMLErrors, XMLDelta: string;
begin
GetXMLInfo(XMLBrokerName, XMLErrors, XMLDelta, [xoQuote]);
Result := Result +
DeclareXMLDocument(XMLBrokerName, sErrXMLVarName, sErrDocVarName, sErrorPacketTag,
XMLErrors );
Result := Result +
DeclareXMLDocument(XMLBrokerName, sDeltaXMLVarName, sDeltaDocVarName, sDeltaPacketTag,
XMLDelta);
end;
function TReconcilePageProducer.DeclareXMLIslands: string;
function DeclareXMLIsland(const XMLBrokerName, DocVarName, TagName, XMLData: string): string;
begin
Result := '';
Result := Format('%s<XML ID=%s>'#13#10, [Result, DocVarName]);
if (csDesigning in ComponentState) or (XMLData = '') then
Result := Format('%s<#%s %s=%s>'#13#10,
[Result, TagName, sXMLBroker, XMLBrokerName])
else
Result := Format('%s%s', [Result, XMLData]);
Result := Result + #13#10'</XML>'#13#10;
end;
var
XMLBrokerName: string;
XMLErrors, XMLDelta: string;
begin
GetXMLInfo(XMLBrokerName, XMLErrors, XMLDelta, []);
Result :=
DeclareXMLIsland(XMLBrokerName, sErrDocVarName, sErrorPacketTag,
XMLErrors);
Result := Result +
DeclareXMLIsland(XMLBrokerName, sDeltaDocVarName, sDeltaPacketTag,
XMLDelta);
end;
function TReconcilePageProducer.DeclareRowSets: string;
begin
Result := Format(
'var rowsetErr = new xmlRowSet(%0:s, null, null);'#13#10 + // do not localize
'var rowsetDelta = new xmlRowSet(%1:s, null, null);'#13#10 +
'var frm1 = document.forms[''FORM1''];'#13#10 +
'var grid1 = new ErrReconcile(rowsetDelta,rowsetErr,'#13#10 +
' new Array(frm1.col_FieldName,frm1.col_Modified,frm1.col_Conflicting,frm1.col_Original),'#13#10 +
' new Array("FieldName","Modified","Conflicting","Original"),'#13#10 +
' frm1.ErrMessage,frm1.ErrAction);'#13#10 +
' grid1.setFocus(0,1);'#13#10,
[sErrDocVarName, sDeltaDocVarName]);
end;
const
sSubmitFormName = 'Submitfrm1'; // Do not localize
procedure TReconcilePageProducer.AddScriptComponents;
procedure DeclareSubmitForm;
const
Indent1 = ' ';
var
PathInfo: string;
Redirect: string;
HTMLSubmitFormName: string;
SubmitFormVarName: string;
XMLBrokerName: string;
Forms: string;
begin
Forms := '';
HTMLSubmitFormName := sSubmitFormName;
SubmitFormVarName := sSubmitFormName;
if Assigned(FXMLBroker) then
begin
PathInfo := FXMLBroker.WebDispatch.PathInfo;
XMLBrokerName := FXMLBroker.Name;
end
else
begin
PathInfo := '';
XMLBrokerName := sDefaultXMLBrokerName;
end;
if Copy(PathInfo, 1, 1) = '/' then
Delete(PathInfo, 1, 1);
if Assigned(Dispatcher) and Assigned(Dispatcher.Request) then
PathInfo := Dispatcher.Request.ScriptName + '/' + PathInfo;
Forms := Forms +
Format('<FORM NAME=%0:s ACTION="%1:s" METHOD="POST">'#13#10,
[HTMLSubmitFormName, PathInfo]);
Forms := Forms +
Format('%0:s<INPUT TYPE=HIDDEN NAME="%1:s" VALUE="%2:s">'#13#10,
[Indent1, sXMLBroker, XMLBrokerName]);
Forms := Forms +
Format('%0:s<INPUT TYPE=HIDDEN NAME="%1:s">'#13#10,
[Indent1, SPostDelta]);
Forms := Forms +
Format('%0:s<INPUT TYPE=HIDDEN NAME="%1:s" VALUE="%2:s">'#13#10,
[Indent1, sProducer, Self.Name]);
if (Dispatcher <> nil) and (Dispatcher.Request <> nil) then
begin
Redirect := Dispatcher.Request.ContentFields.Values[SRedirect];
Forms := Forms +
Format('%0:s<INPUT TYPE=HIDDEN NAME="%1:s" VALUE="%2:s">'#13#10,
[Indent1, sRedirect, Redirect]);
end;
Forms := Forms + '</FORM>'#13#10;
ScriptManager.GetAddElementsIntf.AddHTMLBlock(HTMLSubmitFormName, Forms);
ScriptManager.GetAddElementsIntf.AddVar(SubmitFormVarName,
Format('var %0:s = document.forms[''%1:s''];'#13#10,
[SubmitFormVarName, HTMLSubmitFormName]));
end;
begin
inherited;
DeclareSubmitForm;
end;
procedure TReconcilePageProducer.SetReconcileGrid(
const Value: TReconcileGrid);
begin
FReconcileGrid.Assign(Value);
end;
{ TReconcileGrid }
constructor TReconcileGrid.Create(AOwner: TComponent);
begin
inherited Create;
FDisplayRows := 4;
FTableAttributes := TGridAttributes.Create(AOwner);
FHeadingAttributes := TGridRowAttributes.Create(AOwner);
FRowAttributes := TGridRowAttributes.Create(AOwner);
FTableAttributes.Border := 1;
FFieldNameColumn := TFieldNameColumn.Create(AOwner);
FModifiedColumn := TModifiedColumn.Create(AOwner);
FOriginalColumn := TOriginalColumn.Create(AOwner);
FConflictingColumn := TConflictingColumn.Create(AOwner);
end;
destructor TReconcileGrid.Destroy;
var
I: Integer;
begin
inherited;
FTableAttributes.Free;
FHeadingAttributes.Free;
FRowAttributes.Free;
for I := 0 to ColumnCount - 1 do
Column[I].Free;
end;
procedure TReconcileGrid.AssignTo(Dest: TPersistent);
var
I: Integer;
begin
if Dest is TReconcileGrid then
with TReconcileGrid(Dest) do
begin
FDisplayRows := Self.FDisplayRows;
FTableAttributes.Assign(Self.FTableAttributes);
FHeadingAttributes.Assign(Self.FHeadingAttributes);
FRowAttributes.Assign(Self.FRowAttributes);
for I := 0 to ColumnCount do
Column[I].Assign(Self.Column[I]);
end else inherited AssignTo(Dest);
end;
function TReconcileGrid.FormatTable(Layout: TLayoutWebContent;
Options: TWebContentOptions): string;
function TableHeader: string;
var
Attribs: string;
begin
AddStringAttrib(Attribs, 'NAME', HTMLTableName);
with TableAttributes do
begin
Attribs := Attribs + HTMLAlign[Align];
AddIntAttrib(Attribs, 'CELLSPACING', CellSpacing);
AddIntAttrib(Attribs, 'CELLPADDING', CellPadding);
AddIntAttrib(Attribs, 'BORDER', Border);
AddStringAttrib(Attribs, 'BGCOLOR', BgColor);
AddQuotedAttrib(Attribs, 'STYLE', Style);
AddQuotedAttrib(Attribs, 'CLASS', StyleRule);
AddCustomAttrib(Attribs, Custom);
end;
Result := Format(#13#10'<TABLE%s>', [Attribs]);
end;
function RowHeader(HeadingAttributes: TGridRowAttributes): string;
var
Attribs: string;
begin
with HeadingAttributes do
begin
Attribs := Attribs + HTMLAlign[Align];
Attribs := Attribs + HTMLVAlign[VAlign];
AddQuotedAttrib(Attribs, 'BGCOLOR', BgColor);
AddQuotedAttrib(Attribs, 'STYLE', Style);
AddQuotedAttrib(Attribs, 'CLASS', StyleRule);
AddCustomAttrib(Attribs, Custom);
end;
Result := Format('<TR%s>', [Attribs]);
end;
function FormatColumn(AColumn: TReconcileColumn; var OneRow: string): string;
var
Attribs: string;
begin
Result := '';
Attribs := '';
AddQuotedAttrib(Attribs, 'STYLE', AColumn.CaptionAttributes.Style);
AddCustomAttrib(Attribs, AColumn.CaptionAttributes.Custom);
AddQuotedAttrib(Attribs, 'CLASS', AColumn.CaptionAttributes.StyleRule);
Result := Format('%s<TH%s>%s</TH>'#13#10, [Result, Attribs, AColumn.Caption]);
Attribs := '';
AddQuotedAttrib(Attribs, 'STYLE', AColumn.Style);
AddCustomAttrib(Attribs, AColumn.Custom);
AddQuotedAttrib(Attribs, 'CLASS', AColumn.StyleRule);
OneRow := Format('%s<TD%s><DIV>%s</DIV></TD>'#13#10, [OneRow, Attribs,
AColumn.ControlContent(Options)]);
end;
var
I: Integer;
OneRow: string;
RowHeaderStr: string;
begin
Result := TableHeader + RowHeader(HeadingAttributes) + #13#10;
for I := 0 to ColumnCount - 1 do
Result := Result + FormatColumn(Column[I], OneRow);
Result := Result + '</TR>';
RowHeaderStr := RowHeader(RowAttributes);
for I := 0 to DisplayRows - 1 do
Result := Format('%0:s%1:s%2:s</TR>'#13#10, [Result, RowHeaderStr, OneRow]);
Result := Result + '</TABLE>';
end;
function TReconcileGrid.HTMLTableName: string;
begin
Result := Format(ScriptTableName, ['Reconcile']);
end;
procedure TReconcileGrid.SetHeadingAttributes(
const Value: TGridRowAttributes);
begin
FHeadingAttributes.Assign(Value);
end;
procedure TReconcileGrid.SetRowAttributes(const Value: TGridRowAttributes);
begin
FRowAttributes.Assign(Value);
end;
procedure TReconcileGrid.SetTableAttributes(const Value: TGridAttributes);
begin
FTableAttributes.Assign(Value);
end;
function TReconcileGrid.GetColumn(I: Integer): TReconcileColumn;
begin
Result := nil;
case I of
0: Result := FFieldNameColumn;
1: Result := FModifiedColumn;
2: Result := FConflictingColumn;
3: Result := FOriginalColumn;
else
Assert(False, 'Column out of range');
end;
end;
function TReconcileGrid.GetColumnCount: Integer;
begin
Result := 4;
end;
procedure TReconcileGrid.SetConflictingColumn(
const Value: TReconcileColumn);
begin
FConflictingColumn.Assign(Value);
end;
procedure TReconcileGrid.SetFieldNameColumn(const Value: TReconcileColumn);
begin
FFieldNameColumn.Assign(Value);
end;
procedure TReconcileGrid.SetModifiedColumn(const Value: TReconcileColumn);
begin
FModifiedColumn.Assign(Value);
end;
procedure TReconcileGrid.SetOriginalColumn(const Value: TReconcileColumn);
begin
FOriginalColumn.Assign(Value);
end;
{ TReconcileColumn }
procedure TReconcileColumn.AssignTo(Dest: TPersistent);
begin
if Dest is TReconcileColumn then
with TReconcileColumn(Dest) do
begin
FCaption := Self.FCaption;
FCustom := Self.FCustom;
FStyle := Self.FStyle;
FStyleRule := Self.FStyleRule;
FCaptionAttributes.Assign(Self.FCaptionAttributes);
FDisplayWidth := Self.FDisplayWidth;
end else inherited AssignTo(Dest);
end;
function TReconcileColumn.ControlContent(
Options: TWebContentOptions): string;
procedure AddAttributes(var Attrs: string);
begin
AddQuotedAttrib(Attrs, 'NAME', GetHTMLControlName);
AddIntAttrib(Attrs, 'SIZE', DisplayWidth);
AddIntAttrib(Attrs, 'MAXLENGTH', MaxWidth);
AddQuotedAttrib(Attrs, 'STYLE', Style);
AddQuotedAttrib(Attrs, 'CLASS', StyleRule);
AddCustomAttrib(Attrs, Custom);
end;
function EventContent(Options: TWebContentOptions): string;
begin
Result := FEvents;
end;
var
Attrs: string;
Events: string;
begin
AddAttributes(Attrs);
if (not (coNoScript in Options.Flags)) then
Events := EventContent(Options);
Result := Format('<INPUT TYPE=TEXT %0:s %1:s>', [Attrs, Events]);
end;
constructor TReconcileColumn.Create(AOwner: TComponent);
begin
inherited Create;
FCaptionAttributes := TCaptionAttributes.Create(AOwner);
FMaxWidth := -1;
end;
destructor TReconcileColumn.Destroy;
begin
inherited;
FCaptionAttributes.Free;
end;
function TReconcileColumn.GetHTMLControlName: string;
begin
Result := FName;
end;
procedure TReconcileColumn.SetCaptionAttributes(
const Value: TCaptionAttributes);
begin
FCaptionAttributes.Assign(Value);
end;
{ TFieldNameColumn }
constructor TFieldNameColumn.Create(AOwner: TComponent);
begin
inherited;
FName := 'col_FieldName';
FEvents := 'onfocus = "blur();"';
FDisplayWidth := 18;
FCaption := sFieldNameCaption;
end;
{ TModifiedColumn }
constructor TModifiedColumn.Create(AOwner: TComponent);
begin
inherited;
FName := 'col_Modified';
FEvents := 'onfocus = "grid1.xfocus(this);"';
FDisplayWidth := 24;
FCaption := sModifiedCaption;
end;
{ TConflictingColumn }
constructor TConflictingColumn.Create(AOwner: TComponent);
begin
inherited;
FName := 'col_Conflicting';
FEvents := 'onfocus = "blur();"';
FDisplayWidth := 24;
FCaption := sConflictingCaption;
end;
{ TOriginalColumn }
constructor TOriginalColumn.Create(AOwner: TComponent);
begin
inherited;
FName := 'col_Original';
FEvents := 'onfocus = "blur();"';
FDisplayWidth := 24;
FCaption := sOriginalCaption;
end;
end.
|
{ *********************************************************************** }
{ }
{ Delphi Runtime Library }
{ }
{ Copyright (c) 1996-2001 Borland Software Corporation }
{ }
{ *********************************************************************** }
{*******************************************************}
{ OLE dialogs interface unit }
{*******************************************************}
unit OleDlg;
{$WEAKPACKAGEUNIT}
interface
(*$HPPEMIT '' *)
(*$HPPEMIT '#include <oledlg.h>' *)
(*$HPPEMIT '' *)
uses Windows, CommCtrl, ActiveX;
const
{ Help Button Identifier }
{$EXTERNALSYM IDC_OLEUIHELP}
IDC_OLEUIHELP = 99;
{ Insert Object Dialog identifiers }
{$EXTERNALSYM IDC_IO_CREATENEW}
IDC_IO_CREATENEW = 2100;
{$EXTERNALSYM IDC_IO_CREATEFROMFILE}
IDC_IO_CREATEFROMFILE = 2101;
{$EXTERNALSYM IDC_IO_LINKFILE}
IDC_IO_LINKFILE = 2102;
{$EXTERNALSYM IDC_IO_OBJECTTYPELIST}
IDC_IO_OBJECTTYPELIST = 2103;
{$EXTERNALSYM IDC_IO_DISPLAYASICON}
IDC_IO_DISPLAYASICON = 2104;
{$EXTERNALSYM IDC_IO_CHANGEICON}
IDC_IO_CHANGEICON = 2105;
{$EXTERNALSYM IDC_IO_FILE}
IDC_IO_FILE = 2106;
{$EXTERNALSYM IDC_IO_FILEDISPLAY}
IDC_IO_FILEDISPLAY = 2107;
{$EXTERNALSYM IDC_IO_RESULTIMAGE}
IDC_IO_RESULTIMAGE = 2108;
{$EXTERNALSYM IDC_IO_RESULTTEXT}
IDC_IO_RESULTTEXT = 2109;
{$EXTERNALSYM IDC_IO_ICONDISPLAY}
IDC_IO_ICONDISPLAY = 2110;
{$EXTERNALSYM IDC_IO_OBJECTTYPETEXT}
IDC_IO_OBJECTTYPETEXT = 2111;
{$EXTERNALSYM IDC_IO_FILETEXT}
IDC_IO_FILETEXT = 2112;
{$EXTERNALSYM IDC_IO_FILETYPE}
IDC_IO_FILETYPE = 2113;
{$EXTERNALSYM IDC_IO_INSERTCONTROL}
IDC_IO_INSERTCONTROL = 2114;
{$EXTERNALSYM IDC_IO_ADDCONTROL}
IDC_IO_ADDCONTROL = 2115;
{$EXTERNALSYM IDC_IO_CONTROLTYPELIST}
IDC_IO_CONTROLTYPELIST = 2116;
{ Paste Special Dialog identifiers }
{$EXTERNALSYM IDC_PS_PASTE}
IDC_PS_PASTE = 500;
{$EXTERNALSYM IDC_PS_PASTELINK}
IDC_PS_PASTELINK = 501;
{$EXTERNALSYM IDC_PS_SOURCETEXT}
IDC_PS_SOURCETEXT = 502;
{$EXTERNALSYM IDC_PS_PASTELIST}
IDC_PS_PASTELIST = 503;
{$EXTERNALSYM IDC_PS_PASTELINKLIST}
IDC_PS_PASTELINKLIST = 504;
{$EXTERNALSYM IDC_PS_DISPLAYLIST}
IDC_PS_DISPLAYLIST = 505;
{$EXTERNALSYM IDC_PS_DISPLAYASICON}
IDC_PS_DISPLAYASICON = 506;
{$EXTERNALSYM IDC_PS_ICONDISPLAY}
IDC_PS_ICONDISPLAY = 507;
{$EXTERNALSYM IDC_PS_CHANGEICON}
IDC_PS_CHANGEICON = 508;
{$EXTERNALSYM IDC_PS_RESULTIMAGE}
IDC_PS_RESULTIMAGE = 509;
{$EXTERNALSYM IDC_PS_RESULTTEXT}
IDC_PS_RESULTTEXT = 510;
{ Change Icon Dialog identifiers }
{$EXTERNALSYM IDC_CI_GROUP}
IDC_CI_GROUP = 120;
{$EXTERNALSYM IDC_CI_CURRENT}
IDC_CI_CURRENT = 121;
{$EXTERNALSYM IDC_CI_CURRENTICON}
IDC_CI_CURRENTICON = 122;
{$EXTERNALSYM IDC_CI_DEFAULT}
IDC_CI_DEFAULT = 123;
{$EXTERNALSYM IDC_CI_DEFAULTICON}
IDC_CI_DEFAULTICON = 124;
{$EXTERNALSYM IDC_CI_FROMFILE}
IDC_CI_FROMFILE = 125;
{$EXTERNALSYM IDC_CI_FROMFILEEDIT}
IDC_CI_FROMFILEEDIT = 126;
{$EXTERNALSYM IDC_CI_ICONLIST}
IDC_CI_ICONLIST = 127;
{$EXTERNALSYM IDC_CI_LABEL}
IDC_CI_LABEL = 128;
{$EXTERNALSYM IDC_CI_LABELEDIT}
IDC_CI_LABELEDIT = 129;
{$EXTERNALSYM IDC_CI_BROWSE}
IDC_CI_BROWSE = 130;
{$EXTERNALSYM IDC_CI_ICONDISPLAY}
IDC_CI_ICONDISPLAY = 131;
{ Convert Dialog identifiers }
{$EXTERNALSYM IDC_CV_OBJECTTYPE}
IDC_CV_OBJECTTYPE = 150;
{$EXTERNALSYM IDC_CV_DISPLAYASICON}
IDC_CV_DISPLAYASICON = 152;
{$EXTERNALSYM IDC_CV_CHANGEICON}
IDC_CV_CHANGEICON = 153;
{$EXTERNALSYM IDC_CV_ACTIVATELIST}
IDC_CV_ACTIVATELIST = 154;
{$EXTERNALSYM IDC_CV_CONVERTTO}
IDC_CV_CONVERTTO = 155;
{$EXTERNALSYM IDC_CV_ACTIVATEAS}
IDC_CV_ACTIVATEAS = 156;
{$EXTERNALSYM IDC_CV_RESULTTEXT}
IDC_CV_RESULTTEXT = 157;
{$EXTERNALSYM IDC_CV_CONVERTLIST}
IDC_CV_CONVERTLIST = 158;
{$EXTERNALSYM IDC_CV_ICONDISPLAY}
IDC_CV_ICONDISPLAY = 165;
{ Edit Links Dialog identifiers }
{$EXTERNALSYM IDC_EL_CHANGESOURCE}
IDC_EL_CHANGESOURCE = 201;
{$EXTERNALSYM IDC_EL_AUTOMATIC}
IDC_EL_AUTOMATIC = 202;
{$EXTERNALSYM IDC_EL_CANCELLINK}
IDC_EL_CANCELLINK = 209;
{$EXTERNALSYM IDC_EL_UPDATENOW}
IDC_EL_UPDATENOW = 210;
{$EXTERNALSYM IDC_EL_OPENSOURCE}
IDC_EL_OPENSOURCE = 211;
{$EXTERNALSYM IDC_EL_MANUAL}
IDC_EL_MANUAL = 212;
{$EXTERNALSYM IDC_EL_LINKSOURCE}
IDC_EL_LINKSOURCE = 216;
{$EXTERNALSYM IDC_EL_LINKTYPE}
IDC_EL_LINKTYPE = 217;
{$EXTERNALSYM IDC_EL_LINKSLISTBOX}
IDC_EL_LINKSLISTBOX = 206;
{$EXTERNALSYM IDC_EL_COL1}
IDC_EL_COL1 = 220;
{$EXTERNALSYM IDC_EL_COL2}
IDC_EL_COL2 = 221;
{$EXTERNALSYM IDC_EL_COL3}
IDC_EL_COL3 = 222;
{ Busy dialog identifiers }
{$EXTERNALSYM IDC_BZ_RETRY}
IDC_BZ_RETRY = 600;
{$EXTERNALSYM IDC_BZ_ICON}
IDC_BZ_ICON = 601;
{$EXTERNALSYM IDC_BZ_MESSAGE1}
IDC_BZ_MESSAGE1 = 602;
{$EXTERNALSYM IDC_BZ_SWITCHTO}
IDC_BZ_SWITCHTO = 604;
{ Update Links dialog identifiers }
{$EXTERNALSYM IDC_UL_METER}
IDC_UL_METER = 1029;
{$EXTERNALSYM IDC_UL_STOP}
IDC_UL_STOP = 1030;
{$EXTERNALSYM IDC_UL_PERCENT}
IDC_UL_PERCENT = 1031;
{$EXTERNALSYM IDC_UL_PROGRESS}
IDC_UL_PROGRESS = 1032;
{ User Prompt dialog identifiers }
{$EXTERNALSYM IDC_PU_LINKS}
IDC_PU_LINKS = 900;
{$EXTERNALSYM IDC_PU_TEXT}
IDC_PU_TEXT = 901;
{$EXTERNALSYM IDC_PU_CONVERT}
IDC_PU_CONVERT = 902;
{$EXTERNALSYM IDC_PU_ICON}
IDC_PU_ICON = 908;
{ General Properties identifiers }
{$EXTERNALSYM IDC_GP_OBJECTNAME}
IDC_GP_OBJECTNAME = 1009;
{$EXTERNALSYM IDC_GP_OBJECTTYPE}
IDC_GP_OBJECTTYPE = 1010;
{$EXTERNALSYM IDC_GP_OBJECTSIZE}
IDC_GP_OBJECTSIZE = 1011;
{$EXTERNALSYM IDC_GP_CONVERT}
IDC_GP_CONVERT = 1013;
{$EXTERNALSYM IDC_GP_OBJECTICON}
IDC_GP_OBJECTICON = 1014;
{$EXTERNALSYM IDC_GP_OBJECTLOCATION}
IDC_GP_OBJECTLOCATION = 1022;
{ View Properties identifiers }
{$EXTERNALSYM IDC_VP_PERCENT}
IDC_VP_PERCENT = 1000;
{$EXTERNALSYM IDC_VP_CHANGEICON}
IDC_VP_CHANGEICON = 1001;
{$EXTERNALSYM IDC_VP_EDITABLE}
IDC_VP_EDITABLE = 1002;
{$EXTERNALSYM IDC_VP_ASICON}
IDC_VP_ASICON = 1003;
{$EXTERNALSYM IDC_VP_RELATIVE}
IDC_VP_RELATIVE = 1005;
{$EXTERNALSYM IDC_VP_SPIN}
IDC_VP_SPIN = 1006;
{$EXTERNALSYM IDC_VP_SCALETXT}
IDC_VP_SCALETXT = 1034;
{$EXTERNALSYM IDC_VP_ICONDISPLAY}
IDC_VP_ICONDISPLAY = 1021;
{$EXTERNALSYM IDC_VP_RESULTIMAGE}
IDC_VP_RESULTIMAGE = 1033;
{ Link Properties identifiers }
{$EXTERNALSYM IDC_LP_OPENSOURCE}
IDC_LP_OPENSOURCE = 1006;
{$EXTERNALSYM IDC_LP_UPDATENOW}
IDC_LP_UPDATENOW = 1007;
{$EXTERNALSYM IDC_LP_BREAKLINK}
IDC_LP_BREAKLINK = 1008;
{$EXTERNALSYM IDC_LP_LINKSOURCE}
IDC_LP_LINKSOURCE = 1012;
{$EXTERNALSYM IDC_LP_CHANGESOURCE}
IDC_LP_CHANGESOURCE = 1015;
{$EXTERNALSYM IDC_LP_AUTOMATIC}
IDC_LP_AUTOMATIC = 1016;
{$EXTERNALSYM IDC_LP_MANUAL}
IDC_LP_MANUAL = 1017;
{$EXTERNALSYM IDC_LP_DATE}
IDC_LP_DATE = 1018;
{$EXTERNALSYM IDC_LP_TIME}
IDC_LP_TIME = 1019;
{ Dialog Identifiers as passed in Help messages to identify the source }
{$EXTERNALSYM IDD_INSERTOBJECT}
IDD_INSERTOBJECT = 1000;
{$EXTERNALSYM IDD_CHANGEICON}
IDD_CHANGEICON = 1001;
{$EXTERNALSYM IDD_CONVERT}
IDD_CONVERT = 1002;
{$EXTERNALSYM IDD_PASTESPECIAL}
IDD_PASTESPECIAL = 1003;
{$EXTERNALSYM IDD_EDITLINKS}
IDD_EDITLINKS = 1004;
{$EXTERNALSYM IDD_BUSY}
IDD_BUSY = 1006;
{$EXTERNALSYM IDD_UPDATELINKS}
IDD_UPDATELINKS = 1007;
{$EXTERNALSYM IDD_CHANGESOURCE}
IDD_CHANGESOURCE = 1009;
{$EXTERNALSYM IDD_INSERTFILEBROWSE}
IDD_INSERTFILEBROWSE = 1010;
{$EXTERNALSYM IDD_CHANGEICONBROWSE}
IDD_CHANGEICONBROWSE = 1011;
{$EXTERNALSYM IDD_CONVERTONLY}
IDD_CONVERTONLY = 1012;
{$EXTERNALSYM IDD_CHANGESOURCE4}
IDD_CHANGESOURCE4 = 1013;
{$EXTERNALSYM IDD_GNRLPROPS}
IDD_GNRLPROPS = 1100;
{$EXTERNALSYM IDD_VIEWPROPS}
IDD_VIEWPROPS = 1101;
{$EXTERNALSYM IDD_LINKPROPS}
IDD_LINKPROPS = 1102;
{ The following Dialogs are message dialogs used by OleUIPromptUser API }
{$EXTERNALSYM IDD_CANNOTUPDATELINK}
IDD_CANNOTUPDATELINK = 1008;
{$EXTERNALSYM IDD_LINKSOURCEUNAVAILABLE}
IDD_LINKSOURCEUNAVAILABLE = 1020;
{$EXTERNALSYM IDD_SERVERNOTFOUND}
IDD_SERVERNOTFOUND = 1023;
{$EXTERNALSYM IDD_OUTOFMEMORY}
IDD_OUTOFMEMORY = 1024;
{$EXTERNALSYM IDD_SERVERNOTREG}
IDD_SERVERNOTREG = 1021;
{$EXTERNALSYM IDD_LINKTYPECHANGED}
IDD_LINKTYPECHANGED = 1022;
{ Delimeter used to separate ItemMoniker pieces of a composite moniker }
{$EXTERNALSYM OLESTDDELIM}
OLESTDDELIM = '\';
{ Strings for registered messages }
{$EXTERNALSYM SZOLEUI_MSG_HELP}
SZOLEUI_MSG_HELP = 'OLEUI_MSG_HELP';
{$EXTERNALSYM SZOLEUI_MSG_ENDDIALOG}
SZOLEUI_MSG_ENDDIALOG = 'OLEUI_MSG_ENDDIALOG';
{$EXTERNALSYM SZOLEUI_MSG_BROWSE}
SZOLEUI_MSG_BROWSE = 'OLEUI_MSG_BROWSE';
{$EXTERNALSYM SZOLEUI_MSG_CHANGEICON}
SZOLEUI_MSG_CHANGEICON = 'OLEUI_MSG_CHANGEICON';
{$EXTERNALSYM SZOLEUI_MSG_CLOSEBUSYDIALOG}
SZOLEUI_MSG_CLOSEBUSYDIALOG = 'OLEUI_MSG_CLOSEBUSYDIALOG';
{$EXTERNALSYM SZOLEUI_MSG_CONVERT}
SZOLEUI_MSG_CONVERT = 'OLEUI_MSG_CONVERT';
{$EXTERNALSYM SZOLEUI_MSG_CHANGESOURCE}
SZOLEUI_MSG_CHANGESOURCE = 'OLEUI_MSG_CHANGESOURCE';
{$EXTERNALSYM SZOLEUI_MSG_ADDCONTROL}
SZOLEUI_MSG_ADDCONTROL = 'OLEUI_MSG_ADDCONTROL';
{$EXTERNALSYM SZOLEUI_MSG_BROWSE_OFN}
SZOLEUI_MSG_BROWSE_OFN = 'OLEUI_MSG_BROWSE_OFN';
{ Identifiers for SZOLEUI_MSG_BROWSE_OFN (in wParam) }
{$EXTERNALSYM ID_BROWSE_CHANGEICON}
ID_BROWSE_CHANGEICON = 1;
{$EXTERNALSYM ID_BROWSE_INSERTFILE}
ID_BROWSE_INSERTFILE = 2;
{$EXTERNALSYM ID_BROWSE_ADDCONTROL}
ID_BROWSE_ADDCONTROL = 3;
{$EXTERNALSYM ID_BROWSE_CHANGESOURCE}
ID_BROWSE_CHANGESOURCE = 4;
{ Standard success/error definitions }
{$EXTERNALSYM OLEUI_FALSE}
OLEUI_FALSE = 0;
{$EXTERNALSYM OLEUI_SUCCESS}
OLEUI_SUCCESS = 1; { No error, same as OLEUI_OK }
{$EXTERNALSYM OLEUI_OK}
OLEUI_OK = 1; { OK button pressed }
{$EXTERNALSYM OLEUI_CANCEL}
OLEUI_CANCEL = 2; { Cancel button pressed }
{$EXTERNALSYM OLEUI_ERR_STANDARDMIN}
OLEUI_ERR_STANDARDMIN = 100;
{$EXTERNALSYM OLEUI_ERR_STRUCTURENULL}
OLEUI_ERR_STRUCTURENULL = 101; { Standard field validation }
{$EXTERNALSYM OLEUI_ERR_STRUCTUREINVALID}
OLEUI_ERR_STRUCTUREINVALID = 102;
{$EXTERNALSYM OLEUI_ERR_CBSTRUCTINCORRECT}
OLEUI_ERR_CBSTRUCTINCORRECT = 103;
{$EXTERNALSYM OLEUI_ERR_HWNDOWNERINVALID}
OLEUI_ERR_HWNDOWNERINVALID = 104;
{$EXTERNALSYM OLEUI_ERR_LPSZCAPTIONINVALID}
OLEUI_ERR_LPSZCAPTIONINVALID = 105;
{$EXTERNALSYM OLEUI_ERR_LPFNHOOKINVALID}
OLEUI_ERR_LPFNHOOKINVALID = 106;
{$EXTERNALSYM OLEUI_ERR_HINSTANCEINVALID}
OLEUI_ERR_HINSTANCEINVALID = 107;
{$EXTERNALSYM OLEUI_ERR_LPSZTEMPLATEINVALID}
OLEUI_ERR_LPSZTEMPLATEINVALID = 108;
{$EXTERNALSYM OLEUI_ERR_HRESOURCEINVALID}
OLEUI_ERR_HRESOURCEINVALID = 109;
{$EXTERNALSYM OLEUI_ERR_FINDTEMPLATEFAILURE}
OLEUI_ERR_FINDTEMPLATEFAILURE = 110; { Initialization errors }
{$EXTERNALSYM OLEUI_ERR_LOADTEMPLATEFAILURE}
OLEUI_ERR_LOADTEMPLATEFAILURE = 111;
{$EXTERNALSYM OLEUI_ERR_DIALOGFAILURE}
OLEUI_ERR_DIALOGFAILURE = 112;
{$EXTERNALSYM OLEUI_ERR_LOCALMEMALLOC}
OLEUI_ERR_LOCALMEMALLOC = 113;
{$EXTERNALSYM OLEUI_ERR_GLOBALMEMALLOC}
OLEUI_ERR_GLOBALMEMALLOC = 114;
{$EXTERNALSYM OLEUI_ERR_LOADSTRING}
OLEUI_ERR_LOADSTRING = 115;
{$EXTERNALSYM OLEUI_ERR_OLEMEMALLOC}
OLEUI_ERR_OLEMEMALLOC = 116;
{$EXTERNALSYM OLEUI_ERR_STANDARDMAX}
OLEUI_ERR_STANDARDMAX = 117; { Start here for specific errors }
{ Hook type used in all structures }
type
TFNOleUIHook = function(Wnd: HWnd; Msg, WParam, LParam: Longint): Longint stdcall;
{ Miscellaneous utility functions }
function OleUIAddVerbMenu(oleObj: IOleObject; pszShortType: PChar;
menu: HMenu; uPos: Integer; uIDVerbMin: Integer; uIDVerbMax: Integer;
bAddConvert: BOOL; idConvert: Integer; var outMenu: HMenu): BOOL; stdcall;
{$EXTERNALSYM OleUIAddVerbMenu}
{ **** Insert Object dialog **** }
{ Insert object dialog structure }
type
POleUIInsertObject = ^TOleUIInsertObject;
{$EXTERNALSYM tagOLEUIINSERTOBJECTA}
tagOLEUIINSERTOBJECTA = record
cbStruct: Longint; { Structure Size }
dwFlags: Longint; { IN-OUT: Flags }
hWndOwner: HWnd; { Owning window }
lpszCaption: PChar; { Dialog caption bar contents }
lpfnHook: TFNOleUIHook; { Hook callback }
lCustData: Longint; { Custom data to pass to hook }
hInstance: THandle; { Instance for customized template name }
lpszTemplate: PChar; { Customized template name }
hResource: HRsrc; { Customized template handle }
clsid: TCLSID; { OUT: Return space for class ID }
lpszFile: PChar; { IN-OUT: Filename for inserts or links }
cchFile: Integer; { IN: Size of lpszFile buffer: MAX_PATH }
cClsidExclude: Integer; { IN: CLSIDs in lpClsidExclude }
lpClsidExclude: PCLSID; { IN: List of CLSIDs to exclude from listing }
iid: TIID; { IN: Requested interface on creation }
oleRender: Longint; { IN: Rendering option }
lpFormatEtc: PFormatEtc; { IN: Desired format }
lpIOleClientSite: IOleClientSite; { IN: Site to be use for the object }
lpIStorage: IStorage; { IN: Storage used for the object }
ppvObj: Pointer; { OUT: Where the object is returned }
sc: HResult; { OUT: Result of creation calls }
hMetaPict: HGlobal; { OUT: metafile aspect (METAFILEPICT) }
end;
TOleUIInsertObject = tagOLEUIINSERTOBJECTA;
{ Insert object dialog function }
function OleUIInsertObject(var Info: TOleUIInsertObject): Integer; stdcall;
{$EXTERNALSYM OleUIInsertObject}
{ Insert Object flags }
const
{$EXTERNALSYM IOF_SHOWHELP}
IOF_SHOWHELP = $00000001;
{$EXTERNALSYM IOF_SELECTCREATENEW}
IOF_SELECTCREATENEW = $00000002;
{$EXTERNALSYM IOF_SELECTCREATEFROMFILE}
IOF_SELECTCREATEFROMFILE = $00000004;
{$EXTERNALSYM IOF_CHECKLINK}
IOF_CHECKLINK = $00000008;
{$EXTERNALSYM IOF_CHECKDISPLAYASICON}
IOF_CHECKDISPLAYASICON = $00000010;
{$EXTERNALSYM IOF_CREATENEWOBJECT}
IOF_CREATENEWOBJECT = $00000020;
{$EXTERNALSYM IOF_CREATEFILEOBJECT}
IOF_CREATEFILEOBJECT = $00000040;
{$EXTERNALSYM IOF_CREATELINKOBJECT}
IOF_CREATELINKOBJECT = $00000080;
{$EXTERNALSYM IOF_DISABLELINK}
IOF_DISABLELINK = $00000100;
{$EXTERNALSYM IOF_VERIFYSERVERSEXIST}
IOF_VERIFYSERVERSEXIST = $00000200;
{$EXTERNALSYM IOF_DISABLEDISPLAYASICON}
IOF_DISABLEDISPLAYASICON = $00000400;
{$EXTERNALSYM IOF_HIDECHANGEICON}
IOF_HIDECHANGEICON = $00000800;
{$EXTERNALSYM IOF_SHOWINSERTCONTROL}
IOF_SHOWINSERTCONTROL = $00001000;
{$EXTERNALSYM IOF_SELECTCREATECONTROL}
IOF_SELECTCREATECONTROL = $00002000;
{ Insert Object specific error codes }
const
{$EXTERNALSYM OLEUI_IOERR_LPSZFILEINVALID}
OLEUI_IOERR_LPSZFILEINVALID = OLEUI_ERR_STANDARDMAX + 0;
{$EXTERNALSYM OLEUI_IOERR_LPSZLABELINVALID}
OLEUI_IOERR_LPSZLABELINVALID = OLEUI_ERR_STANDARDMAX + 1;
{$EXTERNALSYM OLEUI_IOERR_HICONINVALID}
OLEUI_IOERR_HICONINVALID = OLEUI_ERR_STANDARDMAX + 2;
{$EXTERNALSYM OLEUI_IOERR_LPFORMATETCINVALID}
OLEUI_IOERR_LPFORMATETCINVALID = OLEUI_ERR_STANDARDMAX + 3;
{$EXTERNALSYM OLEUI_IOERR_PPVOBJINVALID}
OLEUI_IOERR_PPVOBJINVALID = OLEUI_ERR_STANDARDMAX + 4;
{$EXTERNALSYM OLEUI_IOERR_LPIOLECLIENTSITEINVALID}
OLEUI_IOERR_LPIOLECLIENTSITEINVALID = OLEUI_ERR_STANDARDMAX + 5;
{$EXTERNALSYM OLEUI_IOERR_LPISTORAGEINVALID}
OLEUI_IOERR_LPISTORAGEINVALID = OLEUI_ERR_STANDARDMAX + 6;
{$EXTERNALSYM OLEUI_IOERR_SCODEHASERROR}
OLEUI_IOERR_SCODEHASERROR = OLEUI_ERR_STANDARDMAX + 7;
{$EXTERNALSYM OLEUI_IOERR_LPCLSIDEXCLUDEINVALID}
OLEUI_IOERR_LPCLSIDEXCLUDEINVALID = OLEUI_ERR_STANDARDMAX + 8;
{$EXTERNALSYM OLEUI_IOERR_CCHFILEINVALID}
OLEUI_IOERR_CCHFILEINVALID = OLEUI_ERR_STANDARDMAX + 9;
{ **** Paste Special dialog **** }
{ The OLEUIPASTE_xxx values are used by the TOleUIPasteEntry structure.
OLEUIPASTE_ENABLEICON: If the container does not specify this flag for
the entry in the TOleUIPasteEntry array passed as input to
OleUIPasteSpecial, the DisplayAsIcon button will be unchecked and
disabled when the the user selects the format that corresponds to
the entry.
OLEUIPASTE_PASTEONLY: Indicates that the entry in the TOleUIPasteEntry
array is valid for pasting only.
OLEUIPASTE_PASTE: Indicates that the entry in the TOleUIPasteEntry array
is valid for pasting. It may also be valid for linking if any of
the following linking flags are specified.
If the entry in the TOleUIPasteEntry array is valid for linking, the
following flags indicate which link types are acceptable by OR'ing
together the appropriate OLEUIPASTE_LINKTYPE<#> values.
These values correspond as follows to the array of link types passed to
OleUIPasteSpecial:
OLEUIPASTE_LINKTYPE1 = arrLinkTypes[0]
OLEUIPASTE_LINKTYPE2 = arrLinkTypes[1]
OLEUIPASTE_LINKTYPE3 = arrLinkTypes[2]
OLEUIPASTE_LINKTYPE4 = arrLinkTypes[3]
OLEUIPASTE_LINKTYPE5 = arrLinkTypes[4]
OLEUIPASTE_LINKTYPE6 = arrLinkTypes[5]
OLEUIPASTE_LINKTYPE7 = arrLinkTypes[6]
OLEUIPASTE_LINKTYPE8 = arrLinkTypes[7]
where,
UINT arrLinkTypes[8] is an array of registered clipboard formats for
linking. A maximium of 8 link types are allowed. }
const
{$EXTERNALSYM OLEUIPASTE_ENABLEICON}
OLEUIPASTE_ENABLEICON = 2048; { enable display as icon }
{$EXTERNALSYM OLEUIPASTE_PASTEONLY}
OLEUIPASTE_PASTEONLY = 0;
{$EXTERNALSYM OLEUIPASTE_PASTE}
OLEUIPASTE_PASTE = 512;
{$EXTERNALSYM OLEUIPASTE_LINKANYTYPE}
OLEUIPASTE_LINKANYTYPE = 1024;
{$EXTERNALSYM OLEUIPASTE_LINKTYPE1}
OLEUIPASTE_LINKTYPE1 = 1;
{$EXTERNALSYM OLEUIPASTE_LINKTYPE2}
OLEUIPASTE_LINKTYPE2 = 2;
{$EXTERNALSYM OLEUIPASTE_LINKTYPE3}
OLEUIPASTE_LINKTYPE3 = 4;
{$EXTERNALSYM OLEUIPASTE_LINKTYPE4}
OLEUIPASTE_LINKTYPE4 = 8;
{$EXTERNALSYM OLEUIPASTE_LINKTYPE5}
OLEUIPASTE_LINKTYPE5 = 16;
{$EXTERNALSYM OLEUIPASTE_LINKTYPE6}
OLEUIPASTE_LINKTYPE6 = 32;
{$EXTERNALSYM OLEUIPASTE_LINKTYPE7}
OLEUIPASTE_LINKTYPE7 = 64;
{$EXTERNALSYM OLEUIPASTE_LINKTYPE8}
OLEUIPASTE_LINKTYPE8 = 128;
{ TOleUIPasteEntry structure
An array of TOleUIPasteEntry entries is specified for the PasteSpecial
dialog box. Each entry includes a TFormatEtc which specifies the
formats that are acceptable, a string that is to represent the format
in the dialog's list box, a string to customize the result text of the
dialog and a set of flags from the OLEUIPASTE_xxx constants. The
flags indicate if the entry is valid for pasting only, linking only or
both pasting and linking. }
type
POleUIPasteEntry = ^TOleUIPasteEntry;
{$EXTERNALSYM tagOLEUIPASTEENTRYA}
tagOLEUIPASTEENTRYA = record
fmtetc: TFormatEtc; { Format that is acceptable }
lpstrFormatName: PChar; { String that represents the format
to the user. %s is replaced by the
full user type name of the object }
lpstrResultText: PChar; { String to customize the result text
of the dialog when the user
selects the format correspoding to
this entry. Any %s in this string
is replaced by the the application
name or FullUserTypeName of the
object on the clipboard }
dwFlags: Longint; { Values from OLEUIPASTE_xxx set }
dwScratchSpace: Longint; { Scratch space used internally }
end;
TOleUIPasteEntry = tagOLEUIPASTEENTRYA;
{$EXTERNALSYM OLEUIPASTEENTRY}
OLEUIPASTEENTRY = tagOLEUIPASTEENTRYA;
{ Maximum number of link types }
const
{$EXTERNALSYM PS_MAXLINKTYPES}
PS_MAXLINKTYPES = 8;
type
POleUIPasteSpecial = ^TOleUIPasteSpecial;
{$EXTERNALSYM tagOLEUIPASTESPECIALA}
tagOLEUIPASTESPECIALA = record
cbStruct: Longint; { Structure Size }
dwFlags: Longint; { IN-OUT: Flags }
hWndOwner: HWnd; { Owning window }
lpszCaption: PChar; { Dialog caption bar contents }
lpfnHook: TFNOleUIHook; { Hook callback }
lCustData: Longint; { Custom data to pass to hook }
hInstance: THandle; { Instance for customized template name }
lpszTemplate: PChar; { Customized template name }
hResource: HRsrc; { Customized template handle }
lpSrcDataObj: IDataObject; { IN-OUT: Source IDataObject on the clipboard }
arrPasteEntries: POleUIPasteEntry; { IN: Array of acceptable formats }
cPasteEntries: Integer; { IN: No. of TOleUIPasteEntry array entries }
arrLinkTypes: PLongint; { IN: List of acceptable link types }
cLinkTypes: Integer; { IN: Number of link types }
cClsidExclude: Integer; { IN: Number of CLSIDs in lpClsidExclude }
lpClsidExclude: PCLSID; { IN: List of CLSIDs to exclude from list }
nSelectedIndex: Integer; { OUT: Index that the user selected }
fLink: BOOL; { OUT: Indicates if Paste or PasteLink }
hMetaPict: HGlobal; { OUT: Handle to Metafile containing icon }
sizel: TSize; { OUT: size of object/link in its source
may be 0,0 if different display
aspect is chosen }
end;
TOleUIPasteSpecial = tagOLEUIPASTESPECIALA;
function OleUIPasteSpecial(var Info: TOleUIPasteSpecial): Integer; stdcall;
{$EXTERNALSYM OleUIPasteSpecial}
{ Paste Special specific flags }
const
{$EXTERNALSYM PSF_SHOWHELP}
PSF_SHOWHELP = $00000001;
{$EXTERNALSYM PSF_SELECTPASTE}
PSF_SELECTPASTE = $00000002;
{$EXTERNALSYM PSF_SELECTPASTELINK}
PSF_SELECTPASTELINK = $00000004;
{$EXTERNALSYM PSF_CHECKDISPLAYASICON}
PSF_CHECKDISPLAYASICON = $00000008;
{$EXTERNALSYM PSF_DISABLEDISPLAYASICON}
PSF_DISABLEDISPLAYASICON = $00000010;
{$EXTERNALSYM PSF_HIDECHANGEICON}
PSF_HIDECHANGEICON = $00000020;
{$EXTERNALSYM PSF_STAYONCLIPBOARDCHANGE}
PSF_STAYONCLIPBOARDCHANGE = $00000040;
{$EXTERNALSYM PSF_NOREFRESHDATAOBJECT}
PSF_NOREFRESHDATAOBJECT = $00000080;
{ Paste Special specific error codes }
const
{$EXTERNALSYM OLEUI_IOERR_SRCDATAOBJECTINVALID}
OLEUI_IOERR_SRCDATAOBJECTINVALID = OLEUI_ERR_STANDARDMAX + 0;
{$EXTERNALSYM OLEUI_IOERR_ARRPASTEENTRIESINVALID}
OLEUI_IOERR_ARRPASTEENTRIESINVALID = OLEUI_ERR_STANDARDMAX + 1;
{$EXTERNALSYM OLEUI_IOERR_ARRLINKTYPESINVALID}
OLEUI_IOERR_ARRLINKTYPESINVALID = OLEUI_ERR_STANDARDMAX + 2;
{$EXTERNALSYM OLEUI_PSERR_CLIPBOARDCHANGED}
OLEUI_PSERR_CLIPBOARDCHANGED = OLEUI_ERR_STANDARDMAX + 3;
{$EXTERNALSYM OLEUI_PSERR_GETCLIPBOARDFAILED}
OLEUI_PSERR_GETCLIPBOARDFAILED = OLEUI_ERR_STANDARDMAX + 4;
{ **** Edit Links dialog **** }
{ IOleUILinkContainer interface
This interface must be implemented by container applications that
want to use the EditLinks dialog. the EditLinks dialog calls back
to the container app to perform the OLE functions to manipulate
the links within the container. }
type
IOleUILinkContainer = interface(IUnknown)
['{00000000-0000-0000-0000-000000000000}'] //!!!
function GetNextLink(dwLink: Longint): Longint; stdcall;
function SetLinkUpdateOptions(dwLink: Longint; dwUpdateOpt: Longint): HResult; stdcall;
function GetLinkUpdateOptions(dwLink: Longint;
var dwUpdateOpt: Longint): HResult; stdcall;
function SetLinkSource(dwLink: Longint; pszDisplayName: PChar;
lenFileName: Longint; var chEaten: Longint;
fValidateSource: BOOL): HResult; stdcall;
function GetLinkSource(dwLink: Longint; var pszDisplayName: PChar;
var lenFileName: Longint; var pszFullLinkType: PChar;
var pszShortLinkType: PChar; var fSourceAvailable: BOOL;
var fIsSelected: BOOL): HResult; stdcall;
function OpenLinkSource(dwLink: Longint): HResult; stdcall;
function UpdateLink(dwLink: Longint; fErrorMessage: BOOL;
fErrorAction: BOOL): HResult; stdcall;
function CancelLink(dwLink: Longint): HResult; stdcall;
end;
{$EXTERNALSYM IOleUILinkContainer}
{ TOleIUEditLinks structure }
type
POleUIEditLinks = ^TOleUIEditLinks;
{$EXTERNALSYM tagOLEUIEDITLINKSA}
tagOLEUIEDITLINKSA = record
cbStruct: Longint; { Structure Size }
dwFlags: Longint; { IN-OUT: Flags }
hWndOwner: HWnd; { Owning window }
lpszCaption: PChar; { Dialog caption bar contents }
lpfnHook: TFNOleUIHook; { Hook callback }
lCustData: Longint; { Custom data to pass to hook }
hInstance: THandle; { Instance for customized template name }
lpszTemplate: PChar; { Customized template name }
hResource: HRsrc; { Customized template handle }
OleUILinkContainer: IOleUILinkContainer; { IN: Interface to manipulate
links in the container }
end;
TOleUIEditLinks = tagOLEUIEDITLINKSA;
const
{$EXTERNALSYM OLEUI_ELERR_LINKCNTRNULL}
OLEUI_ELERR_LINKCNTRNULL = OLEUI_ERR_STANDARDMAX + 0;
{$EXTERNALSYM OLEUI_ELERR_LINKCNTRINVALID}
OLEUI_ELERR_LINKCNTRINVALID = OLEUI_ERR_STANDARDMAX + 1;
{$EXTERNALSYM OleUIEditLinks}
function OleUIEditLinks(var Info: TOleUIEditLinks): Integer; stdcall;
{ Edit Links flags }
const
{$EXTERNALSYM ELF_SHOWHELP}
ELF_SHOWHELP = $00000001;
{$EXTERNALSYM ELF_DISABLEUPDATENOW}
ELF_DISABLEUPDATENOW = $00000002;
{$EXTERNALSYM ELF_DISABLEOPENSOURCE}
ELF_DISABLEOPENSOURCE = $00000004;
{$EXTERNALSYM ELF_DISABLECHANGESOURCE}
ELF_DISABLECHANGESOURCE = $00000008;
{$EXTERNALSYM ELF_DISABLECANCELLINK}
ELF_DISABLECANCELLINK = $00000010;
{ **** Change Icon dialog **** }
type
POleUIChangeIcon = ^TOleUIChangeIcon;
{$EXTERNALSYM tagOLEUICHANGEICONA}
tagOLEUICHANGEICONA = record
cbStruct: Longint; { Structure Size }
dwFlags: Longint; { IN-OUT: Flags }
hWndOwner: HWnd; { Owning window }
lpszCaption: PChar; { Dialog caption bar contents }
lpfnHook: TFNOleUIHook; { Hook callback }
lCustData: Longint; { Custom data to pass to hook }
hInstance: THandle; { Instance for customized template name }
lpszTemplate: PChar; { Customized template name }
hResource: HRsrc; { Customized template handle }
hMetaPict: HGlobal; { IN-OUT: Current and final image.
Source of the icon is embedded in
the metafile itself }
clsid: TCLSID; { IN: class used to get Default icon }
szIconExe: array[0..MAX_PATH - 1] of Char; { IN: exlicit icon source path }
cchIconExe: Integer; { IN: number of characters in szIconExe }
end;
TOleUIChangeIcon = tagOLEUICHANGEICONA;
{$EXTERNALSYM OleUIChangeIcon}
function OleUIChangeIcon(var Info: TOleUIChangeIcon): Integer; stdcall;
{ Change Icon flags }
const
{$EXTERNALSYM CIF_SHOWHELP}
CIF_SHOWHELP = $00000001;
{$EXTERNALSYM CIF_SELECTCURRENT}
CIF_SELECTCURRENT = $00000002;
{$EXTERNALSYM CIF_SELECTDEFAULT}
CIF_SELECTDEFAULT = $00000004;
{$EXTERNALSYM CIF_SELECTFROMFILE}
CIF_SELECTFROMFILE = $00000008;
{$EXTERNALSYM CIF_USEICONEXE}
CIF_USEICONEXE = $00000010;
{ Change Icon specific error codes }
const
{$EXTERNALSYM OLEUI_CIERR_MUSTHAVECLSID}
OLEUI_CIERR_MUSTHAVECLSID = OLEUI_ERR_STANDARDMAX + 0;
{$EXTERNALSYM OLEUI_CIERR_MUSTHAVECURRENTMETAFILE}
OLEUI_CIERR_MUSTHAVECURRENTMETAFILE = OLEUI_ERR_STANDARDMAX + 1;
{$EXTERNALSYM OLEUI_CIERR_SZICONEXEINVALID}
OLEUI_CIERR_SZICONEXEINVALID = OLEUI_ERR_STANDARDMAX + 2;
{ Property used by ChangeIcon dialog to give its parent window access to
its hDlg. The PasteSpecial dialog may need to force the ChgIcon dialog
down if the clipboard contents change underneath it. If so it will send
a IDCANCEL command to the ChangeIcon dialog. }
const
{$EXTERNALSYM PROP_HWND_CHGICONDLG}
PROP_HWND_CHGICONDLG = 'HWND_CIDLG';
{ **** Convert dialog **** }
type
POleUIConvert = ^TOleUIConvert;
{$EXTERNALSYM tagOLEUICONVERTA}
tagOLEUICONVERTA = record
cbStruct: Longint; { Structure Size }
dwFlags: Longint; { IN-OUT: Flags }
hWndOwner: HWnd; { Owning window }
lpszCaption: PChar; { Dialog caption bar contents }
lpfnHook: TFNOleUIHook; { Hook callback }
lCustData: Longint; { Custom data to pass to hook }
hInstance: THandle; { Instance for customized template name }
lpszTemplate: PChar; { Customized template name }
hResource: HRsrc; { Customized template handle }
clsid: TCLSID; { IN: Class ID sent in to dialog: IN only }
clsidConvertDefault: TCLSID; { IN: use as convert default: IN only }
clsidActivateDefault: TCLSID; { IN: use as activate default: IN only }
clsidNew: TCLSID; { OUT: Selected Class ID }
dvAspect: Longint; { IN-OUT: either DVASPECT_CONTENT or
DVASPECT_ICON }
wFormat: Word; { IN" Original data format }
fIsLinkedObject: BOOL; { IN: true if object is linked }
hMetaPict: HGlobal; { IN-OUT: metafile icon image }
lpszUserType: PChar; { IN-OUT: user type name of original class.
We'll do lookup if NULL. This gets freed
on exit }
fObjectsIconChanged: BOOL; { OUT: TRUE == ChangeIcon was called }
lpszDefLabel: PChar; { IN-OUT: default label to use for icon.
if NULL, the short user type name
will be used. if the object is a
link, the caller should pass the
DisplayName of the link source
This gets freed on exit }
cClsidExclude: Integer; { IN: No. of CLSIDs in lpClsidExclude }
lpClsidExclude: PCLSID; { IN: List of CLSIDs to exclude from list }
end;
TOleUIConvert = tagOLEUICONVERTA;
{$EXTERNALSYM OleUIConvert}
function OleUIConvert(var Info: TOleUIConvert): Integer; stdcall;
{ Determine if there is at least one class that can Convert or ActivateAs
the given clsid }
{$EXTERNALSYM OleUICanConvertOrActivateAs}
function OleUICanConvertOrActivateAs(const clsid: TCLSID;
fIsLinkedObject: BOOL; wFormat: Word): BOOL; stdcall;
{ Convert Dialog flags }
const
{$EXTERNALSYM CF_SHOWHELPBUTTON}
CF_SHOWHELPBUTTON = $00000001;
{$EXTERNALSYM CF_SETCONVERTDEFAULT}
CF_SETCONVERTDEFAULT = $00000002;
{$EXTERNALSYM CF_SETACTIVATEDEFAULT}
CF_SETACTIVATEDEFAULT = $00000004;
{$EXTERNALSYM CF_SELECTCONVERTTO}
CF_SELECTCONVERTTO = $00000008;
{$EXTERNALSYM CF_SELECTACTIVATEAS}
CF_SELECTACTIVATEAS = $00000010;
{$EXTERNALSYM CF_DISABLEDISPLAYASICON}
CF_DISABLEDISPLAYASICON = $00000020;
{$EXTERNALSYM CF_DISABLEACTIVATEAS}
CF_DISABLEACTIVATEAS = $00000040;
{$EXTERNALSYM CF_HIDECHANGEICON}
CF_HIDECHANGEICON = $00000080;
{$EXTERNALSYM CF_CONVERTONLY}
CF_CONVERTONLY = $00000100;
{ Convert specific error codes }
const
{$EXTERNALSYM OLEUI_CTERR_CLASSIDINVALID}
OLEUI_CTERR_CLASSIDINVALID = OLEUI_ERR_STANDARDMAX + 1;
{$EXTERNALSYM OLEUI_CTERR_DVASPECTINVALID}
OLEUI_CTERR_DVASPECTINVALID = OLEUI_ERR_STANDARDMAX + 2;
{$EXTERNALSYM OLEUI_CTERR_CBFORMATINVALID}
OLEUI_CTERR_CBFORMATINVALID = OLEUI_ERR_STANDARDMAX + 3;
{$EXTERNALSYM OLEUI_CTERR_HMETAPICTINVALID}
OLEUI_CTERR_HMETAPICTINVALID = OLEUI_ERR_STANDARDMAX + 4;
{$EXTERNALSYM OLEUI_CTERR_STRINGINVALID}
OLEUI_CTERR_STRINGINVALID = OLEUI_ERR_STANDARDMAX + 5;
{ **** Busy dialog **** }
type
POleUIBusy = ^TOleUIBusy;
{$EXTERNALSYM tagOLEUIBUSYA}
tagOLEUIBUSYA = record
cbStruct: Longint; { Structure Size }
dwFlags: Longint; { IN-OUT: Flags }
hWndOwner: HWnd; { Owning window }
lpszCaption: PChar; { Dialog caption bar contents }
lpfnHook: TFNOleUIHook; { Hook callback }
lCustData: Longint; { Custom data to pass to hook }
hInstance: THandle; { Instance for customized template name }
lpszTemplate: PChar; { Customized template name }
hResource: HRsrc; { Customized template handle }
task: HTask; { IN: HTask which is blocking }
lphWndDialog: ^HWnd; { IN: Dialog's HWND is placed here }
end;
TOleUIBusy = tagOLEUIBUSYA;
{$EXTERNALSYM OleUIBusy}
function OleUIBusy(var Info: TOleUIBusy): Integer; stdcall;
{ Flags for the Busy dialog }
const
{$EXTERNALSYM BZ_DISABLECANCELBUTTON}
BZ_DISABLECANCELBUTTON = $00000001;
{$EXTERNALSYM BZ_DISABLESWITCHTOBUTTON}
BZ_DISABLESWITCHTOBUTTON = $00000002;
{$EXTERNALSYM BZ_DISABLERETRYBUTTON}
BZ_DISABLERETRYBUTTON = $00000004;
{$EXTERNALSYM BZ_NOTRESPONDINGDIALOG}
BZ_NOTRESPONDINGDIALOG = $00000008;
{ Busy specific error/return codes }
const
{$EXTERNALSYM OLEUI_BZERR_HTASKINVALID}
OLEUI_BZERR_HTASKINVALID = OLEUI_ERR_STANDARDMAX + 0;
{$EXTERNALSYM OLEUI_BZ_SWITCHTOSELECTED}
OLEUI_BZ_SWITCHTOSELECTED = OLEUI_ERR_STANDARDMAX + 1;
{$EXTERNALSYM OLEUI_BZ_RETRYSELECTED}
OLEUI_BZ_RETRYSELECTED = OLEUI_ERR_STANDARDMAX + 2;
{$EXTERNALSYM OLEUI_BZ_CALLUNBLOCKED}
OLEUI_BZ_CALLUNBLOCKED = OLEUI_ERR_STANDARDMAX + 3;
{ **** Object Properties dialog **** }
type
IOleUIObjInfo = interface(IUnknown)
['{00000000-0000-0000-0000-000000000000}'] //!!!
function GetObjectInfo(dwObject: Longint;
var dwObjSize: Longint; var lpszLabel: PChar;
var lpszType: PChar; var lpszShortType: PChar;
var lpszLocation: PChar): HResult; stdcall;
function GetConvertInfo(dwObject: Longint; var ClassID: TCLSID;
var wFormat: Word; var ConvertDefaultClassID: TCLSID;
var lpClsidExclude: PCLSID; var cClsidExclude: Longint): HResult; stdcall;
function ConvertObject(dwObject: Longint; const clsidNew: TCLSID): HResult; stdcall;
function GetViewInfo(dwObject: Longint; var hMetaPict: HGlobal;
var dvAspect: Longint; var nCurrentScale: Integer): HResult; stdcall;
function SetViewInfo(dwObject: Longint; hMetaPict: HGlobal;
dvAspect: Longint; nCurrentScale: Integer;
bRelativeToOrig: BOOL): HResult; stdcall;
end;
{$EXTERNALSYM IOleUIObjInfo}
type
IOleUILinkInfo = interface(IOleUILinkContainer)
['{00000000-0000-0000-0000-000000000000}'] //!!!
function GetLastUpdate(dwLink: Longint; var LastUpdate: TFileTime): HResult; stdcall;
end;
{$EXTERNALSYM IOleUILinkInfo}
type
POleUIGnrlProps = ^TOleUIGnrlProps;
{$EXTERNALSYM tagOLEUIGNRLPROPSA}
tagOLEUIGNRLPROPSA = record
cbStruct: Longint;
dwFlags: Longint;
dwReserved1: array[1..2] of Longint;
lpfnHook: TFNOleUIHook;
lCustData: Longint;
dwReserved2: array[1..3] of Longint;
lpOP: Pointer;
end;
TOleUIGnrlProps = tagOLEUIGNRLPROPSA;
{$EXTERNALSYM OLEUIGNRLPROPS}
OLEUIGNRLPROPS = tagOLEUIGNRLPROPSA;
type
POleUIViewProps = ^TOleUIViewProps;
{$EXTERNALSYM tagOLEUIVIEWPROPSA}
tagOLEUIVIEWPROPSA = record
cbStruct: Longint;
dwFlags: Longint;
dwReserved1: array[1..2] of Longint;
lpfnHook: TFNOleUIHook;
lCustData: Longint;
dwReserved2: array[1..3] of Longint;
lpOP: Pointer;
nScaleMin: Integer;
nScaleMax: Integer;
end;
TOleUIViewProps = tagOLEUIVIEWPROPSA;
{$EXTERNALSYM OLEUIVIEWPROPS}
OLEUIVIEWPROPS = tagOLEUIVIEWPROPSA;
{ Flags for TOleUIViewProps }
const
{$EXTERNALSYM VPF_SELECTRELATIVE}
VPF_SELECTRELATIVE = $00000001; { IN: relative to orig }
{$EXTERNALSYM VPF_DISABLERELATIVE}
VPF_DISABLERELATIVE = $00000002; { IN: disable relative to orig }
{$EXTERNALSYM VPF_DISABLESCALE}
VPF_DISABLESCALE = $00000004; { IN: disable scale option }
type
POleUILinkProps = ^TOleUILinkProps;
{$EXTERNALSYM tagOLEUILINKPROPSA}
tagOLEUILINKPROPSA = record
cbStruct: Longint;
dwFlags: Longint;
dwReserved1: array[1..2] of Longint;
lpfnHook: TFNOleUIHook;
lCustData: Longint;
dwReserved2: array[1..3] of Longint;
lpOP: Pointer;
end;
TOleUILinkProps = tagOLEUILINKPROPSA;
{$EXTERNALSYM OLEUILINKPROPS}
OLEUILINKPROPS = tagOLEUILINKPROPSA;
type
POleUIObjectProps = ^TOleUIObjectProps;
{$EXTERNALSYM tagOLEUIOBJECTPROPSA}
tagOLEUIOBJECTPROPSA = record
cbStruct: Longint; { Structure Size }
dwFlags: Longint; { IN-OUT: global flags for the sheet }
lpPS: PPropSheetHeader; { IN: property sheet header }
dwObject: Longint; { IN: identifier for the object }
lpObjInfo: IOleUIObjInfo; { IN: interface to manipulate object }
dwLink: Longint; { IN: identifier for the link }
lpLinkInfo: IOleUILinkInfo; { IN: interface to manipulate link }
lpGP: POleUIGnrlProps; { IN: general page }
lpVP: POleUIViewProps; { IN: view page }
lpLP: POleUILinkProps; { IN: link page }
end;
TOleUIObjectProps = tagOLEUIOBJECTPROPSA;
{$EXTERNALSYM OLEUIOBJECTPROPS}
OLEUIOBJECTPROPS = tagOLEUIOBJECTPROPSA;
{$EXTERNALSYM OleUIObjectProperties}
function OleUIObjectProperties(var Info: TOleUIObjectProps): Integer; stdcall;
{ Flags for OLEUIOBJECTPROPS }
const
{$EXTERNALSYM OPF_OBJECTISLINK}
OPF_OBJECTISLINK = $00000001;
{$EXTERNALSYM OPF_NOFILLDEFAULT}
OPF_NOFILLDEFAULT = $00000002;
{$EXTERNALSYM OPF_SHOWHELP}
OPF_SHOWHELP = $00000004;
{$EXTERNALSYM OPF_DISABLECONVERT}
OPF_DISABLECONVERT = $00000008;
{ Errors for OleUIObjectProperties }
const
{$EXTERNALSYM OLEUI_OPERR_SUBPROPNULL}
OLEUI_OPERR_SUBPROPNULL = OLEUI_ERR_STANDARDMAX + 0;
{$EXTERNALSYM OLEUI_OPERR_SUBPROPINVALID}
OLEUI_OPERR_SUBPROPINVALID = OLEUI_ERR_STANDARDMAX + 1;
{$EXTERNALSYM OLEUI_OPERR_PROPSHEETNULL}
OLEUI_OPERR_PROPSHEETNULL = OLEUI_ERR_STANDARDMAX + 2;
{$EXTERNALSYM OLEUI_OPERR_PROPSHEETINVALID}
OLEUI_OPERR_PROPSHEETINVALID = OLEUI_ERR_STANDARDMAX + 3;
{$EXTERNALSYM OLEUI_OPERR_SUPPROP}
OLEUI_OPERR_SUPPROP = OLEUI_ERR_STANDARDMAX + 4;
{$EXTERNALSYM OLEUI_OPERR_PROPSINVALID}
OLEUI_OPERR_PROPSINVALID = OLEUI_ERR_STANDARDMAX + 5;
{$EXTERNALSYM OLEUI_OPERR_PAGESINCORRECT}
OLEUI_OPERR_PAGESINCORRECT = OLEUI_ERR_STANDARDMAX + 6;
{$EXTERNALSYM OLEUI_OPERR_INVALIDPAGES}
OLEUI_OPERR_INVALIDPAGES = OLEUI_ERR_STANDARDMAX + 7;
{$EXTERNALSYM OLEUI_OPERR_NOTSUPPORTED}
OLEUI_OPERR_NOTSUPPORTED = OLEUI_ERR_STANDARDMAX + 8;
{$EXTERNALSYM OLEUI_OPERR_DLGPROCNOTNULL}
OLEUI_OPERR_DLGPROCNOTNULL = OLEUI_ERR_STANDARDMAX + 9;
{$EXTERNALSYM OLEUI_OPERR_LPARAMNOTZERO}
OLEUI_OPERR_LPARAMNOTZERO = OLEUI_ERR_STANDARDMAX + 10;
{$EXTERNALSYM OLEUI_GPERR_STRINGINVALID}
OLEUI_GPERR_STRINGINVALID = OLEUI_ERR_STANDARDMAX + 11;
{$EXTERNALSYM OLEUI_GPERR_CLASSIDINVALID}
OLEUI_GPERR_CLASSIDINVALID = OLEUI_ERR_STANDARDMAX + 12;
{$EXTERNALSYM OLEUI_GPERR_LPCLSIDEXCLUDEINVALID}
OLEUI_GPERR_LPCLSIDEXCLUDEINVALID = OLEUI_ERR_STANDARDMAX + 13;
{$EXTERNALSYM OLEUI_GPERR_CBFORMATINVALID}
OLEUI_GPERR_CBFORMATINVALID = OLEUI_ERR_STANDARDMAX + 14;
{$EXTERNALSYM OLEUI_VPERR_METAPICTINVALID}
OLEUI_VPERR_METAPICTINVALID = OLEUI_ERR_STANDARDMAX + 15;
{$EXTERNALSYM OLEUI_VPERR_DVASPECTINVALID}
OLEUI_VPERR_DVASPECTINVALID = OLEUI_ERR_STANDARDMAX + 16;
{$EXTERNALSYM OLEUI_LPERR_LINKCNTRNULL}
OLEUI_LPERR_LINKCNTRNULL = OLEUI_ERR_STANDARDMAX + 17;
{$EXTERNALSYM OLEUI_LPERR_LINKCNTRINVALID}
OLEUI_LPERR_LINKCNTRINVALID = OLEUI_ERR_STANDARDMAX + 18;
{$EXTERNALSYM OLEUI_OPERR_PROPERTYSHEET}
OLEUI_OPERR_PROPERTYSHEET = OLEUI_ERR_STANDARDMAX + 19;
{ wParam used by PSM_QUERYSIBLINGS }
const
{$EXTERNALSYM OLEUI_QUERY_GETCLASSID}
OLEUI_QUERY_GETCLASSID = $FF00; { override class id for icon }
{$EXTERNALSYM OLEUI_QUERY_LINKBROKEN}
OLEUI_QUERY_LINKBROKEN = $FF01; { after link broken }
implementation
const
OleDlgDLL = 'oledlg.dll';
function OleUIAddVerbMenu; external OleDlgDLL name 'OleUIAddVerbMenuA';
function OleUIInsertObject; external OleDlgDLL name 'OleUIInsertObjectA';
function OleUIPasteSpecial; external OleDlgDLL name 'OleUIPasteSpecialA';
function OleUIEditLinks; external OleDlgDLL name 'OleUIEditLinksA';
function OleUIChangeIcon; external OleDlgDLL name 'OleUIChangeIconA';
function OleUIConvert; external OleDlgDLL name 'OleUIConvertA';
function OleUICanConvertOrActivateAs; external OleDlgDLL name 'OleUICanConvertOrActivateAs';
function OleUIBusy; external OleDlgDLL name 'OleUIBusyA';
function OleUIObjectProperties; external OleDlgDLL name 'OleUIObjectPropertiesA';
end.
|
// Copyright 2021 Darian Miller, Licensed under Apache-2.0
// SPDX-License-Identifier: Apache-2.0
// More info: www.radprogrammer.com
unit radRTL.BitUtils.Tests;
interface
uses
TestFramework;
type
TBitUtilsTest = class(TTestCase)
published
procedure TestExtractLastBits_ValueZero;
procedure TestExtractLastBits_ValueOne;
procedure TestExtractLastBits_ValueTwo;
procedure TestExtractLastBits_ValueThree;
procedure TestExtractLastBits_ValueFour;
procedure TestExtractLastBits_ValueFourteen;
procedure TestExtractLastBits_ValueFifteen;
procedure TestExtractLastBits_ValueMaxInt;
procedure TestExtractLastBits_ValueNegativeOne;
end;
implementation
uses
System.SysUtils,
System.Math,
radRTL.BitUtils;
procedure TBitUtilsTest.TestExtractLastBits_ValueZero;
const
TESTVALUE = 0; // '0000-0000-0000-0000-0000-0000-0000-0000'
var
vBits:Integer;
begin
// no matter the bits requested, should be 0 returned
for vBits := 1 to 31 do // signed integer with leading signed bit in position 32
begin
CheckEquals(TESTVALUE, ExtractLastBits(TESTVALUE, vBits), 'Failed with bit ' + IntToStr(vBits));
end;
end;
procedure TBitUtilsTest.TestExtractLastBits_ValueOne;
const
TESTVALUE = 1; // '0000-0000-0000-0000-0000-0000-0000-0001'
var
vBits:Integer;
begin
CheckEquals(0, ExtractLastBits(1, 0));
for vBits := 1 to 31 do
begin
CheckEquals(TESTVALUE, ExtractLastBits(TESTVALUE, vBits), 'Failed with bit ' + IntToStr(vBits));
end;
end;
procedure TBitUtilsTest.TestExtractLastBits_ValueTwo;
const
TESTVALUE = 2; // '0000-0000-0000-0000-0000-0000-0000-0010'
var
vBits:Integer;
begin
CheckEquals(0, ExtractLastBits(TESTVALUE, 0));
CheckEquals(0, ExtractLastBits(TESTVALUE, 1));
for vBits := 2 to 31 do
begin
CheckEquals(TESTVALUE, ExtractLastBits(TESTVALUE, vBits), 'Failed with bit ' + IntToStr(vBits));
end;
end;
procedure TBitUtilsTest.TestExtractLastBits_ValueThree;
const
TESTVALUE = 3; // '0000-0000-0000-0000-0000-0000-0000-0011'
var
vBits:Integer;
begin
CheckEquals(0, ExtractLastBits(TESTVALUE, 0));
CheckEquals(1, ExtractLastBits(TESTVALUE, 1));
for vBits := 2 to 31 do
begin
CheckEquals(TESTVALUE, ExtractLastBits(TESTVALUE, vBits), 'Failed with bit ' + IntToStr(vBits));
end;
end;
procedure TBitUtilsTest.TestExtractLastBits_ValueFour;
const
TESTVALUE = 4; // '0000-0000-0000-0000-0000-0000-0000-0100'
var
vBits:Integer;
begin
CheckEquals(0, ExtractLastBits(TESTVALUE, 0));
CheckEquals(0, ExtractLastBits(TESTVALUE, 1));
CheckEquals(0, ExtractLastBits(TESTVALUE, 2));
for vBits := 3 to 31 do
begin
CheckEquals(TESTVALUE, ExtractLastBits(TESTVALUE, vBits), 'Failed with bit ' + IntToStr(vBits));
end;
end;
procedure TBitUtilsTest.TestExtractLastBits_ValueFourteen;
const
TESTVALUE = 14; // '0000-0000-0000-0000-0000-0000-0000-1110'
var
vBits:Integer;
begin
CheckEquals(0, ExtractLastBits(TESTVALUE, 0));
CheckEquals(0, ExtractLastBits(TESTVALUE, 1));
CheckEquals(2, ExtractLastBits(TESTVALUE, 2));
CheckEquals(6, ExtractLastBits(TESTVALUE, 3));
for vBits := 4 to 31 do
begin
CheckEquals(TESTVALUE, ExtractLastBits(TESTVALUE, vBits), 'Failed with bit ' + IntToStr(vBits));
end;
end;
procedure TBitUtilsTest.TestExtractLastBits_ValueFifteen;
const
TESTVALUE = 15; // '0000-0000-0000-0000-0000-0000-0000-1111'
var
vBits:Integer;
begin
CheckEquals(0, ExtractLastBits(TESTVALUE, 0));
CheckEquals(1, ExtractLastBits(TESTVALUE, 1));
CheckEquals(3, ExtractLastBits(TESTVALUE, 2));
CheckEquals(7, ExtractLastBits(TESTVALUE, 3));
for vBits := 4 to 31 do
begin
CheckEquals(TESTVALUE, ExtractLastBits(TESTVALUE, vBits), 'Failed with bit ' + IntToStr(vBits));
end;
end;
procedure TBitUtilsTest.TestExtractLastBits_ValueMaxInt;
const
TESTVALUE = MaxInt; // 2147483647 '0111-1111-1111-1111-1111-1111-1111-1111'
var
vBits:Integer;
vExpected:Integer;
begin
CheckEquals(0, ExtractLastBits(TESTVALUE, 0));
for vBits := 1 to 31 do
begin
vExpected := Trunc(Power(2, vBits)) - 1;
CheckEquals(vExpected, ExtractLastBits(TESTVALUE, vBits), 'Failed with bit ' + IntToStr(vBits));
end;
end;
procedure TBitUtilsTest.TestExtractLastBits_ValueNegativeOne;
const
TESTVALUE = -1; // '1111-1111-1111-1111-1111-1111-1111-1111'
var
vBits:Integer;
vExpected:Integer;
begin
CheckEquals(0, ExtractLastBits(TESTVALUE, 0));
for vBits := 1 to 31 do
begin
vExpected := Trunc(Power(2, vBits)) - 1;
CheckEquals(vExpected, ExtractLastBits(TESTVALUE, vBits), 'Failed with bit ' + IntToStr(vBits));
end;
end;
initialization
RegisterTest(TBitUtilsTest.Suite);
end.
|
{
Asynchronous wrapper around Synapse TBlockSocket.
(C) Sergey Bodrov, 2012-2018
When using UDP, remember, that it not session protocol, data delivery and correct
order not guaranteed. To start receive data, you must send empty packet to
remote side, it tell remote side return address.
From version 1.0.3 multiple DataPortIP instances uses common socket reader with single thread.
Properties:
RemoteHost - IP-address or name of remote host
RemotePort - remote UPD or TCP port number
LocalHost - IP-address or name of local host
LocalPort - local UPD or TCP port number
Methods:
Open() - Connect to remote port. Session establiched for TCP and just port initialised for UDP. Init string format:
InitStr = 'RemoteHost:RemotePort'
RemoteHost - IP-address or name of remote host
RemotePort - remote UPD or TCP port number
Events:
OnOpen - Triggered after UDP port init or TCP session establiched.
}
unit DataPortIP;
interface
uses {$ifndef FPC}Windows,{$endif} SysUtils, Classes,
syncobjs, DataPort, synsock, blcksock, synautil;
{$ifdef Linux}
// Uncomment next line to enable TCP keep-alive in Linux
//{$define LINUX_TCP_KEEPALIVE}
{$endif}
type
TIpProtocolEnum = (ippUDP, ippTCP);
TIpSocketItem = class;
{ TDataPortIP }
TDataPortIP = class(TDataPort)
private
//slReadData: TStringList; // for storing every incoming data packet separately
FLock: TMultiReadExclusiveWriteSynchronizer;
procedure SetIpProtocol(AValue: TIpProtocolEnum);
protected
FIpSocketItem: TIpSocketItem;
FRemoteHost: string;
FRemotePort: string;
FIpProtocol: TIpProtocolEnum;
function GetLocalHost: string; virtual;
function GetLocalPort: string; virtual;
procedure OnIncomingMsgHandler(Sender: TObject; const AMsg: string);
procedure OnErrorHandler(Sender: TObject; const AMsg: string);
procedure OnConnectHandler(Sender: TObject);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
{ Open() - Connect to remote port. Session establiched for TCP and just port initialised for UDP. Init string format:
InitStr = 'RemoteHost:RemotePort'
RemoteHost - IP-address or name of remote host
RemotePort - remote UPD or TCP port number }
procedure Open(const AInitStr: string = ''); override;
procedure Close(); override;
function Push(const AData: AnsiString): boolean; override;
function Pull(ASize: Integer = MaxInt): AnsiString; override;
function Peek(ASize: Integer = MaxInt): AnsiString; override;
function PeekSize(): Cardinal; override;
{ IP protocol type }
property IpProtocol: TIpProtocolEnum read FIpProtocol write SetIpProtocol;
published
{ IP-address or name of remote host }
property RemoteHost: string read FRemoteHost write FRemoteHost;
{ remote UPD or TCP port number }
property RemotePort: string read FRemotePort write FRemotePort;
{ IP-address or name of local host }
property LocalHost: string read GetLocalHost;
{ local UPD or TCP port number }
property LocalPort: string read GetLocalPort;
property Active;
property OnDataAppear;
property OnError;
{ Triggered after UDP port init or TCP session establiched }
property OnOpen;
property OnClose;
end;
TDataPortTCP = class(TDataPortIP)
public
procedure Open(const AInitStr: string = ''); override;
end;
{ TDataPortUDP }
TDataPortUDP = class(TDataPortIP)
public
procedure Open(const AInitStr: string = ''); override;
{ Send data to destination address ADestAddr as 'host:port' }
function PushTo(const AData: AnsiString; ADestAddr: string): Boolean;
end;
{ TIpSocketItem }
{ Item for sockets list, created on Open(), used by reader thread }
TIpSocketItem = class(TObject)
private
FOnIncomingMsg: TMsgEvent;
FOnError: TMsgEvent;
FOnConnect: TNotifyEvent;
FLock: TCriticalSection;
public
// Only socket reader can manage Socket
Socket: TBlockSocket;
DataPortIP: TDataPortIP;
Protocol: TIpProtocolEnum;
LockCount: Integer;
RxDataStr: AnsiString;
//TxDataStr: AnsiString;
ErrorStr: string;
Active: Boolean;
Connected: Boolean;
function GetLocalHost(): string;
function GetLocalPort(): string;
function SendString(const ADataStr: AnsiString): Boolean;
function SendStream(st: TStream): Boolean;
property Lock: TCriticalSection read FLock;
property OnIncomingMsg: TMsgEvent read FOnIncomingMsg write FOnIncomingMsg;
property OnError: TMsgEvent read FOnError write FOnError;
property OnConnect: TNotifyEvent read FOnConnect write FOnConnect;
end;
procedure Register;
implementation
type
{ TIpSocketPool }
{ For better portability to DLL and stability, reader thread and critical section
automaticaly created after unit initialisation, when first DataPortIP opened.
And destroyed when last DataPortIP closed, before unit finalisation. }
TIpSocketPool = class(TList)
private
FIpReadThread: TThread;
FLock: TCriticalSection;
protected
procedure Notify(Ptr: Pointer; Action: TListNotification); override;
public
procedure BeforeDestruction(); override;
function DataPortOpen(ADataPortIP: TDataPortIP; AIncomingMsgHandler: TMsgEvent; AErrorHandler: TMsgEvent; AConnectHandler: TNotifyEvent): TIpSocketItem;
procedure DataPortClose(ADataPortIP: TDataPortIP);
function GetItem(AIndex: Integer): TIpSocketItem;
{ Lock for modifing items list. NOTE! Can be nil if no items in list! }
property Lock: TCriticalSection read FLock;
end;
{ TIpReadThread }
TIpReadThread = class(TThread)
protected
FItem: TIpSocketItem;
FEventType: Byte; // 0 - none, 1-connect, 2-data, 3-error
procedure CloseSocket();
procedure Execute(); override;
procedure SyncProc();
public
IpSocketPool: TIpSocketPool;
end;
var
GlobalIpSocketPool: TIpSocketPool;
procedure Register;
begin
RegisterComponents('DataPort', [TDataPortTCP]);
RegisterComponents('DataPort', [TDataPortUDP]);
end;
{ TIpReadThread }
procedure TIpReadThread.CloseSocket();
begin
FItem.Active := False;
if Assigned(FItem.Socket) then
begin
try
FItem.Socket.CloseSocket();
finally
FreeAndNil(FItem.Socket);
end;
end;
end;
procedure TIpReadThread.Execute();
var
n, ItemLockCount: Integer;
{$ifdef LINUX_TCP_KEEPALIVE}OptVal: Integer;{$endif}
IsNeedSleep: Boolean;
begin
n := 0;
while not Terminated do
begin
IsNeedSleep := True;
if n < IpSocketPool.Count then
begin
FItem := IpSocketPool.GetItem(n);
if Assigned(FItem.DataPortIP) then
begin
// acquire lock
//ItemLockCount := InterLockedIncrement(FItem.LockCount);
try
//if (ItemLockCount = 1) then
begin
// connect
if FItem.Active and (not Assigned(FItem.Socket)) then
begin
FItem.Connected := False;
FItem.ErrorStr := '';
case FItem.DataPortIP.IpProtocol of
ippUDP: FItem.Socket := TUDPBlockSocket.Create();
ippTCP: FItem.Socket := TTCPBlockSocket.Create();
end;
FItem.Socket.Connect(FItem.DataPortIP.RemoteHost, FItem.DataPortIP.RemotePort);
if FItem.Socket.LastError <> 0 then
begin
// Error event
FItem.ErrorStr := IntToStr(FItem.Socket.LastError) + ' ' + FItem.Socket.LastErrorDesc;
FItem.Active := False;
end
else
begin
// Connected event
FItem.Connected := True;
if Assigned(FItem.OnConnect) then
begin
FEventType := 1;
Synchronize(SyncProc);
end;
{$ifdef LINUX_TCP_KEEPALIVE}
// Set TCP keep-alive for Linux
OptVal := 1;
SetSockOpt(FItem.Socket.Socket, SOL_SOCKET, SO_KEEPALIVE, @OptVal, SizeOf(OptVal));
OptVal := 3; // TCP_KEEPIDLE - Start keepalives after this period
SetSockOpt(FItem.Socket.Socket, 6, 4, @OptVal, SizeOf(OptVal));
OptVal := 3; // TCP_KEEPINTVL - Interval between keepalives
SetSockOpt(FItem.Socket.Socket, 6, 5, @OptVal, SizeOf(OptVal));
OptVal := 3; // TCP_KEEPCNT - Number of keepalives before death
SetSockOpt(FItem.Socket.Socket, 6, 6, @OptVal, SizeOf(OptVal));
{$endif}
end;
//IsNeedSleep := False;
end;
// read
//if FItem.Active and Assigned(FItem.Socket) and (FItem.Socket.WaitingData > 0) then
//if FItem.Active and Assigned(FItem.Socket) and (FItem.Socket.WaitingDataEx() > 0) then
if FItem.Active and Assigned(FItem.Socket) then
begin
try
FItem.RxDataStr := FItem.RxDataStr + FItem.Socket.RecvPacket(0);
if FItem.Socket.LastError = 0 then
begin
// DataRead event
if Assigned(FItem.OnIncomingMsg) then
begin
FEventType := 2;
Synchronize(SyncProc);
end;
end
else if FItem.Socket.LastError = WSAETIMEDOUT then
begin
// nothing
end
else
begin
// Error event
FItem.ErrorStr := IntToStr(FItem.Socket.LastError) + ' ' + FItem.Socket.LastErrorDesc;
FItem.Active := False;
end;
IsNeedSleep := False;
except on E: Exception do
begin
FItem.ErrorStr := E.Message;
CloseSocket();
end;
end;
end;
// disconnect
if (not FItem.Active) and Assigned(FItem.Socket) then
begin
CloseSocket();
IsNeedSleep := False;
end;
end;
finally
// release lock
//InterLockedDecrement(FItem.LockCount);
end;
end
else
begin
// delete item
CloseSocket();
if Assigned(IpSocketPool.Lock) then
begin
IpSocketPool.Lock.Acquire();
try
IpSocketPool.Delete(n);
Dec(n);
finally
IpSocketPool.Lock.Release();
end;
end;
end;
// Error event
if FItem.ErrorStr <> '' then
begin
if Assigned(FItem.OnError) then
begin
FEventType := 3;
Synchronize(SyncProc);
end;
FItem.ErrorStr := '';
end;
Inc(n);
end
else
begin
n := 0;
if IsNeedSleep then
Sleep(1);
end;
end;
if Terminated then
begin
// cleanup sockets
for n := IpSocketPool.Count-1 downto 0 do
begin
FItem := IpSocketPool.GetItem(n);
CloseSocket();
IpSocketPool.Delete(n);
end;
end;
end;
procedure TIpReadThread.SyncProc();
begin
case FEventType of
1: FItem.OnConnect(FItem);
2: FItem.OnIncomingMsg(FItem, FItem.RxDataStr);
3: FItem.OnError(FItem, FItem.ErrorStr);
end;
FEventType := 0;
end;
{ TIpSocketPool }
procedure TIpSocketPool.Notify(Ptr: Pointer; Action: TListNotification);
begin
inherited Notify(Ptr, Action);
if Action = lnDeleted then
TIpSocketItem(Ptr).Free();
end;
procedure TIpSocketPool.BeforeDestruction();
begin
if Assigned(FIpReadThread) then
FreeAndNil(FIpReadThread);
if Assigned(FLock) then
FreeAndNil(FLock);
inherited BeforeDestruction;
end;
function TIpSocketPool.DataPortOpen(ADataPortIP: TDataPortIP;
AIncomingMsgHandler: TMsgEvent; AErrorHandler: TMsgEvent;
AConnectHandler: TNotifyEvent): TIpSocketItem;
var
i: Integer;
begin
for i := 0 to Count-1 do
begin
Result := GetItem(i);
if Result.DataPortIP = ADataPortIP then
Exit;
end;
Result := TIpSocketItem.Create();
Result.DataPortIP := ADataPortIP;
Result.OnIncomingMsg := AIncomingMsgHandler;
Result.OnError := AErrorHandler;
Result.OnConnect := AConnectHandler;
Result.Active := True;
if not Assigned(FLock) then
FLock := TCriticalSection.Create();
FLock.Acquire();
try
Add(Result);
finally
FLock.Release();
end;
if (not Assigned(FIpReadThread)) then
begin
// create socket reader
FIpReadThread := TIpReadThread.Create(True);
(FIpReadThread as TIpReadThread).IpSocketPool := Self;
FIpReadThread.Suspended := False;
end;
end;
procedure TIpSocketPool.DataPortClose(ADataPortIP: TDataPortIP);
var
i, ActiveCount: Integer;
Item: TIpSocketItem;
begin
ActiveCount := 0;
if Assigned(FLock) then
begin
FLock.Acquire();
try
for i := Count-1 downto 0 do
begin
Item := GetItem(i);
if Item.DataPortIP = ADataPortIP then
begin
Item.DataPortIP := nil;
Item.OnIncomingMsg := nil;
Item.OnError := nil;
Item.OnConnect := nil;
Break;
end
else if Assigned(Item.DataPortIP) then
Inc(ActiveCount);
end;
finally
FLock.Release();
end;
end;
{if (ActiveCount = 0) then
begin
if Assigned(FIpReadThread) then
FreeAndNil(FIpReadThread);
if Assigned(FLock) then
FreeAndNil(FLock);
end; }
end;
function TIpSocketPool.GetItem(AIndex: Integer): TIpSocketItem;
begin
Result := TIpSocketItem(Get(AIndex));
end;
{ TIpSocketItem }
function TIpSocketItem.GetLocalHost(): string;
begin
if Assigned(Socket) then
begin
Socket.GetSinLocal();
Result := Socket.GetLocalSinIP;
end
else
Result := '';
end;
function TIpSocketItem.GetLocalPort(): string;
begin
if Assigned(Socket) then
begin
Socket.GetSinLocal();
Result := IntToStr(Socket.GetLocalSinPort);
end
else
Result := '';
end;
function TIpSocketItem.SendString(const ADataStr: AnsiString): Boolean;
var
LockTryCount: Integer;
begin
//TxDataStr := TxDataStr + ADataStr;
Result := False;
if Assigned(Socket) then
begin
// try to acquire exclusive lock
LockTryCount := 10;
while (InterLockedIncrement(LockCount) > 1) and (LockTryCount > 0) do
begin
InterLockedDecrement(LockCount);
Dec(LockTryCount);
if (LockTryCount = 0) then
Exit;
Sleep(1);
end;
try
try
Result := Socket.CanWrite(0);
if Result then
begin
Socket.SendString(ADataStr);
Result := (Socket.LastError = 0);
if not Result then
begin
ErrorStr := IntToStr(Socket.LastError) + ' ' + Socket.LastErrorDesc;
end;
end;
except
ErrorStr := 'Socket write exception';
end;
finally
// release exclusive lock
InterLockedDecrement(LockCount);
end;
end;
end;
function TIpSocketItem.SendStream(st: TStream): Boolean;
begin
Result := False;
if Assigned(st) and (st.Size <> 0) and Assigned(Socket) then
begin
st.Position := 0;
try
Result := Socket.CanWrite(0);
if Result then
begin
Socket.SendStream(st);
Result := (Socket.LastError = 0);
if not Result then
begin
ErrorStr := IntToStr(Socket.LastError) + ' ' + Socket.LastErrorDesc;
end;
end;
except
ErrorStr := 'Socket write exception';
end;
end;
end;
{ TDataPortIP }
constructor TDataPortIP.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
self.FLock := TMultiReadExclusiveWriteSynchronizer.Create();
Self.FRemoteHost := '';
Self.FRemotePort := '';
Self.FActive := False;
end;
procedure TDataPortIP.Open(const AInitStr: string = '');
var
n: integer;
begin
// Set host and port from init string
if AInitStr <> '' then
begin
n := Pos(':', AInitStr);
if n > 0 then
begin
Self.FRemoteHost := Copy(AInitStr, 1, n - 1);
Self.FRemotePort := Copy(AInitStr, n + 1, MaxInt);
end
else
Self.FRemoteHost := AInitStr;
end;
if Assigned(GlobalIpSocketPool) then
begin
FIpSocketItem := GlobalIpSocketPool.DataPortOpen(Self, OnIncomingMsgHandler, OnErrorHandler, OnConnectHandler);
end;
// don't inherits Open() - OnOpen event will be after successfull connection
end;
procedure TDataPortIP.Close();
begin
FIpSocketItem := nil;
if Active and Assigned(GlobalIpSocketPool) then
GlobalIpSocketPool.DataPortClose(Self);
inherited Close();
end;
destructor TDataPortIP.Destroy();
begin
FIpSocketItem := nil;
if Assigned(GlobalIpSocketPool) then
GlobalIpSocketPool.DataPortClose(Self);
FreeAndNil(FLock);
inherited Destroy();
end;
procedure TDataPortIP.OnConnectHandler(Sender: TObject);
begin
FActive := True;
if Assigned(OnOpen) then
OnOpen(Self);
end;
procedure TDataPortIP.SetIpProtocol(AValue: TIpProtocolEnum);
begin
if FIpProtocol = AValue then Exit;
Close();
FIpProtocol := AValue;
end;
function TDataPortIP.GetLocalHost: string;
begin
if Assigned(FIpSocketItem) then
Result := FIpSocketItem.GetLocalHost()
else
Result := '';
end;
function TDataPortIP.GetLocalPort: string;
begin
if Assigned(FIpSocketItem) then
Result := FIpSocketItem.GetLocalPort()
else
Result := '';
end;
procedure TDataPortIP.OnIncomingMsgHandler(Sender: TObject; const AMsg: string);
begin
if AMsg <> '' then
begin
if Assigned(FOnDataAppear) then
FOnDataAppear(self);
end;
end;
procedure TDataPortIP.OnErrorHandler(Sender: TObject; const AMsg: string);
begin
FIpSocketItem := nil;
if Assigned(Self.FOnError) then
Self.FOnError(Self, AMsg);
FActive := False;
end;
function TDataPortIP.Peek(ASize: Integer): AnsiString;
begin
if Assigned(FIpSocketItem) then
begin
FLock.BeginRead();
try
Result := Copy(FIpSocketItem.RxDataStr, 1, ASize);
finally
FLock.EndRead();
end;
end;
end;
function TDataPortIP.PeekSize(): Cardinal;
begin
if Assigned(FIpSocketItem) then
begin
FLock.BeginRead();
try
Result := Cardinal(Length(FIpSocketItem.RxDataStr));
finally
FLock.EndRead();
end;
end
else
Result := 0;
end;
function TDataPortIP.Pull(ASize: Integer): AnsiString;
begin
Result := '';
if Assigned(FIpSocketItem) then
begin
FLock.BeginRead();
try
Result := Copy(FIpSocketItem.RxDataStr, 1, ASize);
Delete(FIpSocketItem.RxDataStr, 1, ASize);
finally
FLock.EndRead();
end;
end;
end;
function TDataPortIP.Push(const AData: AnsiString): boolean;
begin
Result := False;
if Assigned(FIpSocketItem) and FLock.BeginWrite() then
begin
try
Result := FIpSocketItem.SendString(AData);
finally
FLock.EndWrite();
end;
end;
end;
procedure TDataPortTCP.Open(const AInitStr: string = '');
begin
FIpProtocol := ippTCP;
inherited Open(AInitStr);
FActive := True;
end;
procedure TDataPortUDP.Open(const AInitStr: string = '');
begin
FIpProtocol := ippUDP;
inherited Open(AInitStr);
FActive := True;
end;
function TDataPortUDP.PushTo(const AData: AnsiString; ADestAddr: string
): Boolean;
var
n: integer;
ss, sh, sp: string;
begin
Result := False;
if Assigned(FIpSocketItem) and Assigned(FIpSocketItem.Socket) then
begin
if ADestAddr = '' then
begin
//UdpSocket.SetRemoteSin(remoteHost, remotePort);
end
else
begin
ss := ADestAddr;
n := Pos(':', ss);
sh := Copy(ss, 1, n - 1);
sp := Copy(ss, n + 1, MaxInt);
FIpSocketItem.Socket.SetRemoteSin(sh, sp);
end;
FIpSocketItem.Socket.SendString(AData);
Result := (FIpSocketItem.Socket.LastError = 0);
if not Result then
begin
FIpSocketItem.ErrorStr := IntToStr(FIpSocketItem.Socket.LastError) + ' ' + FIpSocketItem.Socket.LastErrorDesc;
end;
end;
end;
initialization
GlobalIpSocketPool := TIpSocketPool.Create();
finalization
FreeAndNil(GlobalIpSocketPool);
end.
|
unit SmartCombo;
{
-Source
https://stackoverflow.com/questions/9466547/how-to-make-a-combo-box-with-fulltext-search-autocomplete-support
-Author1
https://stackoverflow.com/users/1870653/nikb
-Author2
https://stackoverflow.com/users/7974700/mprot
-Edit
jsf3rd@nate.com
* add - FChar: char; for UNICODE(like hangul)
}
interface
uses stdctrls, classes, messages, controls, windows, sysutils;
type
TSmartComboBox = class(TComboBox)
// Usage:
// Same as TComboBox, just invoke InitSmartCombo after Items list is filled with data.
// After InitSmartCombo is invoked, StoredItems is assigned and combo starts to behave as a smart combo.
// If InitSmartCombo is not invoked it acts as standard TComboBox, it is safe to bulk replace all TComboBox in application with TSmartComboBox
private
FChar: char;
FStoredItems: TStringList;
dofilter: boolean;
storeditemindex: integer;
procedure FilterItems;
procedure StoredItemsChange(Sender: TObject);
procedure SetStoredItems(const Value: TStringList);
procedure CNCommand(var AMessage: TWMCommand); message CN_COMMAND;
protected
procedure KeyPress(var Key: char); override;
procedure CloseUp; override;
procedure Click; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property StoredItems: TStringList read FStoredItems write SetStoredItems;
procedure InitSmartCombo;
end;
implementation
procedure TSmartComboBox.KeyPress(var Key: char);
// combo dropdown must be done in keypress, if its done on CBN_EDITUPDATE it messes up whole message processing mumbo-jumbo
begin
inherited;
if dofilter and not(ord(Key) in [8, 13, 27]) then // BackSpace, Enter, ESC
begin
FChar := Key;
// if (items.Count <> 0) and not droppeddown then
SendMessage(Handle, CB_SHOWDROPDOWN, 1, 0);
// something matched -> dropdown combo to display results
end;
if dofilter and (ord(Key) = 8) then
FChar := Key;
end;
procedure TSmartComboBox.CloseUp;
// ugly workaround for some wierd combobox/modified code interactions
// var
// x: string;
begin
if dofilter then
begin
if (items.Count = 1) and (itemindex = 0) then
text := items[itemindex]
else if ((text <> '') and (itemindex <> -1) and (text <> items[itemindex])) or
((text = '') and (itemindex = 0)) then
begin
storeditemindex := itemindex;
{
// jsf3rd - 사용자 입력 후 콤보선택 시 버그
x := text;
itemindex := items.indexof(text);
if itemindex = -1 then
text := x;
}
end
else
storeditemindex := -1;
end;
inherited;
end;
procedure TSmartComboBox.Click;
// ugly workaround for some weird combobox/modified code interactions
begin
if dofilter then
begin
if storeditemindex <> -1 then
itemindex := storeditemindex;
storeditemindex := -1;
end;
inherited;
end;
procedure TSmartComboBox.InitSmartCombo;
begin
FStoredItems.OnChange := nil;
StoredItems.Assign(items);
AutoComplete := False;
FStoredItems.OnChange := StoredItemsChange;
dofilter := true;
storeditemindex := -1;
end;
constructor TSmartComboBox.Create(AOwner: TComponent);
begin
inherited;
FStoredItems := TStringList.Create;
dofilter := False;
end;
destructor TSmartComboBox.Destroy;
begin
FStoredItems.Free;
inherited;
end;
procedure TSmartComboBox.CNCommand(var AMessage: TWMCommand);
begin
// we have to process everything from our ancestor
inherited;
if FChar = #0 then
Exit;
// if we received the CBN_EDITUPDATE notification
if (AMessage.NotifyCode = CBN_EDITUPDATE) and dofilter then
begin
// fill the items with the matches
FilterItems;
end;
FChar := #0;
end;
procedure TSmartComboBox.FilterItems;
var
I: integer;
Selection: TSelection;
begin
// store the current combo edit selection
SendMessage(Handle, CB_GETEDITSEL, WPARAM(@Selection.StartPos), LPARAM(@Selection.EndPos));
// begin with the items update
items.BeginUpdate;
try
// if the combo edit is not empty, then clear the items
// and search through the FStoredItems
if text <> '' then
begin
// clear all items
items.Clear;
// iterate through all of them
for I := 0 to FStoredItems.Count - 1 do
begin
// check if the current one contains the text in edit, case insensitive
if (Pos(uppercase(text), uppercase(FStoredItems[I])) > 0) then
begin
// and if so, then add it to the items
items.Add(FStoredItems[I]);
end;
end;
end
else
begin
// else the combo edit is empty
// so then we'll use all what we have in the FStoredItems
items.Assign(FStoredItems);
end;
finally
// finish the items update
items.EndUpdate;
end;
// and restore the last combo edit selection
SendMessage(Handle, CB_SETEDITSEL, 0, MakeLParam(Selection.StartPos, Selection.EndPos));
end;
procedure TSmartComboBox.StoredItemsChange(Sender: TObject);
begin
if Assigned(FStoredItems) then
FilterItems;
end;
procedure TSmartComboBox.SetStoredItems(const Value: TStringList);
begin
if Assigned(FStoredItems) then
FStoredItems.Assign(Value)
else
FStoredItems := Value;
end;
end.
|
unit SomeFunction;
interface
uses
Classes;
const DirecName:array[1..4]of string=
('Iron','Boron','Temperature','Thickness');
ShortDirecName:array[1..4]of string=('Fe','B','T','d');
FileHeader='nFsrh nFBsrh dnsrh nF nFB dn';
function EditString(str:string):string;
function NumberToString(Number:double;DigitNumber:word=4):string;
function SubDirectoryName(Number1,Number2:word):string;
function SubDirectorySault(Number1,Number2:word):string;
function DataFileHeader(Number1,Number2:word):string;
function MatrixFileHeader(Number1:word):string;
function DataLabel(Number1,Number2:word):string;
function DataStringConvert(Souce:string):string;
function DataStringConvertNew(Souce:string;StartPosition:word=0):string;
function PartOfDataFileName(Key:string):string;
function DataFileName(Number1,Number2:word;Key1,Key2:string):string;
function MatrixFileName(Number1:word;Key1:string):string;
procedure KeysAndStringListToStringList(Key:string;Souce,Target:TStringList);
function LogKey(Key:string):string;
implementation
uses
StrUtils, SysUtils, OlegFunction, Math;
function EditString(str:string):string;
begin
try
if StrToFloat(str)<1 then
begin
Result:=IntToStr(Round(1e6*StrToFloat(str)));
Exit;
end;
finally
end;
Result:=AnsiReplaceStr(str,'.','p');
Result:=AnsiReplaceStr(Result,'+','');
while AnsiPos ('0E', Result)>5 do
Result:=AnsiReplaceStr(Result,'0E','E');
while AnsiPos ('0e', Result)>5 do
Result:=AnsiReplaceStr(Result,'0e','e');
end;
function NumberToString(Number: double; DigitNumber: word): string;
begin
Result:=LowerCase(floattostrF(Number,ffExponent,DigitNumber,2));
Result:=EditString(Result);
end;
function SubDirectorySault(Number1,Number2:word):string;
begin
case Number1 of
1:if Number2=1
then Result:=ShortDirecName[2]
else Result:=ShortDirecName[3];
2:if Number2=1
then Result:=ShortDirecName[1]
else Result:=ShortDirecName[3];
else if Number2=1
then Result:=ShortDirecName[1]
else Result:=ShortDirecName[2];
end;
end;
function SubDirectoryName(Number1,Number2:word):string;
begin
case Number1 of
1:if Number2=1 then Result:=DirecName[2] else Result:=DirecName[3];
2:if Number2=1 then Result:=DirecName[1] else Result:=DirecName[3];
else if Number2=1 then Result:=DirecName[1] else Result:=DirecName[2];
end;
end;
function DataLabel(Number1,Number2:word):string;
begin
case Number1 of
1:if Number2=1 then Result:=ShortDirecName[3] else Result:=ShortDirecName[2];
2:if Number2=1 then Result:=ShortDirecName[3] else Result:=ShortDirecName[1];
else if Number2=1 then Result:=ShortDirecName[2] else Result:=ShortDirecName[1];
end;
end;
function DataFileHeader(Number1,Number2:word):string;
begin
Result:=DataLabel(Number1,Number2)+' '+FileHeader;
// case Number1 of
// 1:if Number2=1 then Result:=ShortDirecName[3] else Result:=ShortDirecName[2];
// 2:if Number2=1 then Result:=ShortDirecName[3] else Result:=ShortDirecName[1];
// else if Number2=1 then Result:=ShortDirecName[2] else Result:=ShortDirecName[1];
// end;
// Result:=Result+' '+FileHeader;
end;
function MatrixFileHeader(Number1:word):string;
begin
case Number1 of
1:Result:=ShortDirecName[2]+' '+ShortDirecName[3];
2:Result:=ShortDirecName[1]+' '+ShortDirecName[3];
else Result:=ShortDirecName[1]+' '+ShortDirecName[2];
end;
Result:=Result+' '+FileHeader;
end;
function DataStringConvert(Souce:string):string;
var nFe,nFeSRH,nFeB,nFeBSRH:double;
begin
nFe:=FloatDataFromRow(Souce,1);
nFeSRH:=FloatDataFromRow(Souce,2);
nFeB:=FloatDataFromRow(Souce,3);
nFeBSRH:=FloatDataFromRow(Souce,4);
Result:=StringDataFromRow(Souce,2)+' '
+StringDataFromRow(Souce,4)+' '
+FloatToStrF(nFeSRH-nFeBSRH,ffExponent,10,2)+' '
+StringDataFromRow(Souce,1)+' '
+StringDataFromRow(Souce,3)+' '
+FloatToStrF(nFe-nFeB,ffExponent,10,2);
end;
function DataStringConvertNew(Souce:string;StartPosition:word=0):string;
var nFe,nFeSRH,nFeB,nFeBSRH:double;
i:byte;
begin
nFe:=FloatDataFromRow(Souce,1+StartPosition);
nFeSRH:=FloatDataFromRow(Souce,2+StartPosition);
nFeB:=FloatDataFromRow(Souce,3+StartPosition);
nFeBSRH:=FloatDataFromRow(Souce,4+StartPosition);
Result:='';
for I := 1 to StartPosition
do Result:=Result+StringDataFromRow(Souce,i)+' ';
Result:=Result
+StringDataFromRow(Souce,2+StartPosition)+' '
+StringDataFromRow(Souce,4+StartPosition)+' '
+FloatToStrF(nFeSRH-nFeBSRH,ffExponent,10,2)+' '
+StringDataFromRow(Souce,1+StartPosition)+' '
+StringDataFromRow(Souce,3+StartPosition)+' '
+FloatToStrF(nFe-nFeB,ffExponent,10,2)+' '
+FloatToStrF(nFeSRH-nFe,ffExponent,10,2)+' '
+FloatToStrF(nFeBSRH-nFeB,ffExponent,10,2);
end;
function PartOfDataFileName(Key:string):string;
begin
if (AnsiPos ('e',Key)>0)or(AnsiPos ('E',Key)>0)
then Result:=Key[1]+Key[3]+AnsiRightStr(Key, 1)
else Result:=Key[2]+Key[3];
end;
function DataFileName(Number1,Number2:word;Key1,Key2:string):string;
begin
Result:=ShortDirecName[Number1]+PartOfDataFileName(Key1);
case Number1 of
1:if Number2=1 then Result:=Result
+ShortDirecName[2]
+PartOfDataFileName(Key2)
+'_'+ShortDirecName[3]
else Result:=Result
+ShortDirecName[3]
+PartOfDataFileName(Key2)
+'_'+ShortDirecName[2];
2:if Number2=1 then Result:=Result
+ShortDirecName[1]
+PartOfDataFileName(Key2)
+'_'+ShortDirecName[3]
else Result:=Result
+ShortDirecName[3]
+PartOfDataFileName(Key2)
+'_'+ShortDirecName[1];
else if Number2=1 then Result:=Result
+ShortDirecName[1]
+PartOfDataFileName(Key2)
+'_'+ShortDirecName[2]
else Result:=Result
+ShortDirecName[2]
+PartOfDataFileName(Key2)
+'_'+ShortDirecName[1];
end;
Result:=Result+'.dat';
end;
function MatrixFileName(Number1:word;Key1:string):string;
begin
Result:=ShortDirecName[Number1]+PartOfDataFileName(Key1)
+'_';
case Number1 of
1:Result:=Result+ShortDirecName[2]+ShortDirecName[3];
2:Result:=Result+ShortDirecName[1]+ShortDirecName[3];
else Result:=Result+ShortDirecName[1]+ShortDirecName[2];
end;
Result:=Result+'.dat';
end;
function LogKey(Key:string):string;
begin
if ((AnsiPos ('e',Key)>0)or(AnsiPos ('E',Key)>0))
then
begin
if (strtofloat(Key)>1)
then Result:=FloatToStrF(Log10(strtofloat(Key)), ffExponent, 10, 2)
else Result:=inttostr( Round(strtofloat(Key)*1e6))
end
else Result:=Key;
// if ((AnsiPos ('e',Key)>0)or(AnsiPos ('E',Key)>0))
// and (strtofloat(Key)>1)
// then Result:=FloatToStrF(Log10(strtofloat(Key)), ffExponent, 10, 2)
// else Result:=Key;
end;
procedure KeysAndStringListToStringList(Key:string;Souce,Target:TStringList);
var i:integer;
begin
for I := 0 to Souce.Count - 1 do
Target.Add(Key+' '+LogKey(StringDataFromRow(Souce[i],1))
+' '+DeleteStringDataFromRow(Souce[i],1));
end;
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, rxdbgrid,
Forms, Controls, Graphics, Dialogs, StdCtrls,
DBGrids, Menus, ExtCtrls, DbCtrls, db, rxdbverticalgrid, rxmemds;
type
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
CheckBox2: TCheckBox;
CheckGroup1: TCheckGroup;
dsData: TDataSource;
ImageList1: TImageList;
MenuItem1: TMenuItem;
MenuItem10: TMenuItem;
MenuItem11: TMenuItem;
MenuItem12: TMenuItem;
MenuItem2: TMenuItem;
MenuItem3: TMenuItem;
MenuItem4: TMenuItem;
MenuItem5: TMenuItem;
MenuItem6: TMenuItem;
MenuItem7: TMenuItem;
MenuItem8: TMenuItem;
MenuItem9: TMenuItem;
Panel1: TPanel;
PopupMenu1: TPopupMenu;
PopupMenu2: TPopupMenu;
PopupMenu3: TPopupMenu;
RadioGroup1: TRadioGroup;
rxDataCREATE_USER_DATE: TDateTimeField;
rxDataCREATE_USER_NAME: TStringField;
rxDataTB_CLEINT_CODE: TLongintField;
rxDataTB_CLEINT_MEMO: TMemoField;
rxDataTB_CLEINT_TYPE: TLongintField;
rxDataTB_CLIENT_EMAIL: TStringField;
rxDataTB_CLIENT_ID: TAutoIncField;
rxDataTB_CLIENT_IMAGE: TBlobField;
rxDataTB_CLIENT_INN: TStringField;
rxDataTB_CLIENT_NAME: TStringField;
rxDataTB_CLIENT_PHONE: TStringField;
rxDataVIP: TBooleanField;
RxDBGrid1: TRxDBGrid;
RxDBVerticalGrid1: TRxDBVerticalGrid;
rxData: TRxMemoryData;
Splitter1: TSplitter;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure CheckBox1Change(Sender: TObject);
procedure CheckGroup1ItemClick(Sender: TObject; Index: integer);
procedure FormCreate(Sender: TObject);
private
procedure FillDataBase;
public
end;
var
Form1: TForm1;
implementation
uses LazUTF8, LazFileUtils;
{$R *.lfm}
{ TForm1 }
procedure TForm1.FormCreate(Sender: TObject);
begin
FillDataBase;
CheckBox2.Checked:=RxDBVerticalGrid1.Rows[11].ShowBlobImagesAndMemo;
CheckGroup1.OnItemClick:=nil;
CheckGroup1.Checked[0]:=rxvgFixedVertLine in RxDBVerticalGrid1.Options;
CheckGroup1.Checked[1]:=rxvgFixedHorzLine in RxDBVerticalGrid1.Options;
CheckGroup1.Checked[2]:=rxvgVertLine in RxDBVerticalGrid1.Options;
CheckGroup1.Checked[3]:=rxvgHorzLine in RxDBVerticalGrid1.Options;
CheckGroup1.Checked[4]:=rxvgRowSelect in RxDBVerticalGrid1.Options;
CheckGroup1.Checked[5]:=rxvgAlwaysShowEditor in RxDBVerticalGrid1.Options;
CheckGroup1.Checked[6]:=rxvgThumbTracking in RxDBVerticalGrid1.Options;
CheckGroup1.Checked[7]:=rxvgDblClickAutoSize in RxDBVerticalGrid1.Options;
CheckGroup1.Checked[8]:=rxvgSmoothScroll in RxDBVerticalGrid1.Options;
CheckGroup1.Checked[9]:=rxvgHeaderHotTracking in RxDBVerticalGrid1.Options;
CheckGroup1.Checked[10]:=rxvgHeaderPushedLook in RxDBVerticalGrid1.Options;
CheckGroup1.Checked[11]:=rxvgFixedColSizing in RxDBVerticalGrid1.Options;
CheckGroup1.Checked[12]:=rxvgCellHints in RxDBVerticalGrid1.Options;
CheckGroup1.Checked[13]:=rxvgTruncCellHints in RxDBVerticalGrid1.Options;
CheckGroup1.Checked[14]:=rxvgCellEllipsis in RxDBVerticalGrid1.Options;
CheckGroup1.Checked[15]:=rxvgRowHighlight in RxDBVerticalGrid1.Options;
CheckGroup1.Checked[16]:=rxvgColumnTitle in RxDBVerticalGrid1.Options;
CheckGroup1.OnItemClick:=@CheckGroup1ItemClick;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
RxDBVerticalGrid1.DataSource:=nil;
RxDBGrid1.DataSource:=nil;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
RxDBVerticalGrid1.DataSource:=dsData;
RxDBGrid1.DataSource:=dsData;
end;
procedure TForm1.CheckBox1Change(Sender: TObject);
begin
case RadioGroup1.ItemIndex of
0:RxDBVerticalGrid1.Rows[11].Alignment:=taLeftJustify;
1:RxDBVerticalGrid1.Rows[11].Alignment:=taRightJustify;
2:RxDBVerticalGrid1.Rows[11].Alignment:=taCenter;
end;
RxDBVerticalGrid1.Rows[11].ShowBlobImagesAndMemo:=CheckBox2.Checked;
RxDBVerticalGrid1.Rows[12].ShowBlobImagesAndMemo:=CheckBox2.Checked;
end;
procedure TForm1.CheckGroup1ItemClick(Sender: TObject; Index: integer);
begin
if CheckGroup1.Checked[0] then
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options + [rxvgFixedVertLine]
else
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options - [rxvgFixedVertLine]
;
if CheckGroup1.Checked[1] then
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options + [rxvgFixedHorzLine]
else
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options - [rxvgFixedHorzLine];
if CheckGroup1.Checked[2] then
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options + [rxvgVertLine]
else
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options - [rxvgVertLine];
if CheckGroup1.Checked[3] then
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options + [rxvgHorzLine]
else
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options - [rxvgHorzLine];
if CheckGroup1.Checked[4] then
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options + [rxvgRowSelect]
else
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options - [rxvgRowSelect];
if CheckGroup1.Checked[5] then
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options + [rxvgAlwaysShowEditor]
else
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options - [rxvgAlwaysShowEditor];
if CheckGroup1.Checked[6] then
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options + [rxvgThumbTracking]
else
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options - [rxvgThumbTracking];
if CheckGroup1.Checked[7] then
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options + [rxvgDblClickAutoSize]
else
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options - [rxvgDblClickAutoSize];
if CheckGroup1.Checked[8] then
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options + [rxvgSmoothScroll]
else
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options - [rxvgSmoothScroll];
if CheckGroup1.Checked[9] then
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options + [rxvgHeaderHotTracking]
else
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options - [rxvgHeaderHotTracking];
if CheckGroup1.Checked[10] then
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options + [rxvgHeaderPushedLook]
else
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options - [rxvgHeaderPushedLook];
if CheckGroup1.Checked[11] then
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options + [rxvgFixedColSizing]
else
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options - [rxvgFixedColSizing];
if CheckGroup1.Checked[12] then
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options + [rxvgCellHints]
else
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options - [rxvgCellHints];
if CheckGroup1.Checked[13] then
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options + [rxvgTruncCellHints]
else
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options - [rxvgTruncCellHints];
if CheckGroup1.Checked[14] then
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options + [rxvgCellEllipsis]
else
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options - [rxvgCellEllipsis];
if CheckGroup1.Checked[15] then
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options + [rxvgRowHighlight]
else
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options - [rxvgRowHighlight];
if CheckGroup1.Checked[16] then
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options + [rxvgColumnTitle]
else
RxDBVerticalGrid1.Options:=RxDBVerticalGrid1.Options - [rxvgColumnTitle];
end;
procedure TForm1.FillDataBase;
procedure AppendRecord(AType, ACode:Integer; AINN, AName, ADesc, AEmail, APhone, AUser:string; AVip:boolean; AImageName:string);
var
S: String;
begin
rxData.Append;
rxDataTB_CLEINT_TYPE.AsInteger:=AType;
rxDataTB_CLEINT_CODE.AsInteger:=ACode;
rxDataTB_CLIENT_INN.AsString:=AINN;
rxDataTB_CLIENT_NAME.AsString:=AName;
rxDataTB_CLEINT_MEMO.AsString:=ADesc;
rxDataTB_CLIENT_EMAIL.AsString:=AEmail;
rxDataTB_CLIENT_PHONE.AsString:=APhone;
rxDataVIP.AsBoolean:=AVip;
if AImageName <> '' then
begin
S:=AppendPathDelim(ExpandFileName(AppendPathDelim(ExtractFileDir(ParamStr(0))) + '..'+DirectorySeparator + '..'+DirectorySeparator + '..' + DirectorySeparator + '..')) + 'images' + DirectorySeparator;
//ForceDirectories()
// /usr/local/share/lazarus/components/rxnew/demos/RxDBVerticalGrid
// /usr/local/share/lazarus/images
if FileExistsUTF8(S + AImageName) then
rxDataTB_CLIENT_IMAGE.LoadFromFile(S + AImageName);
end;
rxDataCREATE_USER_NAME.AsString:=AUser;
rxDataCREATE_USER_DATE.AsDateTime:=Now + (200-Random * 100);
rxData.Post;
end;
begin
rxData.Open;
AppendRecord(1, 1, '01000100101', 'JSC "BOOT"', 'Описание'#13'Строка 2'#13'Строка 3', 'test1@email.com', '5(555)-557-88-77', 'alexs', true, 'splash_logo.png');
AppendRecord(2, 2, '02000100101', 'Wikimedia Foundation, Inc.', 'Описание', 'test2@email.com', '5(555)-557-88-77', 'boss', false, 'splash_logo.xpm');
AppendRecord(3, 3, '03000100101', 'LLC Pilot ', 'Описание', 'test3@email.com', '5(555)-557-88-77', 'master', false, 'powered_by.png');
AppendRecord(4, 4, '04000100101', 'Pilot, OOO', 'Описание', 'test4@email.com', '5(555)-557-88-77', 'onegin', false, 'folder.png');
AppendRecord(5, 5, '05000100101', 'JSC "MS"', 'Описание', 'test5@email.com', '5(555)-557-88-77', 'alfred', false, 'splash_source'+DirectorySeparator + 'cheetah.jpg');
AppendRecord(6, 11, '06000100101', 'JSC "AA"', 'Описание', 'test6@email.com', '5(555)-557-88-77', 'anna', false, 'mimetypes'+DirectorySeparator + 'text-lazarus-project-information.png');
AppendRecord(7, 12, '07000100101', 'JSC "BBBB"', 'Описание', 'test7@email.com', '5(555)-557-88-77', 'tux', false, 'splash_source'+DirectorySeparator + 'paw.png');
AppendRecord(8, 13, '08000100101', 'JSC "CCCC"', 'Описание', 'test8@email.com', '5(555)-557-88-77', 'x-man', false, '');
AppendRecord(9, 14, '09000100101', 'JSC "DDD"', 'Описание', 'test9@email.com', '5(555)-557-88-77', 'arny', false, '');
AppendRecord(10, 15, '101000200101', 'JSC "EEEE"', 'Описание', 'test10@email.com', '5(555)-557-88-77', 'andy', false, '');
rxData.First;
end;
end.
|
unit rhlJenkins3;
interface
uses
rhlCore;
type
{ TrhlJenkins3 }
TrhlJenkins3 = class(TrhlHash)
private
m_hash: DWord;
protected
procedure UpdateBytes(const ABuffer; ASize: LongWord); override;
public
constructor Create; override;
procedure Init; override;
procedure Final(var ADigest); override;
end;
implementation
{ TrhlJenkins3 }
procedure TrhlJenkins3.UpdateBytes(const ABuffer; ASize: LongWord);
var
a_data: array[0..0] of Byte absolute ABuffer;
a, b, c: DWord;
ci: Integer;
begin
if (ASize = 0) then
begin
m_hash := 0;
Exit;
end;
a := $deadbeef + ASize;
b := a;
c := a;
ci := 0;
while ASize > 12 do
begin
Inc(a, a_data[ci+0] or a_data[ci+1] shl 8 or a_data[ci+2] shl 16 or a_data[ci+3] shl 24);
Inc(b, a_data[ci+4] or a_data[ci+5] shl 8 or a_data[ci+6] shl 16 or a_data[ci+7] shl 24);
Inc(c, a_data[ci+8] or a_data[ci+9] shl 8 or a_data[ci+10] shl 16 or a_data[ci+11] shl 24);
Dec(a, c);
a := a xor RolDWord(c, 4);
Inc(c, b);
Dec(b, a);
b := b xor RolDWord(a, 6);
Inc(a, c);
Dec(c, b);
c := c xor RolDWord(b, 8);
Inc(b, a);
Dec(a, c);
a := a xor RolDWord(c, 16);
Inc(c, b);
Dec(b, a);
b := b xor RolDWord(a, 19);
Inc(a, c);
Dec(c, b);
c := c xor RolDWord(b, 4);
Inc(b, a);
Inc(ci, 12);
Dec(ASize, 12);
end;
case ASize of
4..12: Inc(a, a_data[ci+0] or a_data[ci+1] shl 8 or a_data[ci+2] shl 16 or a_data[ci+3] shl 24);
3: Inc(a, a_data[ci+0] or a_data[ci+1] shl 8 or a_data[ci+2] shl 16);
2: Inc(a, a_data[ci+0] or a_data[ci+1] shl 8);
1: Inc(a, a_data[ci+0]);
end;
case ASize of
8..12: Inc(b, a_data[ci+4] or a_data[ci+5] shl 8 or a_data[ci+6] shl 16 or a_data[ci+7] shl 24);
7: Inc(b, a_data[ci+4] or a_data[ci+5] shl 8 or a_data[ci+6] shl 16);
6: Inc(b, a_data[ci+4] or a_data[ci+5] shl 8);
5: Inc(b, a_data[ci+4]);
end;
case ASize of
12: Inc(c, a_data[ci+8] or a_data[ci+9] shl 8 or a_data[ci+10] shl 16 or a_data[ci+11] shl 24);
11: Inc(c, a_data[ci+8] or a_data[ci+9] shl 8 or a_data[ci+10] shl 16);
10: Inc(c, a_data[ci+8] or a_data[ci+9] shl 8);
9: Inc(c, a_data[ci+8]);
end;
c := c xor b;
c := c - RolDWord(b, 14);
a := a xor c;
a := a - RolDWord(c, 11);
b := b xor a;
b := b - RolDWord(a, 25);
c := c xor b;
c := c - RolDWord(b, 16);
a := a xor c;
a := a - RolDWord(c, 4);;
b := b xor a;
b := b - RolDWord(a, 14);
c := c xor b;
c := c - RolDWord(b, 24);
m_hash := c;
end;
constructor TrhlJenkins3.Create;
begin
HashSize := 4;
BlockSize := 12;
end;
procedure TrhlJenkins3.Init;
begin
inherited Init;
m_hash := 0;
end;
procedure TrhlJenkins3.Final(var ADigest);
begin
Move(m_hash, ADigest, 4);
end;
end.
|
unit uRegistroBD;
interface
uses
classes,Contnrs, IBQuery,SqlExpr, SysUtils,
uRegistro;
type
TRegistroBD = class(TObject)
private
teste : String;
protected
Qry:TIBQuery;
public
function Inserir (const oRegistro: TRegistro) : Boolean; virtual; abstract;
function Alterar (const oRegistro: TRegistro) : Boolean; virtual; abstract;
function Deletar (const oRegistro: TRegistro) : Boolean; virtual; abstract;
function Procurar (const oRegistro: TRegistro) : TRegistro; virtual; abstract;
function Todos () : TObjectList; virtual; abstract;
function GeraId (Gerador: string) : Integer;
constructor create;
destructor destroy();
end;
Implementation
{ TRegistroBD }
constructor TRegistroBD.create;
begin
Qry := TIBQuery.Create(nil);
end;
destructor TRegistroBD.destroy;
begin
Qry.Close;
Qry.Free;
Qry := nil;
end;
function TRegistroBD.GeraId(Gerador: string): Integer;
begin
result := 0;
Qry.SQL.Clear;
Qry.SQL.Add('SELECT GEN_ID('+GERADOR+',1) as ID FROM rdb$database');
try
Qry.Open;
result := Qry.FieldByName('ID').AsInteger;
except
on e:Exception do begin
Qry.Close;
Qry.Free;
raise exception.Create('Gerador inexistente: ' + Gerador);
end;
end;
Qry.Close;
end;
end.
|
{****************************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 2000, 2001 Borland Software Corporation }
{ }
{****************************************************************}
unit ComApp;
interface
uses
ComObj, ActiveX, WebLib, StdVCL, ComHTTP, Classes, Windows, Forms;
type
TComWebAppImpl = class(TComObject, IWebBroker)
protected
procedure HandleRequest(const Request: IWebRequest); safecall;
{ Protected declarations }
end;
{ TThreadedClassFactory }
TThreadedClassFactory = class(TComObjectFactory, IClassFactory)
protected
function CreateInstance(const UnkOuter: IUnknown; const IID: TGUID;
out Obj): HResult; stdcall;
function DoCreateInstance(const UnkOuter: IUnknown; const IID: TGUID;
out Obj): HResult; stdcall;
end;
TWebAppAutoObjectFactory = class(TThreadedClassFactory)
public
procedure UpdateRegistry(Register: Boolean); override;
constructor Create(
const ClassID: TGUID; const ClassName, Description: string);
end;
{ TApartmentThread }
TApartmentThread = class(TThread)
private
FClassFactory: TThreadedClassFactory;
FUnkOuter: IUnknown;
FIID: TGuid;
FSemaphore: THandle;
FStream: Pointer;
FCreateResult: HResult;
protected
procedure Execute; override;
public
constructor Create(ClassFactory: TThreadedClassFactory; UnkOuter: IUnknown; IID: TGuid);
destructor Destroy; override;
property Semaphore: THandle read FSemaphore;
property CreateResult: HResult read FCreateResult;
property ObjStream: Pointer read FStream;
end;
var
FComWebRequestHandler: TCOMWebRequestHandler;
implementation
uses ComServ, SysUtils, WebCat, WebReq, WebCntxt;
function ComWebRequestHandler: TWebRequestHandler;
begin
if not Assigned(FComWebRequestHandler) then
FComWebRequestHandler := TCOMWebRequestHandler.Create(nil);
Result := FComWebRequestHandler;
end;
procedure TComWebAppImpl.HandleRequest(const Request: IWebRequest);
begin
TComWebRequestHandler(ComWebRequestHandler).Run(Request);
end;
constructor TWebAppAutoObjectFactory.Create(const ClassID: TGUID;
const ClassName, Description: string);
begin
inherited Create(ComServ.ComServer, TComWebAppImpl, ClassID, ClassName, Description,
ciMultiInstance, tmApartment);
end;
procedure TWebAppAutoObjectFactory.UpdateRegistry(Register: Boolean);
var
CatReg: ICatRegister;
Rslt: HResult;
CatInfo: TCATEGORYINFO;
Description: string;
SClassID: string;
begin
if Register then
Inherited UpdateRegistry(Register);
Rslt := CoCreateInstance(CLSID_StdComponentCategoryMgr, nil,
CLSCTX_INPROC_SERVER, ICatRegister, CatReg);
SClassID := GUIDToString(ClassID);
if Succeeded(Rslt) then
begin
if Register then
begin
CatInfo.catid := CATID_WebAppServer;
CatInfo.lcid := $0409;
StringToWideChar(Web_CatDesc, CatInfo.szDescription,
Length(Web_CatDesc) + 1);
CatReg.RegisterCategories(1, @CatInfo);
CatReg.RegisterClassImplCategories(ClassID, 1, @CATID_WebAppServer);
end else
begin
// No ole check here. Win98 returns an error code if already unregistered
CatReg.UnRegisterClassImplCategories(ClassID, 1, @CATID_WebAppServer);
DeleteRegKey(Format(SCatImplBaseKey, [SClassID]));
end;
end else
begin
if Register then
begin
CreateRegKey('Component Categories\' + GUIDToString(CATID_WebAppServer), '409', Web_CatDesc);
CreateRegKey(Format(SCatImplKey, [SClassID, GUIDToString(CATID_WebAppServer)]), '', '');
end else
begin
DeleteRegKey(Format(SCatImplKey, [SClassID, GUIDToString(CATID_WebAppServer)]));
DeleteRegKey(Format(SCatImplBaseKey, [SClassID]));
end;
end;
if not Register then
// Unregister class after category unregistration. Win98's UnRegisterClassImplCategories
// reports an error if the class is not found.
Inherited UpdateRegistry(Register);
if Register then
begin
Description := GetRegStringValue('CLSID\' + SClassID, '');
CreateRegKey('AppID\' + SClassID, '', Description);
CreateRegKey('CLSID\' + SClassID, 'AppID', SClassID);
end else
DeleteRegKey('AppID\' + SClassID);
end;
{ TThreadedAutoObjectFactory }
function TThreadedClassFactory.DoCreateInstance(const UnkOuter: IUnknown;
const IID: TGUID; out Obj): HResult; stdcall;
begin
Result := inherited CreateInstance(UnkOuter, IID, Obj);
end;
function TThreadedClassFactory.CreateInstance(const UnkOuter: IUnknown;
const IID: TGUID; out Obj): HResult; stdcall;
begin
with TApartmentThread.Create(Self, UnkOuter, IID) do
begin
if WaitForSingleObject(Semaphore, INFINITE) = WAIT_OBJECT_0 then
begin
Result := CreateResult;
if Result <> S_OK then Exit;
Result := CoGetInterfaceAndReleaseStream(IStream(ObjStream), IID, Obj);
end else
Result := E_FAIL
end;
end;
{ TApartmentThread }
constructor TApartmentThread.Create(ClassFactory: TThreadedClassFactory;
UnkOuter: IUnknown; IID: TGuid);
begin
FClassFactory := ClassFactory;
FUnkOuter := UnkOuter;
FIID := IID;
FSemaphore := CreateSemaphore(nil, 0, 1, nil);
FreeOnTerminate := True;
inherited Create(False);
end;
destructor TApartmentThread.Destroy;
begin
FUnkOuter := nil;
CloseHandle(FSemaphore);
inherited Destroy;
Application.ProcessMessages; {???}
end;
procedure TApartmentThread.Execute;
var
msg: TMsg;
Unk: IUnknown;
begin
CoInitialize(nil);
FCreateResult := FClassFactory.DoCreateInstance(FUnkOuter, FIID, Unk);
if FCreateResult = S_OK then
CoMarshalInterThreadInterfaceInStream(FIID, Unk, IStream(FStream));
ReleaseSemaphore(FSemaphore, 1, nil);
if FCreateResult = S_OK then
while GetMessage(msg, 0, 0, 0) do
begin
DispatchMessage(msg);
Unk._AddRef;
if Unk._Release = 1 then break;
end;
Unk := nil;
CoUninitialize;
end;
initialization
WebReq.WebRequestHandlerProc := ComWebRequestHandler;
finalization
FreeAndNil(FComWebRequestHandler);
end.
|
unit fODChangeUnreleasedRenew;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, ORCtrls, fAutoSz, uOrders, ORFn, ORDtTm, rOrders,
VA508AccessibilityManager, rODBase, rODMeds;
type
TfrmODChangeUnreleasedRenew = class(TFrmAutoSz)
memOrder: TCaptionMemo;
Panel1: TPanel;
btnOK: TButton;
btnCancel: TButton;
Panel2: TPanel;
edtRefill: TCaptionEdit;
lblRefill: TLabel;
lblPickUp: TLabel;
cboPickup: TORComboBox;
Panel3: TPanel;
Label1: TLabel;
Label2: TLabel;
txtStart: TORDateBox;
txtStop: TORDateBox;
procedure FormCreate(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure btnOKClick(Sender: TObject);
private
OKPressed: boolean;
FCategory: integer;
public
{ Public declarations }
end;
procedure ExecuteChangeRenewedOrder(const AnID: string; var param1, param2: string; Category: integer; AnEvent: TOrderDelayEvent);
implementation
{$R *.dfm}
var
MaxRefills: Integer;
const
TX_ERR_REFILL = 'The number of refills must be in the range of 0 through ';
TC_ERR_REFILL = 'Refills';
TC_INVALID_DATE = 'Unable to interpret date/time entry.';
TX_BAD_START = 'The start date is not valid.';
TX_BAD_STOP = 'The stop date is not valid.';
TX_STOPSTART = 'The stop date must be after the start date.';
procedure ExecuteChangeRenewedOrder(const AnID: string; var param1, param2: string; Category: integer; AnEvent: TOrderDelayEvent);
var
frmODChangeUnreleasedRenew: TfrmODChangeUnreleasedRenew;
theText: string;
tmpRefills: integer;
DestList: TList;
HasObject: Boolean;
i: Integer;
Drug, Days, OrID: string;
begin
//Get needed information
DestList := TList.Create();
try
LoadResponses(DestList, 'X' + AnID, HasObject);
for I := 0 to DestList.Count - 1 do begin
if TResponse(DestList.Items[i]).PromptID = 'DRUG' then Drug := TResponse(DestList.Items[i]).IValue
else if TResponse(DestList.Items[i]).PromptID = 'SUPPLY' then Days := TResponse(DestList.Items[i]).IValue
else if TResponse(DestList.Items[i]).PromptID = 'ORDERABLE' then OrID := TResponse(DestList.Items[i]).IValue;
end;
MaxRefills := CalcMaxRefills(Drug, StrToInt(Days), StrToInt(OrID), AnEvent.EventType = 'D');
tmpRefills := 0;
theText := Trim(RetrieveOrderText(AnID));
if Pos('>> RENEW', UpperCase(theText)) = 1 then Delete(theText,1,length('>> RENEW'))
else if Pos('RENEW',UpperCase(theText))= 1 then Delete(theText,1,length('RENEW'));
frmODChangeUnreleasedRenew := TfrmODChangeUnreleasedRenew.Create(Application);
try
frmODChangeUnreleasedRenew.FCategory := Category;
ResizeFormToFont(TForm(frmODChangeUnreleasedRenew));
if Category = 0 then
begin
frmODChangeUnreleasedRenew.Panel3.Visible := False;
tmpRefills := StrToIntDef(param1,0);
frmODChangeUnreleasedRenew.edtRefill.Text := param1;
frmODChangeUnreleasedRenew.cboPickup.SelectByID(param2);
frmODChangeUnreleasedRenew.memOrder.SetTextBuf(PChar(theText));
end
else if Category = 1 then
begin
frmODChangeUnreleasedRenew.Panel2.Visible := false;
frmODChangeUnreleasedRenew.txtStart.Text := param1;
frmODChangeUnreleasedRenew.txtStop.Text := param2;
frmODChangeUnreleasedRenew.memOrder.SetTextBuf(PChar(theText));
end;
frmODChangeUnreleasedRenew.ShowModal;
if frmODChangeUnreleasedRenew.OKPressed then
begin
if Category = 0 then
begin
tmpRefills := StrToIntDef(frmODChangeUnreleasedRenew.edtRefill.Text, tmpRefills);
param1 := IntToStr(tmpRefills);
param2 := frmODChangeUnreleasedRenew.cboPickup.ItemID;
end
else if Category = 1 then
begin
param1 := frmODChangeUnreleasedRenew.txtStart.Text;
param2 := frmODChangeUnreleasedRenew.txtStop.Text;
end;
end;
finally
frmODChangeUnreleasedRenew.Release;
end;
finally
DestList.Free;
end;
end;
procedure TfrmODChangeUnreleasedRenew.FormCreate(Sender: TObject);
begin
inherited;
OKPressed := False;
with cboPickup.Items do
begin
Add('W^at Window');
Add('M^by Mail');
Add('C^in Clinic');
end;
end;
procedure TfrmODChangeUnreleasedRenew.btnCancelClick(Sender: TObject);
begin
inherited;
Close;
end;
procedure TfrmODChangeUnreleasedRenew.btnOKClick(Sender: TObject);
var
NumRefills: Integer;
x, ErrMsg: string;
begin
inherited;
if panel2.Visible then
begin
NumRefills := StrToIntDef(edtRefill.Text, -1);
if (NumRefills < 0) or (NumRefills > MaxRefills) then
begin
InfoBox(TX_ERR_REFILL + IntToStr(MaxRefills), TC_ERR_REFILL, MB_OK);
Exit;
end;
end
else if panel3.Visible then
begin
ErrMsg := '';
txtStart.Validate(x);
if Length(x) > 0 then ErrMsg := ErrMsg + TX_BAD_START + CRLF;
with txtStop do
begin
Validate(x);
if Length(x) > 0 then ErrMsg := ErrMsg + TX_BAD_STOP + CRLF;
if (Length(Text) > 0) and (FMDateTime <= txtStart.FMDateTime)
then ErrMsg := ErrMsg + TX_STOPSTART;
end;
if Length(ErrMsg) > 0 then
begin
InfoBox(ErrMsg, TC_INVALID_DATE, MB_OK);
Exit;
end;
end;
OKPressed := True;
Close;
end;
end.
|
unit u_xpl_vendor_file;
{==============================================================================
UnitName = uxPLVendorFile
UnitDesc = XML Vendor Seed File Management Unit
UnitCopyright = GPL by Clinique / xPL Project
==============================================================================
Version 0.9 : usage of uxPLConst
0.91 : integrated method of RIP TxPLVendorPlugin / redondant with it
0.92 : small fix on the vendor seed file extension when html downloading
0.93 : Changed ancestor of the class from TXMLDocument to nothing to avoid bug
Added error handling when loading the vendor seed file
Added proxy awareness capability
0.94 : Modifications to use u_xml_plugins
1.00 : Dropped usage of DOM and XMLRead, replaced by superobject
}
{$ifdef fpc}
{$mode objfpc}{$H+}
{$endif}
interface
uses Classes
, SysUtils
, uxPLConst
, u_xpl_address
, u_xml_plugins
, u_xpl_folders
, superobject
, superxmlparser
;
type { TxPLVendorSeedFile ====================================================}
TxPLVendorSeedFile = class(TComponent)
private
fFolders : TxPLFolders;
fLocations : TLocationsType;
fPlugins : TPluginsType;
fSchemas : TSchemaCollection;
function GetLocations: TLocationsType;
function GetPlugins: TPluginsType;
function GetSchemas: TSchemaCollection;
public
constructor Create(const aOwner : TComponent ;const aFolders : TxPLFolders); reintroduce;
destructor Destroy; override;
function FileName : string; inline; // File name of the current vendor plugin file
function SchemaFile : string; inline;
function UpdatedTS : TDateTime; // Renamed to avoid conflict with ancestors
function Update(const sLocation : string = K_XPL_VENDOR_SEED_LOCATION) : boolean; // Reloads the seed file from website
function FindDevice(const aAddress : TxPLAddress) : TDeviceType;
function IsValid : boolean;
published
property Locations : TLocationsType read GetLocations;
property Plugins : TPluginsType read GetPlugins;
property Schemas : TSchemaCollection read GetSchemas;
end;
implementation //==============================================================
uses RegExpr
, u_downloader_Indy
, u_xpl_application
;
// TxPLVendorSeedFile =========================================================
constructor TxPLVendorSeedFile.Create(const aOwner : TComponent; const aFolders: TxPLFolders);
begin
inherited Create(aOwner);
fFolders := aFolders;
end;
destructor TxPLVendorSeedFile.Destroy;
begin
if assigned(fLocations) then fLocations.Free;
if assigned(fPlugins) then fPlugins.Free;
if assigned(fSchemas) then fSchemas.Free;
inherited;
end;
function TxPLVendorSeedFile.IsValid : boolean;
begin
Result := Assigned(Locations) and Assigned(Plugins);
end;
function TxPLVendorSeedFile.FileName: string;
begin
result := fFolders.PluginDir + K_XPL_VENDOR_SEED_FILE;
end;
function TxPLVendorSeedFile.SchemaFile : string;
begin
result := fFolders.PluginDir + K_XPL_SCHEMA_COLL_FILE;
end;
function TxPLVendorSeedFile.GetSchemas: TSchemaCollection;
var SO : ISuperObject;
begin
if not Assigned(fSchemas) then begin
if not FileExists(SchemaFile) then
TxPLApplication(Owner).Log(etWarning,'Schema collection file absent, please consider downloading it')
else begin
SO := XMLParseFile(SchemaFile,true);
fSchemas := TSchemaCollection.Create(so, TxPLApplication(Owner).Folders.PluginDir);
end;
end;
Result := fSchemas;
end;
function TxPLVendorSeedFile.GetLocations: TLocationsType;
var SO : ISuperObject;
begin
if not Assigned(fLocations) then begin
if not FileExists(FileName) then
TxPLApplication(Owner).Log(etWarning,'Vendor file absent, please consider updating it')
else begin
SO := XMLParseFile(FileName,true);
fLocations := TLocationsType.Create(so);
end;
end;
Result := fLocations;
end;
function TxPLVendorSeedFile.GetPlugins: TPluginsType;
var SO : ISuperObject;
begin
if not Assigned(fPlugins) then begin
if not FileExists(FileName) then
TxPLApplication(Owner).Log(etWarning,'Vendor file absent, please consider updating it')
else begin
SO := XMLParseFile(FileName,true);
fPlugins := TPluginsType.Create(so, TxPLApplication(Owner).Folders.PluginDir);
end;
end;
Result := fPlugins;
end;
function TxPLVendorSeedFile.UpdatedTS: TDateTime;
var fileDate : integer;
begin
fileDate := FileAge(FileName);
if fileDate > -1 then Result := FileDateToDateTime(filedate)
else Result := 0;
end;
function TxPLVendorSeedFile.Update(const sLocation : string) : boolean;
begin
Result := HTTPDownload(sLocation + '.xml', FileName, xPLApplication.Settings.ProxyServer);
end;
function TxPLVendorSeedFile.FindDevice(const aAddress: TxPLAddress): TDeviceType;
var plug, dev : TCollectionItem;
begin
result := nil;
if not Assigned(Plugins) then exit; // Bug #FS57,#FS72,#FS73
for plug in Plugins do
if TPluginType(plug).Vendor = aAddress.Vendor then
for dev in TPluginType(plug).Devices do
if TDeviceType(dev).Device = aAddress.Device then
result := TDeviceType(dev);
end;
end.
|
unit proc_type_obj_5;
interface
implementation
uses System;
type
TProc = procedure(V: Int32) of object;
TC = class
private
FData: Int32;
procedure SetData(Value: Int32);
end;
procedure TC.SetData(Value: Int32);
begin
FData := Value;
end;
var
obj: TC;
p: TProc;
G: Int32;
procedure Assign(var P: TProc);
begin
p := obj.SetData;
end;
procedure Call(P: TProc);
begin
p(16);
end;
procedure Test;
begin
obj := TC.Create();
Assign(p);
Call(p);
G := obj.FData;
end;
initialization
Test();
finalization
Assert(G = 16);
end. |
unit Blocks;
interface
uses Windows, Classes, DataTypes, SysUtils, RunObjts, uExtMath, IntArrays;
type
pPointer = ^Pointer;
TConversionType = (COLOR_BGR2BGRA, // 0,
COLOR_RGB2RGBA, // 0,
COLOR_BGRA2BGR, // 1,
COLOR_RGBA2RGB, // 1,
COLOR_BGR2RGBA, // 2,
COLOR_RGB2BGRA, // 2,
COLOR_RGBA2BGR, // 3,
COLOR_BGRA2RGB, // 3,
COLOR_BGR2RGB, // 4,
COLOR_RGB2BGR, // 4,
COLOR_BGRA2RGBA, // 5,
COLOR_RGBA2BGRA, // 5,
COLOR_BGR2GRAY, // 6,
COLOR_RGB2GRAY, // 7,
COLOR_GRAY2BGR, // 8,
COLOR_GRAY2RGB, // 8,
COLOR_BGR2HSV, // 40,
COLOR_RGB2HSV, // 41,
COLOR_HSV2BGR, // 54,
COLOR_HSV2RGB // 55
);
TStructureElement = (MORPH_RECT, MORPH_CROSS, MORPH_ELLIPSE);
TInterpolation = (INTER_NEAREST, INTER_LINEAR, INTER_CUBIC, INTER_AREA);
// **************************************************************************//
// Определяем классы для каждой функции библиотеки //
// **************************************************************************//
TFRAMESOURCE = class(TRunObject)
public
sourceName: String;
source: Pointer;
frame: Pointer;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TIMREAD = class(TRunObject)
public
frame: Pointer;
sourceName: String;
code: NativeInt;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TUMIMPORT = class(TRunObject)
public
frame: Pointer;
server: Pointer;
client: Pointer;
chanells: NativeInt;
port: NativeInt;
state: NativeInt;
lastFrame: NativeInt;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TIMSEQREAD = class(TRunObject)
public
fileList: tStringList;
frame: Pointer;
sourceMask: String;
sourcePath: String;
counter: NativeInt;
code: NativeInt;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TIMSHOW = class(TRunObject)
public
windowName: String;
delay: NativeInt;
frame: Pointer;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TCONVERTCOLOR = class(TRunObject)
public
src: Pointer;
dst: Pointer;
code: NativeInt;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TBITWISEAND = class(TRunObject)
public
src1: Pointer;
src2: Pointer;
dst: Pointer;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TBITWISEOR = class(TRunObject)
public
src1: Pointer;
src2: Pointer;
dst: Pointer;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TBITWISENO = class(TRunObject)
public
src: Pointer;
dst: Pointer;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TBITWISEXOR = class(TRunObject)
public
src1: Pointer;
src2: Pointer;
dst: Pointer;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TmatrixMUL = class(TRunObject)
public
src1: Pointer;
src2: Pointer;
dst: Pointer;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TperElementAddWeighted = class(TRunObject)
public
src1: Pointer;
alpha: RealType;
src2: Pointer;
beta: RealType;
dst: Pointer;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TABSDIFF = class(TRunObject)
public
src1: Pointer;
src2: Pointer;
dst: Pointer;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TperElementMUL = class(TRunObject)
public
scale: RealType;
src1: Pointer;
src2: Pointer;
dst: Pointer;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TperElementADD = class(TRunObject)
public
src1: Pointer;
src2: Pointer;
dst: Pointer;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TperElementADDV = class(TRunObject)
public
src: Pointer;
Value: RealType;
dst: Pointer;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TperElementMULV = class(TRunObject)
public
src: Pointer;
Value: RealType;
dst: Pointer;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TTRESHOLD = class(TRunObject)
public
src: Pointer;
dst: Pointer;
Thresh: Double;
Maxval: Double;
codetype: NativeInt;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TADAPTIVETHRESHOLD = class(TRunObject)
public
src: Pointer;
dst: Pointer;
maxValue: RealType;
adaptiveMethod: NativeInt;
ThresholdType: NativeInt;
blocksize: NativeInt;
C: RealType;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TBILATERALFILTER = class(TRunObject)
public
src: Pointer;
dst: Pointer;
d: NativeInt;
SigmaColor: RealType;
SigmaSpace: RealType;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TBLUR = class(TRunObject)
public
src: Pointer;
dst: Pointer;
ksizeX: NativeInt;
ksizeY: NativeInt;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TGAUSSIANBLUR = class(TRunObject)
public
src: Pointer;
dst: Pointer;
ksizeX: NativeInt;
ksizeY: NativeInt;
sigmaX: RealType;
sigmaY: RealType;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TBOXFILTER = class(TRunObject)
public
src: Pointer;
dst: Pointer;
ksizeX: NativeInt;
ksizeY: NativeInt;
anchorX: NativeInt;
anchorY: NativeInt;
normalize: boolean;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TCANNY = class(TRunObject)
public
src: Pointer;
dst: Pointer;
Threshold1: RealType;
Threshold2: RealType;
apertureSize: NativeInt;
L2gradient: boolean;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TCORNERHARRIS = class(TRunObject)
public
src: Pointer;
dst: Pointer;
blocksize: NativeInt;
ksize: NativeInt;
k: RealType;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TDILATE = class(TRunObject)
public
src: Pointer;
dst: Pointer;
ksize: NativeInt;
kshape: NativeInt;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TERODE = class(TRunObject)
public
src: Pointer;
dst: Pointer;
ksize: NativeInt;
kshape: NativeInt;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TROI = class(TRunObject)
public
src: Pointer;
dst: Pointer;
roix: NativeInt;
roiy: NativeInt;
roiw: NativeInt;
roih: NativeInt;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TFLIP = class(TRunObject)
public
src: Pointer;
dst: Pointer;
code: NativeInt;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TROTATE = class(TRunObject)
public
src: Pointer;
dst: Pointer;
code: NativeInt;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TSPLIT = class(TRunObject)
public
src: Pointer;
dst1: Pointer;
dst2: Pointer;
dst3: Pointer;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TINRANGE = class(TRunObject)
public
src: Pointer;
dst: Pointer;
lower: RealType;
upper: RealType;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TMERGE = class(TRunObject)
public
src1: Pointer;
src2: Pointer;
src3: Pointer;
dst: Pointer;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TSOBEL = class(TRunObject)
public
src: Pointer;
dst: Pointer;
dx: NativeInt;
dy: NativeInt;
ksize: NativeInt;
scale: RealType;
delta: RealType;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TSCHARR = class(TRunObject)
public
src: Pointer;
dst: Pointer;
dx: NativeInt;
dy: NativeInt;
scale: RealType;
delta: RealType;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TLAPLACIAN = class(TRunObject)
public
src: Pointer;
dst: Pointer;
ksize: NativeInt;
scale: RealType;
delta: RealType;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TRESIZE = class(TRunObject)
public
src: Pointer;
dst: Pointer;
ksizeX: NativeInt;
ksizeY: NativeInt;
fx: RealType;
fy: RealType;
interpolation: integer;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TCalibrateCamera = class(TRunObject)
public
calibrated: integer;
image: Pointer;
image_points: Pointer;
object_points: Pointer;
dstImage: Pointer;
intrinsic: Pointer;
distCoeffs: Pointer;
numCornersHor: NativeInt;
numCornersVer: NativeInt;
fileName: String;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TLoadCalibrationParameters = class(TRunObject)
public
dir : String;
intrinsic: Pointer;
distCoeffs: Pointer;
fileName: String;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TUndistotImage = class(TRunObject)
public
intrinsic: Pointer;
distCoeffs: Pointer;
src: Pointer;
dst: Pointer;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TwarpPerspective = class(TRunObject)
public
src: Pointer;
dst: Pointer;
srcPts: Array [1 .. 8] of RealType;
dstPts: Array [1 .. 8] of RealType;
dsizeX: NativeInt;
dsizeY: NativeInt;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TFloodFill = class(TRunObject)
public
src: Pointer;
dst: Pointer;
px: NativeInt;
py: NativeInt;
ch1: NativeInt;
ch2: NativeInt;
ch3: NativeInt;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TFindContous = class(TRunObject)
public
srcFrame: Pointer;
contours: Pointer;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
end;
TSelectContour = class(TRunObject)
public
srcFrame: Pointer;
dstFrame: Pointer;
contours: Pointer;
contour: Pointer;
index: NativeInt;
width: NativeInt;
red: NativeInt;
green: NativeInt;
blue: NativeInt;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TSelectContourArea = class(TRunObject)
public
inputContours: Pointer;
outputContours: Pointer;
minArea: Double;
maxArea: Double;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TFindSign = class(TRunObject)
public
templFrame: Pointer;
templContour: Pointer;
frame: Pointer;
contours: Pointer;
normalizedContourSizeX: NativeInt;
normalizedContourSizeY: NativeInt;
useHull: NativeInt;
draw: NativeInt;
minCorrelation: RealType;
numFound: NativeInt;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TDetectLanes = class(TRunObject)
public
binaryinput: Pointer;
drawinput: Pointer;
rd: NativeInt;
ld: NativeInt;
numHorHist: NativeInt;
wheel: NativeInt;
roi: NativeInt;
leftPointCount: NativeInt;
rightPointCount: NativeInt;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
TCountContours = class(TRunObject)
public
inputContours: Pointer;
count: NativeInt;
function InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt; override;
function RunFunc(var at, h: RealType; Action: integer): NativeInt; override;
function GetParamID(const ParamName: string; var DataType: TDataType;
var IsConst: boolean): NativeInt; override;
end;
// **************************************************************************//
// Определяем ссылки для каждой функции библиотеки //
// **************************************************************************//
var
createHandledWindow: function(windowName: AnsiString): Pointer; cdecl;
getWindowHandle: function(windowName: AnsiString): Pointer; cdecl;
retrieveImage: function(source: Pointer; frame: pPointer): integer; cdecl;
releaseSimMat: function(source: pPointer): integer; cdecl;
releaseSourse: function(source: Pointer): integer; cdecl;
destroyWindowByName: function(windowName: AnsiString): integer; cdecl;
destroyAllWindows: function(err: AnsiString): integer; cdecl;
openVideoSource: function(source: pPointer; windowName: AnsiString)
: integer; cdecl;
openImage: function(frame: pPointer; windowName: AnsiString; code: integer)
: integer; cdecl;
showFrame: function(source: Pointer; delay: integer; windowName: AnsiString)
: integer; cdecl;
sim_convertColor: function(src: Pointer; dst: pPointer; code: integer)
: integer; cdecl;
bitwiseAND: function(src1: Pointer; src2: Pointer; dst: pPointer)
: integer; cdecl;
bitwiseOR: function(src1: Pointer; src2: Pointer; dst: pPointer)
: integer; cdecl;
bitwiseNO: function(src: Pointer; dst: pPointer): integer; cdecl;
bitwiseXOR: function(src1: Pointer; src2: Pointer; dst: pPointer)
: integer; cdecl;
matrixMUL: function(src1: Pointer; src2: Pointer; dst: pPointer)
: integer; cdecl;
perElementAddWeighted: function(src1: Pointer; alpha: RealType; src2: Pointer;
beta: RealType; dst: pPointer): integer; cdecl;
perElementMUL: function(scale: RealType; src1: Pointer; src2: Pointer;
dst: pPointer): integer; cdecl;
absDiff: function(src1: Pointer; src2: Pointer; dst: pPointer)
: integer; cdecl;
perElementADD: function(src1: Pointer; src2: Pointer; dst: pPointer)
: integer; cdecl;
perElementADDV: function(src: Pointer; val: RealType; dst: pPointer)
: integer; cdecl;
perElementMULV: function(src: Pointer; val: RealType; dst: pPointer)
: integer; cdecl;
sim_threshold: function(src: Pointer; dst: pPointer; Thresh: Double;
Maxval: Double; codetype: integer): integer; cdecl;
sim_adaptiveThreshold: function(src: Pointer; dst: pPointer;
maxValue: RealType; adaptiveMethod: integer; ThresholdType: integer;
blocksize: integer; C: RealType): integer; cdecl;
sim_bilateralFilter: function(src: Pointer; dst: Pointer; d: integer;
SigmaColor: RealType; SigmaSpace: RealType): integer; cdecl;
sim_blur: function(src: Pointer; dst: pPointer; ksizeX: integer;
ksizeY: integer): integer; cdecl;
sim_gaussianBlur: function(src: Pointer; dst: pPointer; ksizeX: integer;
ksizeY: integer; sigmaX: RealType; sigmaY: RealType): integer; cdecl;
sim_boxFilter: function(src: Pointer; dst: pPointer; ksizeX: integer;
ksizeY: integer; anchorX: integer; anchorY: integer; normalize: boolean)
: integer; cdecl;
sim_canny: function(src: Pointer; dst: pPointer; Threshold1: RealType;
Threshold2: RealType; apertureSize: integer; L2gradient: boolean)
: integer; cdecl;
sim_cornerHarris: function(src: Pointer; dst: pPointer; blocksize: integer;
ksize: integer; k: RealType): integer; cdecl;
sim_dilate: function(src: Pointer; dst: pPointer; ksize: integer;
kshape: integer): integer; cdecl;
sim_erode: function(src: Pointer; dst: pPointer; ksize: integer;
kshape: integer): integer; cdecl;
sim_roi: function(src: Pointer; dst: pPointer; roix: integer; roiy: integer;
roiw: integer; roih: integer): integer; cdecl;
sim_flip: function(src: Pointer; dst: pPointer; code: integer)
: integer; cdecl;
sim_rotate: function(src: Pointer; dst: pPointer; code: integer)
: integer; cdecl;
sim_split: function(src: Pointer; dst1: pPointer; dst2: pPointer;
dst3: pPointer): integer; cdecl;
sim_inRange: function(src: Pointer; dst: pPointer; lower: RealType;
upper: RealType): integer; cdecl;
sim_merge: function(src1: Pointer; src2: Pointer; src3: Pointer;
dst: pPointer): integer; cdecl;
sim_sobel: function(src: Pointer; dst: pPointer; dx: integer; dy: integer;
ksize: integer; scale: RealType; delta: RealType): integer; cdecl;
sim_scharr: function(src: Pointer; dst: pPointer; dx: integer; dy: integer;
scale: RealType; delta: RealType): integer; cdecl;
sim_laplacian: function(src: Pointer; dst: pPointer; ksize: integer;
scale: RealType; delta: RealType): integer; cdecl;
sim_resize: function(src: Pointer; dst: pPointer; ksizeX: integer;
ksizeY: integer; interpolation: integer): integer; cdecl;
sim_warpPerspective: function(src: Pointer; dst: pPointer; srcPts: Pointer;
dstPts: Pointer; dsizeX: integer; dsizeY: integer): integer; cdecl;
sim_floodFill: function(src: Pointer; dst: pPointer; px: integer; py: integer;
ch1: integer; ch2: integer; ch3: integer): integer; cdecl;
sim_findContours: function(srcImage: Pointer; contours: pPointer)
: integer; cdecl;
sim_selectContour: function(srcImage: Pointer; contours: Pointer;
index: integer; red: integer; green: integer; blue: integer; width: integer;
dstItmage: pPointer; result: pPointer): integer; cdecl;
sim_minMaxAreaContoursFilter: function(src: Pointer; dst: pPointer;
min: Pointer; max: Pointer): integer; cdecl;
sim_countContours: function(src: Pointer; count: Pointer): integer; cdecl;
sim_fidnCalibrationPoints: function(image_points: pPointer;
object_points: pPointer; image: Pointer; dst: pPointer;
numCornersHor: integer; numCornersVer: integer): integer; cdecl;
sim_undistort: function(image: Pointer; imageUndistorted: pPointer;
intrinsic: Pointer; distCoeffs: Pointer): integer; cdecl;
sim_calibrateCamera: function(image_points: Pointer; object_points: Pointer;
image: Pointer; intrinsic: pPointer; distCoeffs: pPointer): integer; cdecl;
sim_saveCalibrationParameters: function(name: AnsiString; intrinsic: Pointer;
distCoeffs: Pointer): integer; cdecl;
sim_loadCalibrationParameters: function(name: AnsiString; intrinsic: pPointer;
distCoeffs: pPointer): integer; cdecl;
sim_findSign: function(templFrame: Pointer; templContour: Pointer;
frame: Pointer; contours: Pointer; normalizedContourSizeX: integer;
normalizedContourSizeY: integer; useHull: NativeInt; draw: NativeInt;
minCorrelation: RealType; numFound: Pointer): integer; cdecl;
sim_detectLanes: function(binaryinput: Pointer; numHorHist: integer;
roi_w: integer; wheel_h: integer; rd: Pointer; ld: Pointer;
drawinput: Pointer; leftPointCount: Pointer; rightPointCount: Pointer):
integer; cdecl;
um_init: function(server_socket: pPointer; client_socket: pPointer;
frame : pPointer; port : integer): integer; cdecl;
um_get_frame: function(socket: Pointer; frame: Pointer): integer; cdecl;
um_release_socket: function(socket: Pointer): Pointer; cdecl;
implementation
uses math, Masks;
procedure SearchInDir(Mask, Dir: string; Subdir: boolean;
var List: tStringList);
var
r: integer;
f: TSearchRec;
begin
if Dir = '' then
Exit;
if Dir[Length(Dir)] <> '\' then
Dir := Dir + '\';
{$I-}
ChDir(Dir);
{$I+}
if IOResult <> 0 then
Exit;
r := FindFirst('*.*', faAnyFile, f);
while r = 0 do
begin
IF ((f.Attr and faDirectory) <> faDirectory) THEN
if (MatchesMask(f.Name, Mask)) or (Mask = '*.*') then
if (f.Name <> '.') and (f.Name <> '..') then
List.Add(ExpandFileName(f.Name));
if (f.Attr and faDirectory) = faDirectory then
if Subdir = True then
begin
if (f.Name <> '.') and (f.Name <> '..') then
begin
SearchInDir(Mask, ExpandFileName(f.Name), Subdir, List);
ChDir(Dir);
end;
end;
r := FindNext(f);
end;
FindClose(f);
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TFRAMESOURCE //////
/// /////////////////////////////////////////////////////////////////////////
function TFRAMESOURCE.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'source') then
begin
result := NativeInt(@sourceName);
DataType := dtString;
end
end
end;
function TFRAMESOURCE.InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TFRAMESOURCE.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
res := openVideoSource(@source, sourceName);
result := 0;
end;
f_GoodStep:
begin
if res = 0 then
begin
res := retrieveImage(source, @frame);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := frame;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@frame);
releaseSourse(source);
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TUMIMPORT //////
/// /////////////////////////////////////////////////////////////////////////
function TUMIMPORT.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'port') then
begin
result := NativeInt(@port);
DataType := dtInteger;
end
end
end;
function TUMIMPORT.InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TUMIMPORT.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
lastFrame := 0;
state := um_init(@server, @client, @frame, port);
result := 0;
end;
f_GoodStep:
begin
if (state = 0) and (lastFrame = 0) then
begin
res := um_get_frame(client, frame);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := frame;
end
else
begin
lastFrame := 1;
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
if state = 0 then
begin
um_release_socket(@server);
um_release_socket(@client);
releaseSimMat(@frame);
end;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TIMREAD //////
/// /////////////////////////////////////////////////////////////////////////
function TIMREAD.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'source') then
begin
result := NativeInt(@sourceName);
DataType := dtString;
end
else if StrEqu(ParamName, 'code') then
begin
result := NativeInt(@code);
DataType := dtInteger;
end
end
end;
function TIMREAD.InfoFunc(Action: integer; aParameter: NativeInt): NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TIMREAD.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
result := 0;
res := 0;
end;
f_GoodStep:
begin
res := openImage(@frame, sourceName, code);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := frame;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@frame);
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TIMSEQREAD //////
/// /////////////////////////////////////////////////////////////////////////
function TIMSEQREAD.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'path') then
begin
result := NativeInt(@sourcePath);
DataType := dtString;
end
else if StrEqu(ParamName, 'mask') then
begin
result := NativeInt(@sourceMask);
DataType := dtString;
end
else if StrEqu(ParamName, 'code') then
begin
result := NativeInt(@code);
DataType := dtInteger;
end
end
end;
function TIMSEQREAD.InfoFunc(Action: integer; aParameter: NativeInt): NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TIMSEQREAD.RunFunc;
var
res, tmp: integer;
begin
result := 0;
case Action of
f_InitState:
begin
fileList := tStringList.Create;
SearchInDir(sourceMask, sourcePath, True, fileList);
result := 0;
counter := 0;
res := 0;
end;
f_GoodStep:
begin
if (counter < fileList.Count) and (fileList.Count > 0) then
begin
ErrorEvent(fileList[counter], msInfo, VisualObject);
res := openImage(@frame, fileList[counter], code);
counter := counter + 1;
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := frame;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@frame);
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TIMSHOW //////
/// /////////////////////////////////////////////////////////////////////////
function TIMSHOW.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'windowName') then
begin
result := NativeInt(@windowName);
DataType := dtString;
end
else
if StrEqu(ParamName, 'delay') then
begin
result := NativeInt(@delay);
DataType := dtInteger;
end
end
end;
function TIMSHOW.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
createHandledWindow(windowName);
result := 0;
end;
f_GoodStep:
begin
frame := pPointer(@U[0].Arr^[0])^;
res := showFrame(frame, delay, windowName);
end;
f_Stop:
begin
destroyWindowByName(windowName);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TCONVERTCOLOR //////
/// /////////////////////////////////////////////////////////////////////////
function TCONVERTCOLOR.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'code') then
begin
result := NativeInt(@code);
DataType := dtInteger;
end
end
end;
function TCONVERTCOLOR.InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TCONVERTCOLOR.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
pPointer(@Y[0].Arr^[0])^ := nil;
result := 0;
end;
f_GoodStep:
begin
src := pPointer(@U[0].Arr^[0])^;
Case code of
integer(COLOR_BGR2BGRA):
res := sim_convertColor(src, @dst, 0);
integer(COLOR_RGB2RGBA):
res := sim_convertColor(src, @dst, 0);
integer(COLOR_BGRA2BGR):
res := sim_convertColor(src, @dst, 1);
integer(COLOR_RGBA2RGB):
res := sim_convertColor(src, @dst, 1);
integer(COLOR_BGR2RGBA):
res := sim_convertColor(src, @dst, 2);
integer(COLOR_RGB2BGRA):
res := sim_convertColor(src, @dst, 2);
integer(COLOR_RGBA2BGR):
res := sim_convertColor(src, @dst, 3);
integer(COLOR_BGRA2RGB):
res := sim_convertColor(src, @dst, 3);
integer(COLOR_BGR2RGB):
res := sim_convertColor(src, @dst, 4);
integer(COLOR_RGB2BGR):
res := sim_convertColor(src, @dst, 4);
integer(COLOR_BGRA2RGBA):
res := sim_convertColor(src, @dst, 5);
integer(COLOR_RGBA2BGRA):
res := sim_convertColor(src, @dst, 5);
integer(COLOR_BGR2GRAY):
res := sim_convertColor(src, @dst, 6);
integer(COLOR_RGB2GRAY):
res := sim_convertColor(src, @dst, 7);
integer(COLOR_GRAY2BGR):
res := sim_convertColor(src, @dst, 8);
integer(COLOR_GRAY2RGB):
res := sim_convertColor(src, @dst, 8);
integer(COLOR_BGR2HSV):
res := sim_convertColor(src, @dst, 40);
integer(COLOR_RGB2HSV):
res := sim_convertColor(src, @dst, 41);
integer(COLOR_HSV2BGR):
res := sim_convertColor(src, @dst, 54);
integer(COLOR_HSV2RGB):
res := sim_convertColor(src, @dst, 55);
End;
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TBITWISEAND //////
/// /////////////////////////////////////////////////////////////////////////
function TBITWISEAND.GetParamID;
begin
result := -1;
end;
function TBITWISEAND.InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TBITWISEAND.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
pPointer(@Y[0].Arr^[0])^ := nil;
result := 0;
end;
f_GoodStep:
begin
src1 := pPointer(@U[0].Arr^[0])^;
src2 := pPointer(@U[1].Arr^[0])^;
res := bitwiseAND(src1, src2, @dst);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TBITWISEOR //////
/// /////////////////////////////////////////////////////////////////////////
function TBITWISEOR.GetParamID;
begin
result := -1;
end;
function TBITWISEOR.InfoFunc(Action: integer; aParameter: NativeInt): NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TBITWISEOR.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
pPointer(@Y[0].Arr^[0])^ := nil;
result := 0;
end;
f_GoodStep:
begin
src1 := pPointer(@U[0].Arr^[0])^;
src2 := pPointer(@U[1].Arr^[0])^;
res := bitwiseOR(src1, src2, @dst);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TBITWISENO //////
/// /////////////////////////////////////////////////////////////////////////
function TBITWISENO.GetParamID;
begin
result := -1;
end;
function TBITWISENO.InfoFunc(Action: integer; aParameter: NativeInt): NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TBITWISENO.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
pPointer(@Y[0].Arr^[0])^ := nil;
result := 0;
end;
f_GoodStep:
begin
src := pPointer(@U[0].Arr^[0])^;
res := bitwiseNO(src, @dst);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TBITWISEXOR //////
/// /////////////////////////////////////////////////////////////////////////
function TBITWISEXOR.GetParamID;
begin
result := -1;
end;
function TBITWISEXOR.InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TBITWISEXOR.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
pPointer(@Y[0].Arr^[0])^ := nil;
result := 0;
end;
f_GoodStep:
begin
src1 := pPointer(@U[0].Arr^[0])^;
src2 := pPointer(@U[1].Arr^[0])^;
res := bitwiseXOR(src1, src2, @dst);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TmatrixMUL //////
/// /////////////////////////////////////////////////////////////////////////
function TmatrixMUL.GetParamID;
begin
result := -1;
end;
function TmatrixMUL.InfoFunc(Action: integer; aParameter: NativeInt): NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TmatrixMUL.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
pPointer(@Y[0].Arr^[0])^ := nil;
result := 0;
end;
f_GoodStep:
begin
src1 := pPointer(@U[0].Arr^[0])^;
src2 := pPointer(@U[1].Arr^[0])^;
res := matrixMUL(src1, src2, @dst);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TperElementAddWeighted //////
/// /////////////////////////////////////////////////////////////////////////
function TperElementAddWeighted.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'alpha') then
begin
result := NativeInt(@alpha);
DataType := dtDouble;
end
else
if StrEqu(ParamName, 'beta') then
begin
result := NativeInt(@beta);
DataType := dtDouble;
end
end
end;
function TperElementAddWeighted.InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TperElementAddWeighted.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
pPointer(@Y[0].Arr^[0])^ := nil;
result := 0;
end;
f_GoodStep:
begin
src1 := pPointer(@U[0].Arr^[0])^;
src2 := pPointer(@U[1].Arr^[0])^;
res := perElementAddWeighted(src1, alpha, src2, beta, @dst);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TperElementDIV //////
/// /////////////////////////////////////////////////////////////////////////
function TABSDIFF.GetParamID;
begin
result := -1;
end;
function TABSDIFF.InfoFunc(Action: integer; aParameter: NativeInt): NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TABSDIFF.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
pPointer(@Y[0].Arr^[0])^ := nil;
result := 0;
end;
f_GoodStep:
begin
src1 := pPointer(@U[0].Arr^[0])^;
src2 := pPointer(@U[1].Arr^[0])^;
res := absDiff(src1, src2, @dst);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TperElementMUL //////
/// /////////////////////////////////////////////////////////////////////////
function TperElementMUL.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'scale') then
begin
result := NativeInt(@scale);
DataType := dtDouble;
end
end
end;
function TperElementMUL.InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TperElementMUL.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
pPointer(@Y[0].Arr^[0])^ := nil;
result := 0;
end;
f_GoodStep:
begin
src1 := pPointer(@U[0].Arr^[0])^;
src2 := pPointer(@U[1].Arr^[0])^;
res := perElementMUL(scale, src1, src2, @dst);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TperElementADDV //////
/// /////////////////////////////////////////////////////////////////////////
function TperElementADD.GetParamID;
begin
result := -1;
end;
function TperElementADD.InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TperElementADD.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
pPointer(@Y[0].Arr^[0])^ := nil;
result := 0;
end;
f_GoodStep:
begin
src1 := pPointer(@U[0].Arr^[0])^;
src2 := pPointer(@U[1].Arr^[0])^;
res := perElementADD(src1, src2, @dst);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TperElementADDV //////
/// /////////////////////////////////////////////////////////////////////////
function TperElementADDV.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'Value') then
begin
result := NativeInt(@Value);
DataType := dtDouble;
end
end
end;
function TperElementADDV.InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TperElementADDV.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
pPointer(@Y[0].Arr^[0])^ := nil;
result := 0;
end;
f_GoodStep:
begin
src := pPointer(@U[0].Arr^[0])^;
res := perElementADDV(src, Value, @dst);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TperElementMULV //////
/// /////////////////////////////////////////////////////////////////////////
function TperElementMULV.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'Value') then
begin
result := NativeInt(@Value);
DataType := dtDouble;
end
end
end;
function TperElementMULV.InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TperElementMULV.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
pPointer(@Y[0].Arr^[0])^ := nil;
result := 0;
end;
f_GoodStep:
begin
src := pPointer(@U[0].Arr^[0])^;
res := perElementMULV(src, Value, @dst);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TTRESHOLD //////
/// /////////////////////////////////////////////////////////////////////////
function TTRESHOLD.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'Thresh') then
begin
result := NativeInt(@Thresh);
DataType := dtDouble;
end
else
if StrEqu(ParamName, 'Maxval') then
begin
result := NativeInt(@Maxval);
DataType := dtDouble;
end
else
if StrEqu(ParamName, 'codetype') then
begin
result := NativeInt(@codetype);
DataType := dtInteger;
end
end
end;
function TTRESHOLD.InfoFunc(Action: integer; aParameter: NativeInt): NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TTRESHOLD.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
result := 0;
end;
f_GoodStep:
begin
src := pPointer(@U[0].Arr^[0])^;
res := sim_threshold(src, @dst, Thresh, Maxval, codetype);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TADAPTIVETHRESHOLD //////
/// /////////////////////////////////////////////////////////////////////////
function TADAPTIVETHRESHOLD.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'maxValue') then
begin
result := NativeInt(@maxValue);
DataType := dtDouble;
end
else if StrEqu(ParamName, 'adaptiveMethod') then
begin
result := NativeInt(@adaptiveMethod);
DataType := dtInteger;
end
else if StrEqu(ParamName, 'ThresholdType') then
begin
result := NativeInt(@ThresholdType);
DataType := dtInteger;
end
else if StrEqu(ParamName, 'blocksize') then
begin
result := NativeInt(@blocksize);
DataType := dtInteger;
end
else if StrEqu(ParamName, 'C') then
begin
result := NativeInt(@C);
DataType := dtDouble;
end
end
end;
function TADAPTIVETHRESHOLD.InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TADAPTIVETHRESHOLD.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
result := 0;
end;
f_GoodStep:
begin
src := pPointer(@U[0].Arr^[0])^;
res := sim_adaptiveThreshold(src, @dst, maxValue, adaptiveMethod,
ThresholdType, blocksize, C);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TBILATERALFILTER //////
/// /////////////////////////////////////////////////////////////////////////
function TBILATERALFILTER.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'd') then
begin
result := NativeInt(@d);
DataType := dtInteger;
end
else if StrEqu(ParamName, 'SigmaColor') then
begin
result := NativeInt(@SigmaColor);
DataType := dtDouble;
end
else if StrEqu(ParamName, 'SigmaSpace') then
begin
result := NativeInt(@SigmaSpace);
DataType := dtDouble;
end
end
end;
function TBILATERALFILTER.InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TBILATERALFILTER.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
result := 0;
end;
f_GoodStep:
begin
src := pPointer(@U[0].Arr^[0])^;
res := sim_bilateralFilter(src, @dst, d, SigmaColor, SigmaSpace);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TBLUR //////
/// /////////////////////////////////////////////////////////////////////////
function TBLUR.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'ksizeX') then
begin
result := NativeInt(@ksizeX);
DataType := dtInteger;
end
else
if StrEqu(ParamName, 'ksizeY') then
begin
result := NativeInt(@ksizeY);
DataType := dtInteger;
end
end
end;
function TBLUR.InfoFunc(Action: integer; aParameter: NativeInt): NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TBLUR.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
result := 0;
end;
f_GoodStep:
begin
src := pPointer(@U[0].Arr^[0])^;
res := sim_blur(src, @dst, ksizeX, ksizeY);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TGAUSSIANBLUR //////
/// /////////////////////////////////////////////////////////////////////////
function TGAUSSIANBLUR.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'ksizeX') then
begin
result := NativeInt(@ksizeX);
DataType := dtInteger;
end
else
if StrEqu(ParamName, 'ksizeY') then
begin
result := NativeInt(@ksizeY);
DataType := dtInteger;
end
else
if StrEqu(ParamName, 'sigmaX') then
begin
result := NativeInt(@sigmaX);
DataType := dtDouble;
end
else
if StrEqu(ParamName, 'sigmaY') then
begin
result := NativeInt(@sigmaY);
DataType := dtDouble;
end
end
end;
function TGAUSSIANBLUR.InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TGAUSSIANBLUR.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
result := 0;
end;
f_GoodStep:
begin
src := pPointer(@U[0].Arr^[0])^;
res := sim_gaussianBlur(src, @dst, ksizeX, ksizeY, sigmaX, sigmaY);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TBOXFILTER //////
/// /////////////////////////////////////////////////////////////////////////
function TBOXFILTER.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'ksizeX') then
begin
result := NativeInt(@ksizeX);
DataType := dtInteger;
end
else
if StrEqu(ParamName, 'ksizeY') then
begin
result := NativeInt(@ksizeY);
DataType := dtInteger;
end
else
if StrEqu(ParamName, 'anchorX') then
begin
result := NativeInt(@anchorX);
DataType := dtInteger;
end
else
if StrEqu(ParamName, 'anchorY') then
begin
result := NativeInt(@anchorY);
DataType := dtInteger;
end
else
if StrEqu(ParamName, 'normalize') then
begin
result := NativeInt(@normalize);
DataType := dtInteger;
end
end
end;
function TBOXFILTER.InfoFunc(Action: integer; aParameter: NativeInt): NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TBOXFILTER.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
result := 0;
end;
f_GoodStep:
begin
src := pPointer(@U[0].Arr^[0])^;
res := sim_boxFilter(src, @dst, ksizeX, ksizeY, anchorX, anchorY,
normalize);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TCANNY //////
/// /////////////////////////////////////////////////////////////////////////
function TCANNY.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'Threshold1') then
begin
result := NativeInt(@Threshold1);
DataType := dtDouble;
end
else
if StrEqu(ParamName, 'Threshold2') then
begin
result := NativeInt(@Threshold2);
DataType := dtDouble;
end
else
if StrEqu(ParamName, 'apertureSize') then
begin
result := NativeInt(@apertureSize);
DataType := dtInteger;
end
else
if StrEqu(ParamName, 'L2gradient') then
begin
result := NativeInt(@L2gradient);
DataType := dtBool;
end
end
end;
function TCANNY.InfoFunc(Action: integer; aParameter: NativeInt): NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TCANNY.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
result := 0;
end;
f_GoodStep:
begin
src := pPointer(@U[0].Arr^[0])^;
res := sim_canny(src, @dst, Threshold1, Threshold2, apertureSize,
L2gradient);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TCORNERHARRIS //////
/// /////////////////////////////////////////////////////////////////////////
function TCORNERHARRIS.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'blocksize') then
begin
result := NativeInt(@blocksize);
DataType := dtInteger;
end
else
if StrEqu(ParamName, 'ksize') then
begin
result := NativeInt(@ksize);
DataType := dtInteger;
end
else
if StrEqu(ParamName, 'k') then
begin
result := NativeInt(@k);
DataType := dtDouble;
end
end
end;
function TCORNERHARRIS.InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TCORNERHARRIS.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
result := 0;
end;
f_GoodStep:
begin
src := pPointer(@U[0].Arr^[0])^;
res := sim_cornerHarris(src, @dst, blocksize, ksize, k);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TDILATE //////
/// /////////////////////////////////////////////////////////////////////////
function TDILATE.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'ksize') then
begin
result := NativeInt(@ksize);
DataType := dtInteger;
end
else
if StrEqu(ParamName, 'kshape') then
begin
result := NativeInt(@kshape);
DataType := dtInteger;
end
end
end;
function TDILATE.InfoFunc(Action: integer; aParameter: NativeInt): NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TDILATE.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
result := 0;
end;
f_GoodStep:
begin
src := pPointer(@U[0].Arr^[0])^;
res := sim_dilate(src, @dst, ksize, integer(kshape));
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TERODE //////
/// /////////////////////////////////////////////////////////////////////////
function TERODE.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'ksize') then
begin
result := NativeInt(@ksize);
DataType := dtInteger;
end
else
if StrEqu(ParamName, 'kShape') then
begin
result := NativeInt(@kshape);
DataType := dtInteger;
end
end
end;
function TERODE.InfoFunc(Action: integer; aParameter: NativeInt): NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TERODE.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
result := 0;
end;
f_GoodStep:
begin
src := pPointer(@U[0].Arr^[0])^;
res := sim_erode(src, @dst, ksize, integer(kshape));
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TROI //////
/// /////////////////////////////////////////////////////////////////////////
function TROI.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'roix') then
begin
result := NativeInt(@roix);
DataType := dtInteger;
end
else
if StrEqu(ParamName, 'roiy') then
begin
result := NativeInt(@roiy);
DataType := dtInteger;
end
else
if StrEqu(ParamName, 'roiw') then
begin
result := NativeInt(@roiw);
DataType := dtInteger;
end
else
if StrEqu(ParamName, 'roih') then
begin
result := NativeInt(@roih);
DataType := dtInteger;
end
end
end;
function TROI.InfoFunc(Action: integer; aParameter: NativeInt): NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TROI.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
result := 0;
end;
f_GoodStep:
begin
src := pPointer(@U[0].Arr^[0])^;
res := sim_roi(src, @dst, roix, roiy, roiw, roih);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TROI //////
/// /////////////////////////////////////////////////////////////////////////
function TFLIP.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'code') then
begin
result := NativeInt(@code);
DataType := dtInteger;
end
end
end;
function TFLIP.InfoFunc(Action: integer; aParameter: NativeInt): NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TFLIP.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
result := 0;
end;
f_GoodStep:
begin
src := pPointer(@U[0].Arr^[0])^;
res := sim_flip(src, @dst, code);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TROTATE //////
/// /////////////////////////////////////////////////////////////////////////
function TROTATE.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'code') then
begin
result := NativeInt(@code);
DataType := dtInteger;
end
end
end;
function TROTATE.InfoFunc(Action: integer; aParameter: NativeInt): NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TROTATE.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
result := 0;
end;
f_GoodStep:
begin
src := pPointer(@U[0].Arr^[0])^;
res := sim_rotate(src, @dst, code);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TSPLIT //////
/// /////////////////////////////////////////////////////////////////////////
function TSPLIT.GetParamID;
begin
result := -1;
end;
function TSPLIT.InfoFunc(Action: integer; aParameter: NativeInt): NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TSPLIT.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
result := 0;
end;
f_GoodStep:
begin
src := pPointer(@U[0].Arr^[0])^;
res := sim_split(src, @dst1, @dst2, @dst3);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst1;
pPointer(@Y[1].Arr^[0])^ := dst2;
pPointer(@Y[2].Arr^[0])^ := dst3;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
pPointer(@Y[1].Arr^[0])^ := nil;
pPointer(@Y[2].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst1);
releaseSimMat(@dst2);
releaseSimMat(@dst3);
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TINRANGE //////
/// /////////////////////////////////////////////////////////////////////////
function TINRANGE.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'lower') then
begin
result := NativeInt(@lower);
DataType := dtDouble;
end
else
if StrEqu(ParamName, 'upper') then
begin
result := NativeInt(@upper);
DataType := dtDouble;
end
end
end;
function TINRANGE.InfoFunc(Action: integer; aParameter: NativeInt): NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TINRANGE.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
result := 0;
end;
f_GoodStep:
begin
src := pPointer(@U[0].Arr^[0])^;
res := sim_inRange(src, @dst, lower, upper);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TMERGE //////
/// /////////////////////////////////////////////////////////////////////////
function TMERGE.GetParamID;
begin
result := -1;
end;
function TMERGE.InfoFunc(Action: integer; aParameter: NativeInt): NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TMERGE.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
result := 0;
end;
f_GoodStep:
begin
src1 := pPointer(@U[0].Arr^[0])^;
src2 := pPointer(@U[1].Arr^[0])^;
src3 := pPointer(@U[2].Arr^[0])^;
res := sim_merge(src1, src2, src3, @dst);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TSOBEL //////
/// /////////////////////////////////////////////////////////////////////////
function TSOBEL.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'dx') then
begin
result := NativeInt(@dx);
DataType := dtInteger;
end
else
if StrEqu(ParamName, 'dy') then
begin
result := NativeInt(@dy);
DataType := dtInteger;
end
else
if StrEqu(ParamName, 'ksize') then
begin
result := NativeInt(@ksize);
DataType := dtInteger;
end
else
if StrEqu(ParamName, 'scale') then
begin
result := NativeInt(@scale);
DataType := dtDouble;
end
else
if StrEqu(ParamName, 'delta') then
begin
result := NativeInt(@delta);
DataType := dtDouble;
end
end
end;
function TSOBEL.InfoFunc(Action: integer; aParameter: NativeInt): NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TSOBEL.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
result := 0;
end;
f_GoodStep:
begin
src := pPointer(@U[0].Arr^[0])^;
res := sim_sobel(src, @dst, dx, dy, ksize, scale, delta);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TSCHARR //////
/// /////////////////////////////////////////////////////////////////////////
function TSCHARR.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'dx') then
begin
result := NativeInt(@dx);
DataType := dtInteger;
end
else
if StrEqu(ParamName, 'dy') then
begin
result := NativeInt(@dy);
DataType := dtInteger;
end
else
if StrEqu(ParamName, 'scale') then
begin
result := NativeInt(@scale);
DataType := dtDouble;
end
else
if StrEqu(ParamName, 'delta') then
begin
result := NativeInt(@delta);
DataType := dtDouble;
end
end
end;
function TSCHARR.InfoFunc(Action: integer; aParameter: NativeInt): NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TSCHARR.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
result := 0;
end;
f_GoodStep:
begin
src := pPointer(@U[0].Arr^[0])^;
res := sim_scharr(src, @dst, dx, dy, scale, delta);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TLAPLACIAN //////
/// /////////////////////////////////////////////////////////////////////////
function TLAPLACIAN.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'ksize') then
begin
result := NativeInt(@ksize);
DataType := dtInteger;
end
else
if StrEqu(ParamName, 'scale') then
begin
result := NativeInt(@scale);
DataType := dtDouble;
end
else
if StrEqu(ParamName, 'delta') then
begin
result := NativeInt(@delta);
DataType := dtDouble;
end
end
end;
function TLAPLACIAN.InfoFunc(Action: integer; aParameter: NativeInt): NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TLAPLACIAN.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
result := 0;
end;
f_GoodStep:
begin
src := pPointer(@U[0].Arr^[0])^;
res := sim_laplacian(src, @dst, ksize, scale, delta);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TRESIZE //////
/// /////////////////////////////////////////////////////////////////////////
function TRESIZE.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'ksizeX') then
begin
result := NativeInt(@ksizeX);
DataType := dtInteger;
end
else
if StrEqu(ParamName, 'ksizeY') then
begin
result := NativeInt(@ksizeY);
DataType := dtInteger;
end
else
if StrEqu(ParamName, 'interpolation') then
begin
result := NativeInt(@interpolation);
DataType := dtInteger;
end
end
end;
function TRESIZE.InfoFunc(Action: integer; aParameter: NativeInt): NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TRESIZE.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
result := 0;
end;
f_GoodStep:
begin
src := pPointer(@U[0].Arr^[0])^;
res := sim_resize(src, @dst, ksizeX, ksizeY, interpolation);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TCalibrateCamera //////
/// /////////////////////////////////////////////////////////////////////////
function TCalibrateCamera.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'numCornersHor') then
begin
result := NativeInt(@numCornersHor);
DataType := dtInteger;
end
else if StrEqu(ParamName, 'numCornersVer') then
begin
result := NativeInt(@numCornersVer);
DataType := dtInteger;
end
else if StrEqu(ParamName, 'fileName') then
begin
result := NativeInt(@fileName);
DataType := dtString;
end
end
end;
function TCalibrateCamera.InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TCalibrateCamera.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
result := 0;
calibrated := 0;
end;
f_GoodStep:
begin
if pPointer(@U[0].Arr^[0])^ <> nil then
begin
image := pPointer(@U[0].Arr^[0])^;
res := sim_fidnCalibrationPoints(@image_points, @object_points, image,
@dstImage, numCornersHor, numCornersVer);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dstImage;
end
end
else
begin
if calibrated = 0 then
begin
res := sim_calibrateCamera(image_points, object_points, image,
@intrinsic, @distCoeffs);
if res = 0 then
begin
calibrated := 1;
ErrorEvent('camera calibrated!!!', msInfo, VisualObject);
sim_saveCalibrationParameters(fileName, intrinsic, distCoeffs);
if res = 0 then
begin
ErrorEvent('calibration data saved to file: ' + fileName, msInfo,
VisualObject);
end;
end
else
begin
calibrated := -1;
ErrorEvent('Cant calibrate camera ', msInfo,
VisualObject);
end;
end;
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
if calibrated = 0 then
begin
res := sim_calibrateCamera(image_points, object_points, image,
@intrinsic, @distCoeffs);
if res = 0 then
begin
ErrorEvent('camera calibrated!!!', msInfo, VisualObject);
sim_saveCalibrationParameters(fileName, intrinsic, distCoeffs);
if res = 0 then
begin
ErrorEvent('calibration data saved to file: ' + fileName, msInfo,
VisualObject);
end;
end
else
begin
ErrorEvent('Cant calibrate camera ', msInfo,
VisualObject);
end;
end;
releaseSimMat(@dstImage);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TUndistotImage //////
/// /////////////////////////////////////////////////////////////////////////
function TUndistotImage.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
end
end;
function TUndistotImage.InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TUndistotImage.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
result := 0;
end;
f_GoodStep:
begin
src := pPointer(@U[0].Arr^[0])^;
intrinsic := pPointer(@U[1].Arr^[0])^;
distCoeffs := pPointer(@U[2].Arr^[0])^;
res := sim_undistort(src, @dst, intrinsic, distCoeffs);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TLoadCalibrationParameters //////
/// /////////////////////////////////////////////////////////////////////////
function TLoadCalibrationParameters.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'fileName') then
begin
result := NativeInt(@fileName);
DataType := dtString;
end
end
end;
function TLoadCalibrationParameters.InfoFunc(Action: integer;
aParameter: NativeInt): NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TLoadCalibrationParameters.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
if FileExists(fileName)
then
begin
dir := fileName;
end
else
begin
dir := GetCurrentDir + '\' + fileName;
if not FileExists(dir)
then
begin
ErrorEvent(dir + ' Файл не найден', msInfo, VisualObject);
end
end;
res := sim_loadCalibrationParameters(dir, @intrinsic, @distCoeffs);
if res = 0 then
begin
ErrorEvent('calibration data loaded from file: ' + dir, msInfo,
VisualObject);
pPointer(@Y[0].Arr^[0])^ := intrinsic;
pPointer(@Y[1].Arr^[0])^ := distCoeffs;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
pPointer(@Y[1].Arr^[0])^ := nil;
end;
result := 0;
end;
f_GoodStep:
begin
result := 0;
end;
f_Stop:
begin
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TwarpPerspective //////
/// /////////////////////////////////////////////////////////////////////////
function TwarpPerspective.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'dsizeX') then
begin
result := NativeInt(@dsizeX);
DataType := dtInteger;
end
else
if StrEqu(ParamName, 'dsizeY') then
begin
result := NativeInt(@dsizeY);
DataType := dtInteger;
end
else
if StrEqu(ParamName, 'srcX1') then
begin
result := NativeInt(@srcPts[1]);
DataType := dtDouble;
end
else
if StrEqu(ParamName, 'srcY1') then
begin
result := NativeInt(@srcPts[2]);
DataType := dtDouble;
end
else
if StrEqu(ParamName, 'srcX2') then
begin
result := NativeInt(@srcPts[3]);
DataType := dtDouble;
end
else
if StrEqu(ParamName, 'srcY2') then
begin
result := NativeInt(@srcPts[4]);
DataType := dtDouble;
end
else
if StrEqu(ParamName, 'srcX3') then
begin
result := NativeInt(@srcPts[5]);
DataType := dtDouble;
end
else
if StrEqu(ParamName, 'srcY3') then
begin
result := NativeInt(@srcPts[6]);
DataType := dtDouble;
end
else
if StrEqu(ParamName, 'srcX4') then
begin
result := NativeInt(@srcPts[7]);
DataType := dtDouble;
end
else
if StrEqu(ParamName, 'srcY4') then
begin
result := NativeInt(@srcPts[8]);
DataType := dtDouble;
end
else
if StrEqu(ParamName, 'dstX1') then
begin
result := NativeInt(@dstPts[1]);
DataType := dtDouble;
end
else
if StrEqu(ParamName, 'dstY1') then
begin
result := NativeInt(@dstPts[2]);
DataType := dtDouble;
end
else
if StrEqu(ParamName, 'dstX2') then
begin
result := NativeInt(@dstPts[3]);
DataType := dtDouble;
end
else
if StrEqu(ParamName, 'dstY2') then
begin
result := NativeInt(@dstPts[4]);
DataType := dtDouble;
end
else
if StrEqu(ParamName, 'dstX3') then
begin
result := NativeInt(@dstPts[5]);
DataType := dtDouble;
end
else
if StrEqu(ParamName, 'dstY3') then
begin
result := NativeInt(@dstPts[6]);
DataType := dtDouble;
end
else
if StrEqu(ParamName, 'dstX4') then
begin
result := NativeInt(@dstPts[7]);
DataType := dtDouble;
end
else
if StrEqu(ParamName, 'dstY4') then
begin
result := NativeInt(@dstPts[8]);
DataType := dtDouble;
end
end
end;
function TwarpPerspective.InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TwarpPerspective.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
result := 0;
end;
f_GoodStep:
begin
src := pPointer(@U[0].Arr^[0])^;
res := sim_warpPerspective(src, @dst, @srcPts[1], @dstPts[1],
dsizeX, dsizeY);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TFloodFill //////
/// /////////////////////////////////////////////////////////////////////////
function TFloodFill.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'px') then
begin
result := NativeInt(@px);
DataType := dtInteger;
end
else
if StrEqu(ParamName, 'py') then
begin
result := NativeInt(@py);
DataType := dtInteger;
end
else
if StrEqu(ParamName, 'ch1') then
begin
result := NativeInt(@ch1);
DataType := dtInteger;
end
else
if StrEqu(ParamName, 'ch2') then
begin
result := NativeInt(@ch2);
DataType := dtInteger;
end
else
if StrEqu(ParamName, 'ch3') then
begin
result := NativeInt(@ch3);
DataType := dtInteger;
end
end
end;
function TFloodFill.InfoFunc(Action: integer; aParameter: NativeInt): NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TFloodFill.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
result := 0;
end;
f_GoodStep:
begin
src := pPointer(@U[0].Arr^[0])^;
res := sim_floodFill(src, @dst, px, py, ch1, ch2, ch3);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dst;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
releaseSimMat(@dst);
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TFindContous //////
/// /////////////////////////////////////////////////////////////////////////
function TFindContous.InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TFindContous.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
result := 0;
end;
f_GoodStep:
begin
srcFrame := pPointer(@U[0].Arr^[0])^;
res := sim_findContours(srcFrame, @contours);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := contours;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TSelectContour //////
/// /////////////////////////////////////////////////////////////////////////
function TSelectContour.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'index') then
begin
result := NativeInt(@index);
DataType := dtInteger;
end
else if StrEqu(ParamName, 'width') then
begin
result := NativeInt(@width);
DataType := dtInteger;
end
else if StrEqu(ParamName, 'red') then
begin
result := NativeInt(@red);
DataType := dtInteger;
end
else if StrEqu(ParamName, 'green') then
begin
result := NativeInt(@green);
DataType := dtInteger;
end
else if StrEqu(ParamName, 'blue') then
begin
result := NativeInt(@blue);
DataType := dtInteger;
end
end
end;
function TSelectContour.InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TSelectContour.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
result := 0;
end;
f_GoodStep:
begin
srcFrame := pPointer(@U[0].Arr^[0])^;
contours := pPointer(@U[1].Arr^[0])^;
res := sim_selectContour(srcFrame, contours, index, red, green, blue,
width, @dstFrame, @contour);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := dstFrame;
pPointer(@Y[1].Arr^[0])^ := contour;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
pPointer(@Y[1].Arr^[0])^ := nil;
end;
// pPointer(@Y[0].Arr^[0])^ := srcFrame;
// pPointer(@Y[1].Arr^[0])^ := contours;
end;
f_Stop:
begin
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TSelectContourArea //////
/// /////////////////////////////////////////////////////////////////////////
function TSelectContourArea.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'minArea') then
begin
result := NativeInt(@minArea);
DataType := dtDouble;
end
else if StrEqu(ParamName, 'maxArea') then
begin
result := NativeInt(@maxArea);
DataType := dtDouble;
end
end
end;
function TSelectContourArea.InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TSelectContourArea.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
result := 0;
end;
f_GoodStep:
begin
inputContours := pPointer(@U[0].Arr^[0])^;
res := sim_minMaxAreaContoursFilter(inputContours, @outputContours,
@minArea, @maxArea);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := outputContours;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TFindSign //////
/// /////////////////////////////////////////////////////////////////////////
function TFindSign.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'normalizedContourSizeX') then
begin
result := NativeInt(@normalizedContourSizeX);
DataType := dtInteger;
end
else if StrEqu(ParamName, 'normalizedContourSizeY') then
begin
result := NativeInt(@normalizedContourSizeY);
DataType := dtInteger;
end
else if StrEqu(ParamName, 'useHull') then
begin
result := NativeInt(@useHull);
DataType := dtBool;
end
else if StrEqu(ParamName, 'draw') then
begin
result := NativeInt(@draw);
DataType := dtBool;
end
else if StrEqu(ParamName, 'minCorrelation') then
begin
result := NativeInt(@minCorrelation);
DataType := dtDouble;
end
end
end;
function TFindSign.InfoFunc(Action: integer; aParameter: NativeInt): NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TFindSign.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
result := 0;
end;
f_GoodStep:
begin
templFrame := pPointer(@U[0].Arr^[0])^;
templContour := pPointer(@U[1].Arr^[0])^;
frame := pPointer(@U[2].Arr^[0])^;
contours := pPointer(@U[3].Arr^[0])^;
res := sim_findSign(templFrame, templContour, frame, contours,
normalizedContourSizeX, normalizedContourSizeY, useHull, draw,
minCorrelation, @numFound);
if res = 0 then
begin
Y[0].Arr^[0] := numFound;
pPointer(@Y[1].Arr^[0])^ := frame;
end
else
begin
Y[0].Arr^[0] := 0;
pPointer(@Y[1].Arr^[0])^ := nil;
end;
end;
f_Stop:
begin
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TDetectLanes //////
/// /////////////////////////////////////////////////////////////////////////
function TDetectLanes.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
if StrEqu(ParamName, 'numHorHist') then
begin
result := NativeInt(@numHorHist);
DataType := dtInteger;
end
else if StrEqu(ParamName, 'wheel') then
begin
result := NativeInt(@wheel);
DataType := dtInteger;
end
else if StrEqu(ParamName, 'roi') then
begin
result := NativeInt(@roi);
DataType := dtInteger;
end
end
end;
function TDetectLanes.InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
cY[1] := 2;
cY[2] := 2;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TDetectLanes.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
result := 0;
end;
f_GoodStep:
begin
binaryinput := pPointer(@U[0].Arr^[0])^;
drawinput := pPointer(@U[1].Arr^[0])^;
res := sim_detectLanes(binaryinput, numHorHist, roi, wheel, @rd, @ld,
drawinput, @leftPointCount, @rightPointCount);
if res = 0 then
begin
pPointer(@Y[0].Arr^[0])^ := drawinput;
Y[1].Arr^[0] := rd;
Y[1].Arr^[1] := ld;
Y[2].Arr^[0] := rightPointCount;
Y[2].Arr^[1] := leftPointCount;
end
else
begin
pPointer(@Y[0].Arr^[0])^ := nil;
Y[1].Arr^[0] := -1;
Y[1].Arr^[1] := -1;
Y[2].Arr^[0] := -1;
Y[2].Arr^[1] := -1;
end;
ErrorEvent(IntToStr(rd) + ' <> ' + IntToStr(ld), msInfo, VisualObject);
end;
f_Stop:
begin
result := 0;
end;
end
end;
/// /////////////////////////////////////////////////////////////////////////
/// // TDetectLanes //////
/// /////////////////////////////////////////////////////////////////////////
function TCountContours.GetParamID;
begin
result := inherited GetParamID(ParamName, DataType, IsConst);
if result = -1 then
begin
end
end;
function TCountContours.InfoFunc(Action: integer; aParameter: NativeInt)
: NativeInt;
begin
result := 0;
case Action of
i_GetCount:
begin
cY[0] := 1;
end;
i_GetInit:
begin
result := 0;
end;
else
result := inherited InfoFunc(Action, aParameter);
end
end;
function TCountContours.RunFunc;
var
res: integer;
begin
result := 0;
case Action of
f_InitState:
begin
result := 0;
end;
f_GoodStep:
begin
count := 0;
inputContours := pPointer(@U[0].Arr^[0])^;
res := sim_countContours(inputContours, @count);
Y[0].Arr^[0] := count;
end;
f_Stop:
begin
result := 0;
end;
end
end;
// ***********************************************************************//
// Раздел инициализации //
// ***********************************************************************//
var
hDll: THandle;
initialization
hDll := LoadLibrary('simintechVisLib.dll');
createHandledWindow := GetProcAddress(hDll, 'createHandledWindow');
getWindowHandle := GetProcAddress(hDll, 'getWindowHandle');
// Получить изображение из источника
retrieveImage := GetProcAddress(hDll, 'retrieveImage');
// Очистка ресурсов
releaseSimMat := GetProcAddress(hDll, 'releaseSimMat');
releaseSourse := GetProcAddress(hDll, 'releaseSourse');
destroyWindowByName := GetProcAddress(hDll, 'destroyWindowByName');
destroyAllWindows := GetProcAddress(hDll, 'destroyAllWindows');
// Открыть источник изображений
openVideoSource := GetProcAddress(hDll, 'openVideoSource');
// Открыть изображение из файла
openImage := GetProcAddress(hDll, 'openImage');
// Показать изображение
showFrame := GetProcAddress(hDll, 'showFrame');
sim_convertColor := GetProcAddress(hDll, 'sim_convertColor');
bitwiseAND := GetProcAddress(hDll, 'bitwiseAND');
bitwiseOR := GetProcAddress(hDll, 'bitwiseOR');
bitwiseNO := GetProcAddress(hDll, 'bitwiseNO');
bitwiseXOR := GetProcAddress(hDll, 'bitwiseXOR');
matrixMUL := GetProcAddress(hDll, 'matrixMUL');
perElementAddWeighted := GetProcAddress(hDll, 'perElementAddWeighted');
absDiff := GetProcAddress(hDll, 'absDiff');
perElementMUL := GetProcAddress(hDll, 'perElementMUL');
perElementADDV := GetProcAddress(hDll, 'perElementADDV');
perElementADD := GetProcAddress(hDll, 'perElementADD');
perElementMULV := GetProcAddress(hDll, 'perElementMULV');
sim_threshold := GetProcAddress(hDll, 'sim_threshold');
sim_adaptiveThreshold := GetProcAddress(hDll, 'sim_adaptiveThreshold');
sim_bilateralFilter := GetProcAddress(hDll, 'sim_bilateralFilter');
sim_blur := GetProcAddress(hDll, 'sim_blur');
sim_gaussianBlur := GetProcAddress(hDll, 'sim_gaussianBlur');
sim_boxFilter := GetProcAddress(hDll, 'sim_boxFilter');
sim_canny := GetProcAddress(hDll, 'sim_canny');
sim_cornerHarris := GetProcAddress(hDll, 'sim_cornerHarris');
sim_dilate := GetProcAddress(hDll, 'sim_dilate');
sim_erode := GetProcAddress(hDll, 'sim_erode');
sim_roi := GetProcAddress(hDll, 'sim_roi');
sim_flip := GetProcAddress(hDll, 'sim_flip');
sim_rotate := GetProcAddress(hDll, 'sim_rotate');
sim_split := GetProcAddress(hDll, 'sim_split');
sim_inRange := GetProcAddress(hDll, 'sim_inRange');
sim_merge := GetProcAddress(hDll, 'sim_merge');
sim_sobel := GetProcAddress(hDll, 'sim_sobel');
sim_scharr := GetProcAddress(hDll, 'sim_scharr');
sim_laplacian := GetProcAddress(hDll, 'sim_laplacian');
sim_resize := GetProcAddress(hDll, 'sim_resize');
sim_warpPerspective := GetProcAddress(hDll, 'sim_warpPerspective');
sim_floodFill := GetProcAddress(hDll, 'sim_floodFill');
sim_findContours := GetProcAddress(hDll, 'sim_findContours');
sim_selectContour := GetProcAddress(hDll, 'sim_selectContour');
sim_minMaxAreaContoursFilter := GetProcAddress(hDll,
'sim_minMaxAreaContoursFilter');
sim_fidnCalibrationPoints := GetProcAddress(hDll, 'sim_fidnCalibrationPoints');
sim_undistort := GetProcAddress(hDll, 'sim_undistort');
sim_calibrateCamera := GetProcAddress(hDll, 'sim_calibrateCamera');
sim_saveCalibrationParameters := GetProcAddress(hDll,
'sim_saveCalibrationParameters');
sim_loadCalibrationParameters := GetProcAddress(hDll,
'sim_loadCalibrationParameters');
sim_findSign := GetProcAddress(hDll, 'sim_findSign');
sim_detectLanes := GetProcAddress(hDll, 'sim_detectLanes');
sim_countContours := GetProcAddress(hDll, 'sim_countContours');
um_init := GetProcAddress(hDll, 'um_init');
um_get_frame := GetProcAddress(hDll, 'um_get_frame');
um_release_socket := GetProcAddress(hDll, 'um_release_socket');
finalization
if hDll <> 0 then
FreeLibrary(hDll);
end.
|
unit WritingSQLUnit;
interface
uses
JoanModule,
TestClasses,
SysUtils, Generics.Collections, Classes, Contnrs;
type
TWritingData = class
private
public
procedure Insert(Writing: TWriting);
procedure Update(Writing: TWriting);
procedure Delete(QuestionNumber: integer; TestIndex: Integer);
function Select(TestIndex: integer) : TObjectList<TQuiz>;
end;
implementation
{ TWritingData }
procedure TWritingData.Delete(QuestionNumber: integer; TestIndex: Integer);
begin
with Joan.JoanQuery do
begin
Close;
SQL.Clear;
SQL.Text :=
'DELETE FROM writing ' +
'WHERE (test_idx = :idx) and (number = :quiznumber);';
ParamByName('idx').AsInteger := TestIndex;
ParamByName('quiznumber').AsInteger := QuestionNumber;
ExecSQL();
end;
end;
procedure TWritingData.Insert(Writing: TWriting);
begin
with Joan.JoanQuery do
begin
Close;
SQL.Clear;
SQL.Text :=
'INSERT INTO writing ' +
'(test_idx, number, example_text, quiz) ' +
'VALUES ' +
'(:idx,:quiznumber,:exampletext,:quiz);';
ParamByName('idx').AsInteger := Writing.Idx;
ParamByName('quiznumber').AsInteger := Writing.QuizNumber;
ParamByName('exampletext').AsString := Writing.ExampleText;
ParamByName('quiz').AsString := Writing.Quiz;
ExecSQL();
end;
end;
procedure TWritingData.Update(Writing: TWriting);
begin
with Joan.JoanQuery do
begin
Close;
SQL.Clear;
SQL.Text :=
'UPDATE writing SET ' +
'test_idx = :idx, number = :quiznumber, '+
'example_text = :exampletext, quiz = :quiz ' +
'WHERE (test_idx = :idx) and (number = :quiznumber);';
ParamByName('idx').AsInteger := Writing.Idx;
ParamByName('quiznumber').AsInteger := Writing.QuizNumber;
ParamByName('exampletext').AsString := Writing.ExampleText;
ParamByName('quiz').AsString := Writing.Quiz;
ExecSQL();
end;
end;
function TWritingData.Select(
TestIndex: integer): TObjectList<TQuiz>;
var
Writing: TWriting;
begin
Result := TObjectList<TQuiz>.Create;
Joan.JoanQuery.SQL.Clear;
Joan.JoanQuery.SQL.Text := 'SELECT * FROM writing WHERE test_idx = :index';
Joan.JoanQuery.ParamByName('index').AsInteger := TestIndex;
Joan.JoanQuery.Open;
while not Joan.JoanQuery.Eof do
begin
begin
Writing := TWriting.Create;
Writing.Idx := Joan.JoanQuery.FieldByName('test_idx').AsInteger;
Writing.QuizNumber := Joan.JoanQuery.FieldByName('number').AsInteger;
Writing.ExampleText := Joan.JoanQuery.FieldByName('example_text').AsString;
Writing.Quiz := Joan.JoanQuery.FieldByName('quiz').AsString;
Result.Add(Writing);
Joan.JoanQuery.Next;
end;
end;
end;
end.
|
unit getbit_3;
interface
implementation
var
V: Int64;
B: Boolean;
procedure Test;
begin
V := Low(Int64);
B := getbit(V, 63);
end;
initialization
Test();
finalization
Assert(B);
end. |
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
unit frmMain;
interface
uses
Windows, Messages, Classes, Graphics, Forms, ExtCtrls, Menus,
Controls, Dialogs, SysUtils,
OpenGL;
type
TfrmGL = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormResize(Sender: TObject);
private
DC : HDC;
hrc: HGLRC;
PText : pointer;
bmWidth, bmHeight:GLsizei;
procedure SetDCPixelFormat (hdc : HDC);
end;
var
frmGL: TfrmGL;
implementation
{$R *.DFM}
function ReadMonochrome(const FilePath:string;var bmWidth,bmHeight:
GLsizei): Pointer;
const
szh = SizeOf(TBitmapFileHeader);
szi = SizeOf(TBitmapInfoHeader);
var
BmpFile: file;
bfh: TBitmapFileHeader;
bmi: TBitmapInfoHeader;
siz,
size: integer;
begin
AssignFile(bmpfile,FilePath);
Reset(bmpfile,1);
size := FileSize(bmpfile) - szh - szi;
BlockRead(bmpfile,bfh,szh);
If Bfh.bfType<>$4D42 then
raise EInvalidGraphic.Create('Invalid Bitmap');
BlockRead(bmpfile,bmi,szi);
With bmi do begin
bmWidth := biWidth;
bmHeight := biHeight;
siz := biSizeImage;
end;
If size > siz then seek(bmpfile,szh+szi+size-siz);
GetMem(Result, siz);
BlockRead(bmpfile, Result^, siz);
CloseFile(bmpfile)
end;
{=======================================================================
Перерисовка окна}
procedure TfrmGL.FormPaint(Sender: TObject);
begin
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
glPushMatrix;
glColor3f (1.0, 0.0, 0.0);
glBegin (GL_TRIANGLES);
glVertex3f (0.0, 0.0, 1.0);
glVertex3f (2.0, -0.5, 1.0);
glVertex3f (1.0, 1.0, 1.0);
glEnd;
glColor3f (0.0, 0.0, 1.0);
glBegin (GL_TRIANGLES);
glVertex3f (0.0, 0.0, -2.1);
glVertex3f (1.0, 0.0, -2.1);
glVertex3f (0.0, 6.0, -2.1);
glEnd;
glColor3f (1.0, 1.0, 0.0);
glRasterPos3f(-0.4, 0.9, -2.0);
glBitmap(bmWidth, bmHeight, 0, 0, 0, 0, PText);
glPopMatrix;
SwapBuffers (DC);
end;
{=======================================================================
Создание окна}
procedure TfrmGL.FormCreate(Sender: TObject);
begin
DC := GetDC (Handle);
SetDCPixelFormat (DC);
hrc := wglCreateContext(DC);
wglMakeCurrent(DC, hrc);
PText := ReadMonochrome('Text.bmp',bmWidth,bmHeight);
glClearColor (0.5, 0.5, 0.75, 1.0);
glPixelStorei(GL_UNPACK_ALIGNMENT,1);
glEnable(GL_DEPTH_TEST); // можно удалить, буквы станут выше объектов
end;
{=======================================================================
Формат пикселя}
procedure TfrmGL.SetDCPixelFormat (hdc : HDC);
var
pfd : TPixelFormatDescriptor;
nPixelFormat : Integer;
begin
FillChar (pfd, SizeOf (pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat (hdc, @pfd);
SetPixelFormat (hdc, nPixelFormat, @pfd);
end;
{=======================================================================
Конец работы программы}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
wglMakeCurrent(0, 0);
wglDeleteContext(hrc);
freemem(PText);
ReleaseDC (Handle, DC);
DeleteDC (DC);
end;
procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If Key = VK_ESCAPE then Close;
end;
procedure TfrmGL.FormResize(Sender: TObject);
begin
glViewport (0, 0, ClientWidth, ClientHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
gluPerspective (45.0, ClientWidth / ClientHeight, 1.0, 100.0);
gluLookAt(0.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 1.0, 0.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
glTranslatef(0.0, 0.0, -5.0);
glRotatef(-45.0, 1.0, 0.0, 0.0);
glRotatef(45.0, 0.0, 1.0, 0.0);
InvalidateRect(Handle, nil, False);
end;
end.
|
/////////////////////////////////////////////////////////
// //
// FlexGraphics library //
// Copyright (c) 2002-2009, FlexGraphics software. //
// //
// FlexGraphics library file formats support //
// Base classes //
// //
/////////////////////////////////////////////////////////
unit FlexFileFormats;
{$I FlexDefs.inc}
interface
uses
Classes, SysUtils, FlexBase;
resourcestring
sUnsupportedFormat = 'Unsupported format %s';
sImportError = 'Import error: %s';
sExportError = 'Export error: %s';
sNotImplemented = 'Not implemented';
type
TFlexFileFormat = class;
TFlexFileFormatClass = class of TFlexFileFormat;
TFlexFileExtensions = class;
TFlexFileSupportKind = (
skImport,
skExport
);
TFlexFileSupportKinds = set of TFlexFileSupportKind;
TFlexFileExtension = class
public
FormatClass: TFlexFileFormatClass;
Extension: string;
Description: string;
Kinds: TFlexFileSupportKinds;
Tag: integer;
end;
TFlexFileFormat = class
protected
// FOwner initialized only when constructed via Create()
FOwner: TObject;
// Determines is the class supports streams. If False then class can
// operate with AFilename parameter only (caller should set AStream to Nil).
// True by default.
FStreamSupport: boolean;
// FExtensions initialized only when constructed via CreateAndRegister()
FExtensions: TFlexFileExtensions;
function RegisterExtension(const AExtension, ADescription: string;
AKinds: TFlexFileSupportKinds; ATag: integer = 0): integer; virtual;
procedure RegisterSupportedExtensions; virtual; abstract;
public
constructor Create(AOwner: TObject); virtual;
constructor CreateForRegister(AExtensions: TFlexFileExtensions);
destructor Destroy; override;
procedure ImportFromStream(AStream: TStream; AFlexPanel: TFlexPanel;
const Extension: TFlexFileExtension; const AFileName: string); virtual;
procedure ExportToStream(AStream: TStream; AFlexPanel: TFlexPanel;
const Extension: TFlexFileExtension; const AFileName: string); virtual;
property Owner: TObject read FOwner;
property StreamSupport: boolean read FStreamSupport;
end;
TFlexFileExtensions = class
private
FItems: TList;
function GetCount: integer;
function GetItem(Index: integer): TFlexFileExtension;
protected
function RegisterExtension(Extension: TFlexFileExtension): integer;
public
constructor Create;
destructor Destroy; override;
function RegisterFormat(AFormat: TFlexFileFormatClass): boolean;
procedure UnregisterFormat(AFormat: TFlexFileFormatClass);
procedure Delete(Index: integer);
procedure Clear;
function IndexOf(AClass: TFlexFileFormatClass): integer;
procedure ImportFromStream(ItemIndex: integer; AFlexPanel: TFlexPanel;
AStream: TStream; AFileName: string = '');
procedure ExportToStream(ItemIndex: integer; AFlexPanel: TFlexPanel;
AStream: TStream; AFileName: string = '');
procedure ImportFromFile(ItemIndex: integer; AFlexPanel: TFlexPanel;
AFilename: string);
procedure ExportToFile(ItemIndex: integer; AFlexPanel: TFlexPanel;
AFilename: string);
property Count: integer read GetCount;
property Items[Index: integer]: TFlexFileExtension read GetItem; default;
end;
function RegisteredFlexFileFormats: TFlexFileExtensions;
implementation
{$IFDEF STDFILEFORMATS}
uses
FormatMetaFile, FormatStdFiles, FormatSvgFile;
{$ENDIF}
var
FFormats: TFlexFileExtensions;
function RegisteredFlexFileFormats: TFlexFileExtensions;
begin
if not Assigned(FFormats) then
FFormats := TFlexFileExtensions.Create;
Result := FFormats;
end;
// TFlexFileFormat ////////////////////////////////////////////////////////////
constructor TFlexFileFormat.Create(AOwner: TObject);
begin
FOwner := AOwner;
FStreamSupport := True;
end;
constructor TFlexFileFormat.CreateForRegister(AExtensions: TFlexFileExtensions);
begin
FExtensions := AExtensions;
RegisterSupportedExtensions;
end;
destructor TFlexFileFormat.Destroy;
begin
inherited;
end;
function TFlexFileFormat.RegisterExtension(const AExtension,
ADescription: string; AKinds: TFlexFileSupportKinds;
ATag: integer = 0): integer;
var
Item: TFlexFileExtension;
begin
Item := TFlexFileExtension.Create;
with Item do
try
FormatClass := TFlexFileFormatClass(Self.ClassType);
Extension := AExtension;
Description := ADescription;
Kinds := AKinds;
Tag := ATag;
Result := FExtensions.RegisterExtension(Item);
except
Free;
raise;
end;
end;
procedure TFlexFileFormat.ImportFromStream(AStream: TStream;
AFlexPanel: TFlexPanel; const Extension: TFlexFileExtension;
const AFileName: string);
begin
raise Exception.CreateFmt(sImportError, [sNotImplemented]);
end;
procedure TFlexFileFormat.ExportToStream(AStream: TStream;
AFlexPanel: TFlexPanel; const Extension: TFlexFileExtension;
const AFileName: string);
begin
raise Exception.CreateFmt(sExportError, [sNotImplemented]);
end;
// TRegisteredFlexFileFormats /////////////////////////////////////////////////
constructor TFlexFileExtensions.Create;
begin
FItems := TList.Create;
end;
destructor TFlexFileExtensions.Destroy;
begin
Clear;
inherited;
FItems.Free;
end;
function TFlexFileExtensions.GetCount: integer;
begin
Result := FItems.Count;
end;
function TFlexFileExtensions.GetItem(Index: integer): TFlexFileExtension;
begin
Result := TFlexFileExtension(FItems[Index]);
end;
function TFlexFileExtensions.IndexOf(AClass: TFlexFileFormatClass): integer;
var
i: integer;
begin
Result := -1;
for i:=0 to FItems.Count-1 do
if TFlexFileExtension(FItems[i]).FormatClass = AClass then begin
Result := i;
Break;
end;
end;
procedure TFlexFileExtensions.Delete(Index: integer);
var
Item: TFlexFileExtension;
begin
Item := FItems[Index];
FItems.Delete(Index);
Item.Free;
end;
procedure TFlexFileExtensions.Clear;
var
i: integer;
begin
for i:=0 to FItems.Count-1 do
TFlexFileExtension(FItems[i]).Free;
FItems.Clear;
end;
function TFlexFileExtensions.RegisterFormat(
AFormat: TFlexFileFormatClass): boolean;
var
i: integer;
begin
Result := True;
// Check if the AFormat class already have registered extensions
for i:=0 to FItems.Count-1 do
if TFlexFileExtension(FItems[i]).FormatClass = AFormat then begin
Result := False;
Break;
end;
// Register all format extensions
if Result then
AFormat.CreateForRegister(Self).Free;
end;
procedure TFlexFileExtensions.UnregisterFormat(AFormat: TFlexFileFormatClass);
var
i: integer;
begin
for i:=FItems.Count-1 downto 0 do
if TFlexFileExtension(FItems[i]).FormatClass = AFormat then
Delete(i);
end;
function TFlexFileExtensions.RegisterExtension(
Extension: TFlexFileExtension): integer;
begin
Result := FItems.IndexOf(Extension);
if Result < 0 then
Result := FItems.Add(Extension);
end;
procedure TFlexFileExtensions.ImportFromStream(ItemIndex: integer;
AFlexPanel: TFlexPanel; AStream: TStream; AFileName: string = '');
begin
with TFlexFileExtension(FItems[ItemIndex]).FormatClass.Create(Self) do
try
ImportFromStream(AStream, AFlexPanel,
TFlexFileExtension(FItems[ItemIndex]), AFileName);
finally
Free;
end;
end;
procedure TFlexFileExtensions.ExportToStream(ItemIndex: integer;
AFlexPanel: TFlexPanel; AStream: TStream; AFileName: string = '');
begin
with TFlexFileExtension(FItems[ItemIndex]).FormatClass.Create(Self) do
try
ExportToStream(AStream, AFlexPanel,
TFlexFileExtension(FItems[ItemIndex]), AFileName);
finally
Free;
end;
end;
procedure TFlexFileExtensions.ImportFromFile(ItemIndex: integer;
AFlexPanel: TFlexPanel; AFilename: string);
var
FS: TFileStream;
begin
FS := Nil;
with TFlexFileExtension(FItems[ItemIndex]).FormatClass.Create(Self) do
try
if StreamSupport then FS := TFileStream.Create(AFilename, fmOpenRead);
ImportFromStream(FS, AFlexPanel,
TFlexFileExtension(FItems[ItemIndex]), AFileName);
finally
FS.Free;
Free;
end;
end;
procedure TFlexFileExtensions.ExportToFile(ItemIndex: integer;
AFlexPanel: TFlexPanel; AFilename: string);
var
FS: TFileStream;
begin
FS := Nil;
with TFlexFileExtension(FItems[ItemIndex]).FormatClass.Create(Self) do
try
if StreamSupport then FS := TFileStream.Create(AFilename, fmCreate);
ExportToStream(FS, AFlexPanel,
TFlexFileExtension(FItems[ItemIndex]), AFileName);
finally
FS.Free;
Free;
end;
end;
///////////////////////////////////////////////////////////////////////////////
initialization
finalization
FFormats.Free;
end.
|
unit DCClassHelpers;
interface
uses
SysUtils,
Variants,
Data.Win.ADODB,
Generics.Collections;
type
TDCObjectHelper = class helper for TObject
procedure &With<T:class>(Action:TProc<T>);
end;
TDCADOParametersHelper = class helper for TParameters
procedure ForEach(Action:TProc<TParameter>);
end;
TDCVariantHelper = record helper for Variant
function GetType():TVarType;
function GetDefault():Variant;
function GetConvertVar():Variant;
function VarToString():string;
function VarToDateTimes():TDateTime;
end;
implementation
{ TDCObjectHelper }
procedure TDCObjectHelper.&With<T>(Action: TProc<T>);
begin
Action(Self);
end;
{ TDCADOParametersHelper }
procedure TDCADOParametersHelper.ForEach(Action: TProc<TParameter>);
var
i : integer;
begin
for i := 0 to Self.Count-1 do
begin
Action(Self.Items[i]);
end;
end;
{ TDCVariantHelper }
function TDCVariantHelper.GetConvertVar: Variant;
begin
case Self.GetType of
//numeric
varSmallInt, varInteger, varBoolean, varShortInt,
varByte, varWord, varLongWord, varInt64, varUInt64 : Result := Self;
//Float
varSingle, varDouble, varCurrency : Result := Self;
//string
varOleStr,varString,varUString : Result := Self.VarToString.QuotedString;
//Datetime
varDate : Result := DateTimeToStr(Self.VarToDateTimes).QuotedString;
//empty or null
varEmpty,varNull : Result := EmptyStr;
end;
end;
function TDCVariantHelper.GetDefault: Variant;
begin
case Self.GetType of
//numeric
varSmallInt, varInteger, varBoolean, varShortInt,
varByte, varWord, varLongWord, varInt64, varUInt64 : Result := 0;
//Float
varSingle, varDouble, varCurrency : Result := 0;
//string
varOleStr,varString,varUString : Result := '';
//Datetime
varDate : Result := null;
//empty or null
varEmpty,varNull : Result := null;
end;
end;
function TDCVariantHelper.GetType: TVarType;
begin
Result := VarType(Self);
end;
function TDCVariantHelper.VarToDateTimes: TDateTime;
begin
Result := VarToDateTime(Self);
end;
function TDCVariantHelper.VarToString: string;
begin
Result := VarToStr(Self);
end;
end.
|
unit mygraphinmemory;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, dialogs, myGraph;
type
{ TMyGraphinMemory }
TMyGraphinMemory=class(TMyGraph)
private
FSorting: Boolean;
protected
procedure SortNodeInLevel(Level: TMyGraphLevel;Down:boolean=false);
public
constructor Create;virtual;
property Sorting:Boolean read FSorting write FSorting default false;
end;
function SortByPositionPredok(Item1, Item2: Pointer): integer;
function SortByPositionPotomok(Item1, Item2: Pointer): integer;
implementation
function SortByPositionPredok(Item1, Item2: Pointer): integer;
var
Node1, Node2:TMyGraphNode;
begin
Node1:=TMyGraphNode(Item1);
Node2:=TMyGraphNode(Item2);
if ((node1.inEdgecount=0)and(node2.inEdgecount=0))or
((Node1.inEdges[0].SourceTop.Level.IndexOfNode(Node1.inEdges[0].SourceTop)=Node2.inEdges[0].SourceTop.Level.IndexOfNode(Node2.inEdges[0].SourceTop))and
(Node1.Level.IndexOfNode(node1)=node2.Level.IndexOfNode(node2)))then
begin
result:=0;
exit;
end else
if (Node1.inEdges[0].SourceTop.Level.IndexOfNode(Node1.inEdges[0].SourceTop)<Node2.inEdges[0].SourceTop.Level.IndexOfNode(Node2.inEdges[0].SourceTop))or
((Node1.inEdges[0].SourceTop.Level.IndexOfNode(Node1.inEdges[0].SourceTop)=Node2.inEdges[0].SourceTop.Level.IndexOfNode(Node2.inEdges[0].SourceTop))and
(Node1.Level.IndexOfNode(node1)<node2.Level.IndexOfNode(node2)))
then
result:=-1
else
if (Node1.inEdges[0].SourceTop.Level.IndexOfNode(Node1.inEdges[0].SourceTop)>Node2.inEdges[0].SourceTop.Level.IndexOfNode(Node2.inEdges[0].SourceTop))or
((Node1.inEdges[0].SourceTop.Level.IndexOfNode(Node1.inEdges[0].SourceTop)=Node2.inEdges[0].SourceTop.Level.IndexOfNode(Node2.inEdges[0].SourceTop))and
(Node1.Level.IndexOfNode(node1)>node2.Level.IndexOfNode(node2)))
then
result:=1;
end;
function SortByPositionPotomok(Item1, Item2: Pointer): integer;
var
Node1, Node2:TMyGraphNode;
begin
Node1:=TMyGraphNode(Item1);
Node2:=TMyGraphNode(Item2);
if ((node1.outEdgecount=0)and(node2.outEdgecount=0))or
(Node1.outEdges[0].TargetBottom.Level.IndexOfNode(Node1.outEdges[0].TargetBottom)=Node2.outEdges[0].TargetBottom.Level.IndexOfNode(Node2.outEdges[0].TargetBottom))then
begin
result:=0;
exit;
end else
if Node1.outEdges[0].TargetBottom.Level.IndexOfNode(Node1.outEdges[0].TargetBottom)<Node2.outEdges[0].TargetBottom.Level.IndexOfNode(Node2.outEdges[0].TargetBottom)
then result:=-1 else
if Node1.outEdges[0].TargetBottom.Level.IndexOfNode(Node1.outEdges[0].TargetBottom)>Node2.outEdges[0].TargetBottom.Level.IndexOfNode(Node2.outEdges[0].TargetBottom)
then result:=1;
end;
procedure TMyGraphinMemory.SortNodeInLevel(Level: TMyGraphLevel; Down: boolean);
begin
if not Down then
begin
if (GetLevelNumber(Level)=0)then exit;
Level.Sort(@SortByPositionPredok);
end
else
begin
if (GetLevelNumber(Level)=countLevel-1)or (level.countNode<=1) then exit;
Level.Sort(@SortByPositionPotomok);
end;
end;
constructor TMyGraphinMemory.Create;
begin
inherited Create;
FSorting:=false;
end;
end.
|
Network Working Group Zaw-Sing Su (SRI)
Request for Comments: 819 Jon Postel (ISI)
August 1982
The Domain Naming Convention for Internet User Applications
1. Introduction
For many years, the naming convention "<user>@<host>" has served the
ARPANET user community for its mail system, and the substring
"<host>" has been used for other applications such as file transfer
(FTP) and terminal access (Telnet). With the advent of network
interconnection, this naming convention needs to be generalized to
accommodate internetworking. A decision has recently been reached to
replace the simple name field, "<host>", by a composite name field,
"<domain>" [2]. This note is an attempt to clarify this generalized
naming convention, the Internet Naming Convention, and to explore the
implications of its adoption for Internet name service and user
applications.
The following example illustrates the changes in naming convention:
ARPANET Convention: Fred@ISIF
Internet Convention: Fred@F.ISI.ARPA
The intent is that the Internet names be used to form a
tree-structured administrative dependent, rather than a strictly
topology dependent, hierarchy. The left-to-right string of name
components proceeds from the most specific to the most general, that
is, the root of the tree, the administrative universe, is on the
right.
The name service for realizing the Internet naming convention is
assumed to be application independent. It is not a part of any
particular application, but rather an independent name service serves
different user applications.
2. The Structural Model
The Internet naming convention is based on the domain concept. The
name of a domain consists of a concatenation of one or more <simple
names>. A domain can be considered as a region of jurisdiction for
name assignment and of responsibility for name-to-address
translation. The set of domains forms a hierarchy.
Using a graph theory representation, this hierarchy may be modeled as
a directed graph. A directed graph consists of a set of nodes and a
Su & Postel [Page 1]
RFC 819 August 1982;
collection of arcs, where arcs are identified by ordered pairs of
distinct nodes [1]. Each node of the graph represents a domain. An
ordered pair (B, A), an arc from B to A, indicates that B is a
subdomain of domain A, and B is a simple name unique within A. We
will refer to B as a child of A, and A a parent of B. The directed
graph that best describes the naming hierarchy is called an
"in-tree", which is a rooted tree with all arcs directed towards the
root (Figure 1). The root of the tree represents the naming universe,
ancestor of all domains. Endpoints (or leaves) of the tree are the
lowest-level domains.
U
/ | \
/ | \ U -- Naming Universe
^ ^ ^ I -- Intermediate Domain
| | | E -- Endpoint Domain
I E I
/ \ |
^ ^ ^
| | |
E E I
/ | \
^ ^ ^
| | |
E E E
Figure 1
The In-Tree Model for Domain Hierarchy
The simple name of a child in this model is necessarily unique within
its parent domain. Since the simple name of the child's parent is
unique within the child's grandparent domain, the child can be
uniquely named in its grandparent domain by the concatenation of its
simple name followed by its parent's simple name.
For example, if the simple name of a child is "C1" then no other
child of the same parent may be named "C1". Further, if the
parent of this child is named "P1", then "P1" is a unique simple
name in the child's grandparent domain. Thus, the concatenation
C1.P1 is unique in C1's grandparent domain.
Similarly, each element of the hierarchy is uniquely named in the
universe by its complete name, the concatenation of its simple name
and those for the domains along the trail leading to the naming
universe.
The hierarchical structure of the Internet naming convention supports
decentralization of naming authority and distribution of name service
capability. We assume a naming authority and a name server
Su & Postel [Page 2]
RFC 819 August 1982;
associated with each domain. In Sections 5 and 6 respectively the
name service and the naming authority are discussed.
Within an endpoint domain, unique names are assigned to <user>
representing user mailboxes. User mailboxes may be viewed as
children of their respective domains.
In reality, anomalies may exist violating the in-tree model of naming
hierarchy. Overlapping domains imply multiple parentage, i.e., an
entity of the naming hierarchy being a child of more than one domain.
It is conceivable that ISI can be a member of the ARPA domain as well
as a member of the USC domain (Figure 2). Such a relation
constitutes an anomaly to the rule of one-connectivity between any
two points of a tree. The common child and the sub-tree below it
become descendants of both parent domains.
U
/ | \
/ . \
. . ARPA
. . | \
USC | \
\ | .
\ | .
ISI
Figure 2
Anomaly in the In-Tree Model
Some issues resulting from multiple parentage are addressed in
Appendix B. The general implications of multiple parentage are a
subject for further investigation.
3. Advantage of Absolute Naming
Absolute naming implies that the (complete) names are assigned with
respect to a universal reference point. The advantage of absolute
naming is that a name thus assigned can be universally interpreted
with respect to the universal reference point. The Internet naming
convention provides absolute naming with the naming universe as its
universal reference point.
For relative naming, an entity is named depending upon the position
of the naming entity relative to that of the named entity. A set of
hosts running the "unix" operating system exchange mail using a
method called "uucp". The naming convention employed by uucp is an
example of relative naming. The mail recipient is typically named by
a source route identifying a chain of locally known hosts linking the
Su & Postel [Page 3]
RFC 819 August 1982;
sender's host to the recipient's. A destination name can be, for
example,
"alpha!beta!gamma!john",
where "alpha" is presumably known to the originating host, "beta" is
known to "alpha", and so on.
The uucp mail system has demonstrated many of the problems inherent
to relative naming. When the host names are only locally
interpretable, routing optimization becomes impossible. A reply
message may have to traverse the reverse route to the original sender
in order to be forwarded to other parties.
Furthermore, if a message is forwarded by one of the original
recipients or passed on as the text of another message, the frame of
reference of the relative source route can be completely lost. Such
relative naming schemes have severe problems for many of the uses
that we depend upon in the ARPA Internet community.
4. Interoperability
To allow interoperation with a different naming convention, the names
assigned by a foreign naming convention need to be accommodated.
Given the autonomous nature of domains, a foreign naming environment
may be incorporated as a domain anywhere in the hierarchy. Within
the naming universe, the name service for a domain is provided within
that domain. Thus, a foreign naming convention can be independent of
the Internet naming convention. What is implied here is that no
standard convention for naming needs to be imposed to allow
interoperations among heterogeneous naming environments.
For example:
There might be a naming convention, say, in the FOO world,
something like "<user>%<host>%<area>". Communications with an
entity in that environment can be achieved from the Internet
community by simply appending ".FOO" on the end of the name in
that foreign convention.
John%ISI-Tops20-7%California.FOO
Another example:
One way of accommodating the "uucp world" described in the last
section is to declare it as a foreign system. Thus, a uucp
name
"alpha!beta!gamma!john"
Su & Postel [Page 4]
RFC 819 August 1982;
might be known in the Internet community as
"alpha!beta!gamma!john.UUCP".
Communicating with a complex subdomain is another case which can
be treated as interoperation. A complex subdomain is a domain
with complex internal naming structure presumably unknown to the
outside world (or the outside world does not care to be concerned
with its complexity).
For the mail system application, the names embedded in the message
text are often used by the destination for such purpose as to reply
to the original message. Thus, the embedded names may need to be
converted for the benefit of the name server in the destination
environment.
Conversion of names on the boundary between heterogeneous naming
environments is a complex subject. The following example illustrates
some of the involved issues.
For example:
A message is sent from the Internet community to the FOO
environment. It may bear the "From" and "To" fields as:
From: Fred@F.ISI.ARPA
To: John%ISI-Tops20-7%California.FOO
where "FOO" is a domain independent of the Internet naming
environment. The interface on the boundary of the two
environments may be represented by a software module. We may
assume this interface to be an entity of the Internet community
as well as an entity of the FOO community. For the benefit of
the FOO environment, the "From" and "To" fields need to be
modified upon the message's arrival at the boundary. One may
view naming as a separate layer of protocol, and treat
conversion as a protocol translation. The matter is
complicated when the message is sent to more than one
destination within different naming environments; or the
message is destined within an environment not sharing boundary
with the originating naming environment.
While the general subject concerning conversion is beyond the scope
of this note, a few questions are raised in Appendix D.
Su & Postel [Page 5]
RFC 819 August 1982;
5. Name Service
Name service is a network service providing name-to-address
translation. Such service may be achieved in a number of ways. For
a simple networking environment, it can be accomplished with a single
central database containing name-to-address correspondence for all
the pertinent network entities, such as hosts.
In the case of the old ARPANET host names, a central database is
duplicated in each individual host. The originating module of an
application process would query the local name service (e.g., make a
system call) to obtain network address for the destination host. With
the proliferation of networks and an accelerating increase in the
number of hosts participating in networking, the ever growing size,
update frequency, and the dissemination of the central database makes
this approach unmanageable.
The hierarchical structure of the Internet naming convention supports
decentralization of naming authority and distribution of name service
capability. It readily accommodates growth of the naming universe.
It allows an arbitrary number of hierarchical layers. The addition
of a new domain adds little complexity to an existing Internet
system.
The name service at each domain is assumed to be provided by one or
more name servers. There are two models for how a name server
completes its work, these might be called "iterative" and
"recursive".
For an iterative name server there may be two kinds of responses.
The first kind of response is a destination address. The second
kind of response is the address of another name server. If the
response is a destination address, then the query is satisfied. If
the response is the address of another name server, then the query
must be repeated using that name server, and so on until a
destination address is obtained.
For a recursive name server there is only one kind of response --
a destination address. This puts an obligation on the name server
to actually make the call on another name server if it can't
answer the query itself.
It is noted that looping can be avoided since the names presented for
translation can only be of finite concatenation. However, care
should be taken in employing mechanisms such as a pointer to the next
simple name for resolution.
We believe that some name servers will be recursive, but we don't
believe that all will be. This means that the caller must be
Su & Postel [Page 6]
RFC 819 August 1982;
prepared for either type of server. Further discussion and examples
of name service is given in Appendix C.
The basic name service at each domain is the translation of simple
names to addresses for all of its children. However, if only this
basic name service is provided, the use of complete (or fully
qualified) names would be required. Such requirement can be
unreasonable in practice. Thus, we propose the use of partial names
in the context in which their uniqueness is preserved. By
construction, naming uniqueness is preserved within the domain of a
common ancestry. Thus, a partially qualified name is constructed by
omitting from the complete name ancestors common to the communicating
parties. When a partially qualified name leaves its context of
uniqueness it must be additionally qualified.
The use of partially qualified names places a requirement on the
Internet name service. To satisfy this requirement, the name service
at each domain must be capable of, in addition to the basic service,
resolving simple names for all of its ancestors (including itself)
and their children. In Appendix B, the required distinction among
simple names for such resolution is addressed.
6. Naming Authority
Associated with each domain there must be a naming authority to
assign simple names and ensure proper distinction among simple names.
Note that if the use of partially qualified names is allowed in a
sub-domain, the uniqueness of simple names inside that sub-domain is
insufficient to avoid ambiguity with names outside the subdomain.
Appendix B discusses simple name assignment in a sub-domain that
would allow the use of partially qualified names without ambiguity.
Administratively, associated with each domain there is a single
person (or office) called the registrar. The registrar of the naming
universe specifies the top-level set of domains and designates a
registrar for each of these domains. The registrar for any given
domain maintains the naming authority for that domain.
7. Network-Oriented Applications
For user applications such as file transfer and terminal access, the
remote host needs to be named. To be compatible with ARPANET naming
convention, a host can be treated as an endpoint domain.
Many operating systems or programming language run-time environments
provide functions or calls (JSYSs, SVCs, UUOs, SYSs, etc.) for
standard services (e.g., time-of-day, account-of-logged-in-user,
convert-number-to-string). It is likely to be very helpful if such a
Su & Postel [Page 7]
RFC 819 August 1982;
function or call is developed for translating a host name to an
address. Indeed, several systems on the ARPANET already have such
facilities for translating an ARPANET host name into an ARPANET
address based on internal tables.
We recommend that this provision of a standard function or call for
translating names to addresses be extended to accept names of
Internet convention. This will promote a consistent interface to the
users of programs involving internetwork activities. The standard
facility for translating Internet names to Internet addresses should
include all the mechanisms available on the host, such as checking a
local table or cache of recently checked names, or consulting a name
server via the Internet.
8. Mail Relaying
Relaying is a feature adopted by more and more mail systems.
Relaying facilitates, among other things, interoperations between
heterogeneous mail systems. The term "relay" is used to describe the
situation where a message is routed via one or more intermediate
points between the sender and the recipient. The mail relays are
normally specified explicitly as relay points in the instructions for
message delivery. Usually, each of the intermediate relays assume
responsibility for the relayed message [3].
A point should be made on the basic difference between mail
relaying and the uucp naming system. The difference is that
although mail relaying with absolute naming can also be considered
as a form of source routing, the names of each intermediate points
and that of the destination are universally interpretable, while
the host names along a source route of the uucp convention is
relative and thus only locally interpretable.
The Internet naming convention explicitly allows interoperations
among heterogeneous systems. This implies that the originator of a
communication may name a destination which resides in a foreign
system. The probability is that the destination network address may
not be comprehensible to the transport system of the originator.
Thus, an implicit relaying mechanism is called for at the boundary
between the domains. The function of this implicit relay is the same
as the explicit relay.
Su & Postel [Page 8]
RFC 819 August 1982;
9. Implementation
The Actual Domains
The initial set of top-level names include:
ARPA
This represents the set of organizations involved in the
Internet system through the authority of the U.S. Defense
Advanced Research Projects Agency. This includes all the
research and development hosts on the ARPANET and hosts on
many other nets as well. But note very carefully that the
top-level domain "ARPA" does not map one-to-one with the
ARPANET -- domains are administrative, not topological.
Transition
In the transition from the ARPANET naming convention to the
Internet naming convention, a host name may be used as a simple
name for an endpoint domain. Thus, if "USC-ISIF" is an ARPANET
host name, then "USC-ISIF.ARPA" is the name of an Internet domain.
10. Summary
A hierarchical naming convention based on the domain concept has been
adopted by the Internet community. It is an absolute naming
convention defined along administrative rather than topological
boundaries. This naming convention is adaptive for interoperations
with other naming conventions. Thus, no standard convention needs to
be imposed for interoperations among heterogeneous naming
environments.
This Internet naming convention allows distributed name service and
naming authority functions at each domain. We have specified these
functions required at each domain. Also discussed are implications
on network-oriented applications, mail systems, and administrative
aspects of this convention.
Su & Postel [Page 9]
RFC 819 August 1982;
APPENDIX A
The BNF Specification
We present here a rather detailed "BNF" definition of the allowed
form for a computer mail "mailbox" composed of a "local-part" and a
"domain" (separated by an at sign). Clearly, the domain can be used
separately in other network-oriented applications.
<mailbox> ::= <local-part> "@" <domain>
<local-part> ::= <string> | <quoted-string>
<string> ::= <char> | <char> <string>
<quoted-string> ::= """ <qtext> """
<qtext> ::= "\" <x> | "\" <x> <qtext> | <q> | <q> <qtext>
<char> ::= <c> | "\" <x>
<domain> ::= <naming-domain> | <naming-domain> "." <domain>
<naming-domain> ::= <simple-name> | <address>
<simple-name> ::= <a> <ldh-str> <let-dig>
<ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
<let-dig> ::= <a> | <d>
<let-dig-hyp> ::= <a> | <d> | "-"
<address> :: = "#" <number> | "[" <dotnum> "]"
<number> ::= <d> | <d> <number>
<dotnum> ::= <snum> "." <snum> "." <snum> "." <snum>
<snum> ::= one, two, or three digits representing a decimal integer
value in the range 0 through 255
<a> ::= any one of the 52 alphabetic characters A through Z in upper
case and a through z in lower case
<c> ::= any one of the 128 ASCII characters except <s> or <SP>
<d> ::= any one of the ten digits 0 through 9
Su & Postel [Page 10]
RFC 819 August 1982;
<q> ::= any one of the 128 ASCII characters except CR, LF, quote ("),
or backslash (\)
<x> ::= any one of the 128 ASCII characters (no exceptions)
<s> ::= "<", ">", "(", ")", "[", "]", "\", ".", ",", ";", ":", "@",
""", and the control characters (ASCII codes 0 through 31 inclusive
and 127)
Note that the backslash, "\", is a quote character, which is used to
indicate that the next character is to be used literally (instead of
its normal interpretation). For example, "Joe\,Smith" could be used
to indicate a single nine character user field with comma being the
fourth character of the field.
The simple names that make up a domain may contain both upper and
lower case letters (as well as digits and hyphen), but these names
are not case sensitive.
Hosts are generally known by names. Sometimes a host is not known to
the translation function and communication is blocked. To bypass
this barrier two forms of addresses are also allowed for host
"names". One form is a decimal integer prefixed by a pound sign, "#".
Another form, called "dotted decimal", is four small decimal integers
separated by dots and enclosed by brackets, e.g., "[123.255.37.2]",
which indicates a 32-bit ARPA Internet Address in four 8-bit fields.
(Of course, these numeric address forms are specific to the Internet,
other forms may have to be provided if this problem arises in other
transport systems.)
Su & Postel [Page 11]
RFC 819 August 1982;
APPENDIX B
An Aside on the Assignment of Simple Names
In the following example, there are two naming hierarchies joining at
the naming universe 'U'. One consists of domains (S, R, N, J, P, Q,
B, A); and the other (L, E, F, G, H, D, C, K, B, A). Domain B is
assumed to have multiple parentage as shown.
U
/ \
/ \
J L
/ \
N E
/ \ / \
R P D F
/ \ | \ \
S Q C (X) G
\ / \ \
B K H
/
A
Figure 3
Illustration of Requirements for the Distinction of Simple Names
Suppose someone at A tries to initiate communication with destination
H. The fully qualified destination name would be
H.G.F.E.L.U
Omitting common ancestors, the partially qualified name for the
destination would be
H.G.F
To permit the case of partially qualified names, name server at A
needs to resolve the simple name F, i.e., F needs to be distinct from
all the other simple names in its database.
To enable the name server of a domain to resolve simple names, a
simple name for a child needs to be assigned distinct from those of
all of its ancestors and their immediate children. However, such
distinction would not be sufficient to allow simple name resolution
at lower-level domains because lower-level domains could have
multiple parentage below the level of this domain.
In the example above, let us assume that a name is to be assigned
Su & Postel [Page 12]
RFC 819 August 1982;
to a new domain X by D. To allow name server at D to resolve
simple names, the name for X must be distinct from L, E, D, C, F,
and J. However, allowing A to resolve simple names, X needs to be
also distinct from A, B, K, as well as from Q, P, N, and R.
The following observations can be made.
Simple names along parallel trails (distinct trails leading from
one domain to the naming universe) must be distinct, e.g., N must
be distinct from E for B or A to properly resolve simple names.
No universal uniqueness of simple names is called for, e.g., the
simple name S does not have to be distinct from that of E, F, G,
H, D, C, K, Q, B, or A.
The lower the level at which a domain occurs, the more immune it
is to the requirement of naming uniqueness.
To satisfy the required distinction of simple names for proper
resolution at all levels, a naming authority needs to ensure the
simple name to be assigned distinct from those in the name server
databases at the endpoint naming domains within its domain. As an
example, for D to assign a simple name for X, it would need to
consult databases at A and K. It is, however, acceptable to have
simple names under domain A identical with those under K. Failure of
such distinct assignment of simple names by naming authority of one
domain would jeopardize the capability of simple name resolution for
entities within the subtree under that domain.
Su & Postel [Page 13]
RFC 819 August 1982;
APPENDIX C
Further Discussion of Name Service and Name Servers
The name service on a system should appear to the programmer of an
application program simply as a system call or library subroutine.
Within that call or subroutine there may be several types of methods
for resolving the name string into an address.
First, a local table may be consulted. This table may be a
complete table and may be updated frequently, or it may simply be
a cache of the few latest name to address mappings recently
determined.
Second, a call may be made to a name server to resolve the string
into a destination address.
Third, a call may be made to a name server to resolve the string
into a relay address.
Whenever a name server is called it may be a recursive server or an
interactive server.
If the server is recursive, the caller won't be able to tell if
the server itself had the information to resolve the query or
called another server recursively (except perhaps for the time it
takes).
If the server is iterative, the caller must be prepared for either
the answer to its query, or a response indicating that it should
call on a different server.
It should be noted that the main name service discussed in this memo
is simply a name string to address service. For some applications
there may be other services needed.
For example, even within the Internet there are several procedures
or protocols for actually transferring mail. One need is to
determine which mail procedures a destination host can use.
Another need is to determine the name of a relay host if the
source and destination hosts do not have a common mail procedure.
These more specialized services must be specific to each
application since the answers may be application dependent, but
the basic name to address translation is application independent.
Su & Postel [Page 14]
RFC 819 August 1982;
APPENDIX D
Further Discussion of Interoperability and Protocol Translations
The translation of protocols from one system to another is often
quite difficult. Following are some questions that stem from
considering the translations of addresses between mail systems:
What is the impact of different addressing environments (i.e.,
environments of different address formats)?
It is noted that the boundary of naming environment may or may not
coincide with the boundary of different mail systems. Should the
conversion of naming be independent of the application system?
The boundary between different addressing environments may or may
not coincide with that of different naming environments or
application systems. Some generic approach appears to be
necessary.
If the conversion of naming is to be independent of the
application system, some form of interaction appears necessary
between the interface module of naming conversion with some
application level functions, such as the parsing and modification
of message text.
To accommodate encryption, conversion may not be desirable at all.
What then can be an alternative to conversion?
Su & Postel [Page 15]
RFC 819 August 1982;
GLOSSARY
address
An address is a numerical identifier for the topological location
of the named entity.
name
A name is an alphanumeric identifier associated with the named
entity. For unique identification, a name needs to be unique in
the context in which the name is used. A name can be mapped to an
address.
complete (fully qualified) name
A complete name is a concatenation of simple names representing
the hierarchical relation of the named with respect to the naming
universe, that is it is the concatenation of the simple names of
the domain structure tree nodes starting with its own name and
ending with the top level node name. It is a unique name in the
naming universe.
partially qualified name
A partially qualified name is an abbreviation of the complete name
omitting simple names of the common ancestors of the communicating
parties.
simple name
A simple name is an alphanumeric identifier unique only within its
parent domain.
domain
A domain defines a region of jurisdiction for name assignment and
of responsibility for name-to-address translation.
naming universe
Naming universe is the ancestor of all network entities.
naming environment
A networking environment employing a specific naming convention.
Su & Postel [Page 16]
RFC 819 August 1982;
name service
Name service is a network service for name-to-address mapping.
name server
A name server is a network mechanism (e.g., a process) realizing
the function of name service.
naming authority
Naming authority is an administrative entity having the authority
for assigning simple names and responsibility for resolving naming
conflict.
parallel relations
A network entity may have one or more hierarchical relations with
respect to the naming universe. Such multiple relations are
parallel relations to each other.
multiple parentage
A network entity has multiple parentage when it is assigned a
simple name by more than one naming domain.
Su & Postel [Page 17]
RFC 819 August 1982;
REFERENCES
[1] F. Harary, "Graph Theory", Addison-Wesley, Reading,
Massachusetts, 1969.
[2] J. Postel, "Computer Mail Meeting Notes", RFC-805,
USC/Information Sciences Institute, 8 February 1982.
[3] J. Postel, "Simple Mail Transfer Protocol", RFC-821,
USC/Information Sciences Institute, August 1982.
[4] D. Crocker, "Standard for the Format of ARPA Internet Text
Messages", RFC-822, Department of Electrical Engineering, University
of Delaware, August 1982.
Su & Postel [Page 18]
# $Copyright: $
# Copyright (c) 1984, 1985, 1986, 1987, 1988, 1989, 1990
# Sequent Computer Systems, Inc. All rights reserved.
#
# This software is furnished under a license and may be used
# only in accordance with the terms of that license and with the
# inclusion of the above copyright notice. This software may not
# be provided or otherwise made available to, or used by, any
# other person. No title to or ownership of the software is
# hereby transferred.
|
{-----------------------------------------------------------------------------
TrendFollowert Name:
Author: Roman
Purpose:
History:
-----------------------------------------------------------------------------}
unit FC.Trade.Alerter.ParabolicTrend;
{$I Compiler.inc}
//{$DEFINE SMALL_ORDER}
interface
uses
Types, Windows, Classes, Math,Contnrs, Forms, Controls, SysUtils, BaseUtils, ActnList,
Collections.Map, Properties.Obj, Properties.Definitions,
StockChart.Definitions, StockChart.Definitions.Units, Properties.Controls, StockChart.Indicators,
Serialization, FC.Definitions, FC.Trade.Alerter.Base,FC.fmUIDataStorage,
StockChart.Definitions.Drawing,Graphics;
type
IStockAlerterTrendFollower = interface
['{15D0F49A-6117-4D9C-8E63-273C53CD786C}']
end;
TStockAlerterTrendFollower = class (TStockAlerterBase,IStockAlerterTrendFollower)
private
//Это временные переменные, испольщуемые при трейдинге
FPbSARs: array [TStockTimeInterval] of ISCIndicatorParabolicSAR;
FPbSAR15mFast: ISCIndicatorParabolicSAR;
FIndexes: array [TStockTimeInterval] of integer;
FPassedPoints:TMap<string,integer>;
procedure TryOpenOrder(const aTime: TDateTime);
protected
procedure GetProperties(aList: TPropertyList); override;
procedure OnPropertyChanged(aNotifier:TProperty); override;
function CreateIndicatorPbSAR(const aChart: IStockChart): ISCIndicatorParabolicSAR;
procedure InitPbSAR(const aPbSAR:ISCIndicatorParabolicSAR; it:TStockTimeInterval);
function CreateCalendarIndicator(const aChart: IStockChart): ISCIndicatorCalendar;
public
function GetIndicatorPbSAR(it:TStockTimeInterval):ISCIndicatorParabolicSAR;
procedure SetProject(const aValue : IStockProject); override;
procedure OnBeginWorkSession; override;
//Посчитать
procedure UpdateStep2(const aTime: TDateTime); override;
constructor Create; override;
destructor Destroy; override;
procedure Dispose; override;
end;
implementation
uses Variants,DateUtils, SystemService, Application.Definitions, FC.Trade.OrderCollection,
StockChart.Indicators.Properties.Dialog, FC.Trade.Alerter.Factory,
FC.DataUtils;
const
TrendToOrderKind : array [TSCTrendType] of TStockOrderKind = (okBuy,okSell,okBuy);
{ TStockAlerterTrendFollower }
constructor TStockAlerterTrendFollower.Create;
begin
inherited Create;
FPassedPoints:=TMap<string,integer>.Create;
end;
function TStockAlerterTrendFollower.CreateCalendarIndicator(const aChart: IStockChart): ISCIndicatorCalendar;
var
aCreated: boolean;
begin
result:=CreateOrFindIndicator(aChart,ISCIndicatorCalendar,'IndicatorCalendar-'+aChart.StockSymbol.GetTimeIntervalName,true, aCreated) as ISCIndicatorCalendar;
if aCreated then
result.SetCountryFilter('США;Еврозона;Германия');
end;
destructor TStockAlerterTrendFollower.Destroy;
begin
inherited;
FreeAndNil(FPassedPoints);
end;
procedure TStockAlerterTrendFollower.Dispose;
begin
inherited;
end;
function TStockAlerterTrendFollower.CreateIndicatorPbSAR(const aChart: IStockChart): ISCIndicatorParabolicSAR;
var
aCreated: boolean;
begin
result:=CreateOrFindIndicator(aChart,ISCIndicatorParabolicSAR,'ParabolicSAR-'+aChart.StockSymbol.GetTimeIntervalName,true,aCreated) as ISCIndicatorParabolicSAR;
if aCreated then
begin
InitPbSAR(result,aChart.StockSymbol.TimeInterval);
end;
end;
procedure TStockAlerterTrendFollower.GetProperties(aList: TPropertyList);
begin
inherited;
end;
procedure TStockAlerterTrendFollower.OnBeginWorkSession;
begin
inherited;
FPassedPoints.Clear;
end;
procedure TStockAlerterTrendFollower.OnPropertyChanged(aNotifier: TProperty);
begin
inherited;
end;
procedure TStockAlerterTrendFollower.SetProject(const aValue: IStockProject);
var
it: TStockTimeInterval;
aCreated: boolean;
begin
if GetProject=aValue then
exit;
inherited;
if aValue <> nil then
begin
for it:=low(TStockTimeInterval) to high(TStockTimeInterval) do
FPbSARs[it]:=CreateIndicatorPbSAR(aValue.GetStockChart(it));
FPbSAR15mFast:=CreateOrFindIndicator(
aValue.GetStockChart(sti15),
ISCIndicatorParabolicSAR,
'ParabolicSAR(Fast)-'+aValue.GetStockChart(sti15).StockSymbol.GetTimeIntervalName,
true,aCreated) as ISCIndicatorParabolicSAR;
if aCreated then
FPbSAR15mFast.SetStep(0.04);
end;
end;
procedure TStockAlerterTrendFollower.UpdateStep2(const aTime: TDateTime);
begin
FIndexes[sti1]:=FPbSARs[sti1].GetInputData.FindExactMatched(aTime);
FIndexes[sti5]:=FPbSARs[sti5].GetInputData.FindExactMatched(aTime);
FIndexes[sti15]:=FPbSARs[sti15].GetInputData.FindExactMatched(aTime);
FIndexes[sti60]:=FPbSARs[sti60].GetInputData.FindExactMatched(aTime);
FIndexes[sti240]:=FPbSARs[sti240].GetInputData.FindExactMatched(aTime);
FIndexes[sti720]:=FPbSARs[sti720].GetInputData.FindExactMatched(aTime);
TryOpenOrder(aTime);
end;
function TStockAlerterTrendFollower.GetIndicatorPbSAR(it: TStockTimeInterval): ISCIndicatorParabolicSAR;
begin
result:=FPbSARs[it];
end;
procedure TStockAlerterTrendFollower.InitPbSAR(const aPbSAR:ISCIndicatorParabolicSAR; it:TStockTimeInterval);
begin
if it=sti60 then
aPbSAR.SetStep(0.03)
else if it = sti240 then
aPbSAR.SetStep(0.04);
end;
procedure TStockAlerterTrendFollower.TryOpenOrder(const aTime: TDateTime);
type
TOperationType = (otNothing, otSetStopOrder,otWait,otOpenImmediate);
var
aOpenDirs: array[TStockTimeInterval] of TStockOrderKind;
aFast15mDir:TStockOrderKind;
aMainDir : TStockOrderKind;
aOperationType: TOperationType;
aTrendStart,aTrendStop: integer;
s: string;
begin
if (FIndexes[sti5]=-1) or (FIndexes[sti15]=-1) or (FIndexes[sti60]=-1) or (FIndexes[sti240]=-1) then
exit;
aOperationType:=otNothing;
//OpenDirs of PbSAR
aOpenDirs[sti5]:=TrendToOrderKind[FPbSARs[sti5].GetTrendDirection(FIndexes[sti5])];
aOpenDirs[sti15]:=TrendToOrderKind[FPbSARs[sti15].GetTrendDirection(FIndexes[sti15])];
aOpenDirs[sti60]:=TrendToOrderKind[FPbSARs[sti60].GetTrendDirection(FIndexes[sti60])];
aOpenDirs[sti240]:=TrendToOrderKind[FPbSARs[sti240].GetTrendDirection(FIndexes[sti240])];
aOpenDirs[sti720]:=TrendToOrderKind[FPbSARs[sti720].GetTrendDirection(FIndexes[sti720])];
aFast15mDir:=TrendToOrderKind[FPbSAR15mFast.GetTrendDirection(FIndexes[sti15])];
aMainDir:=aOpenDirs[sti240];
//Если часовой параболик идет против основного, то анализируем более подробно
if aMainDir<>aOpenDirs[sti60] then
begin
aOperationType:=otWait;
end;
//15-минутный тренд не совпадает с основным трендом
if (aOperationType<>otWait) and (aMainDir<>aOpenDirs[sti15]) then
begin
//Если хотя бы fast parabolic похож, тогда имеет смысл поставить стоповый ордер
if aFast15mDir=aMainDir then
begin
aOperationType:=otSetStopOrder;
end
else begin
aOperationType:=otWait;
end;
end;
//15-минутный тренд совпадает, но он только что начался, и в
//свете того, что весь тренд выглядит шатко-валко, мы ждем подтверждения
if (aOperationType<>otWait) and (FPbSAR15mFast.GetTrendLength(FIndexes[sti15])<=1) then
begin
aOperationType:=otWait;
end;
//5-минутный тренд не совпадает с 15-минутным
if not (aOperationType in [otWait,otSetStopOrder]) and (aOpenDirs[sti15]<>aOpenDirs[sti5]) then
begin
aOperationType:=otSetStopOrder;
end;
if (aOperationType=otNothing) and
(aOpenDirs[sti15]=aMainDir) and
(aOpenDirs[sti5]=aMainDir) then
begin
aOperationType:=otOpenImmediate;
end;
if aOperationType=otOpenImmediate then
begin
FPbSARs[sti5].GetTrendBounds(FIndexes[sti5],aTrendStart,aTrendStop);
s:='All timeframes equal: '+OrderKindNames[aMainDir]+'. TrendStart='+IntToStr(aTrendStart);
//Если это все тот-же 5-минутный тренд, то мы ничего не говорим
if not FPassedPoints.Lookup(s) then
begin
AddMessage('All timeframes equal: '+OrderKindNames[aMainDir]);
FPassedPoints.Add(s,0);
end;
end;
end;
initialization
FC.Trade.Alerter.Factory.AlerterFactory.RegisterAlerter('Basic','Parabolic Trend',TStockAlerterTrendFollower,IStockAlerterTrendFollower);
end.
|
unit TreeListQuery;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, Vcl.StdCtrls, SearchCategoryQuery, NotifyEvents,
DuplicateCategoryQuery, DSWrap, BaseEventsQuery;
type
TTreeListW = class(TDSWrap)
private
FAfterSmartRefresh: TNotifyEventsEx;
FExternalID: TFieldWrap;
FID: TFieldWrap;
FParentId: TFieldWrap;
FqSearchCategory: TQuerySearchCategory;
FValue: TFieldWrap;
function GetIsRootFocused: Boolean;
function GetqSearchCategory: TQuerySearchCategory;
protected
property qSearchCategory: TQuerySearchCategory read GetqSearchCategory;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure AddChildCategory(const AValue: string; ALevel: Integer);
procedure AddRoot;
function CheckPossibility(const AParentID: Integer;
const AValue: String): Boolean;
procedure Delete;
procedure FilterByExternalID(AExternalID: string);
function LocateByExternalID(AExternalID: string;
AOptions: TFDDataSetLocateOptions = []): Boolean;
procedure LocateToRoot;
procedure SmartRefresh; override;
property AfterSmartRefresh: TNotifyEventsEx read FAfterSmartRefresh;
property ExternalID: TFieldWrap read FExternalID;
property ID: TFieldWrap read FID;
property IsRootFocused: Boolean read GetIsRootFocused;
property ParentId: TFieldWrap read FParentId;
property Value: TFieldWrap read FValue;
end;
TQueryTreeList = class(TQueryBaseEvents)
private
FAutoSearchDuplicate: Boolean;
FNeedRestoreAutoSearch: Boolean;
FOldAutoSearchDuplicate: Boolean;
FqDuplicateCategory: TQueryDuplicateCategory;
FW: TTreeListW;
procedure DoAfterOpen(Sender: TObject);
function GetqDuplicateCategory: TQueryDuplicateCategory;
procedure SetAutoSearchDuplicate(const Value: Boolean);
{ Private declarations }
protected
function CreateDSWrap: TDSWrap; override;
procedure DoAfterScroll(Sender: TObject);
public
constructor Create(AOwner: TComponent); override;
procedure GotoDuplicate;
property AutoSearchDuplicate: Boolean read FAutoSearchDuplicate
write SetAutoSearchDuplicate;
property qDuplicateCategory: TQueryDuplicateCategory
read GetqDuplicateCategory;
property W: TTreeListW read FW;
{ Public declarations }
end;
implementation
uses System.Generics.Collections, ProjectConst;
{$R *.dfm}
constructor TQueryTreeList.Create(AOwner: TComponent);
begin
inherited;
FW := FDSWrap as TTreeListW;
TNotifyEventWrap.Create(W.AfterOpen, DoAfterOpen, W.EventList);
TNotifyEventWrap.Create(W.AfterScrollM, DoAfterScroll, W.EventList);
end;
function TQueryTreeList.CreateDSWrap: TDSWrap;
begin
Result := TTreeListW.Create(FDQuery);
end;
procedure TQueryTreeList.DoAfterOpen(Sender: TObject);
begin
W.AddRoot;
end;
procedure TQueryTreeList.DoAfterScroll(Sender: TObject);
begin
if not FAutoSearchDuplicate then
begin
if FNeedRestoreAutoSearch then
begin
FNeedRestoreAutoSearch := False;
FAutoSearchDuplicate := FOldAutoSearchDuplicate;
end;
Exit;
end;
qDuplicateCategory.Search(W.PK.AsInteger);
end;
function TQueryTreeList.GetqDuplicateCategory: TQueryDuplicateCategory;
begin
if FqDuplicateCategory = nil then
FqDuplicateCategory := TQueryDuplicateCategory.Create(Self);
Result := FqDuplicateCategory;
end;
procedure TQueryTreeList.GotoDuplicate;
begin
FOldAutoSearchDuplicate := AutoSearchDuplicate;
FNeedRestoreAutoSearch := True;
AutoSearchDuplicate := False;
W.LocateByPK(qDuplicateCategory.W.ID.F.AsInteger);
end;
procedure TQueryTreeList.SetAutoSearchDuplicate(const Value: Boolean);
begin
if FAutoSearchDuplicate = Value then
Exit;
FAutoSearchDuplicate := Value;
if FAutoSearchDuplicate then
qDuplicateCategory.Search(W.PK.AsInteger);
end;
constructor TTreeListW.Create(AOwner: TComponent);
begin
inherited;
FID := TFieldWrap.Create(Self, 'ID', '', True);
FExternalID := TFieldWrap.Create(Self, 'ExternalID');
FParentId := TFieldWrap.Create(Self, 'ParentId');
FValue := TFieldWrap.Create(Self, 'Value');
FAfterSmartRefresh := TNotifyEventsEx.Create(Self);
end;
destructor TTreeListW.Destroy;
begin
FreeAndNil(FAfterSmartRefresh);
inherited;
end;
procedure TTreeListW.AddChildCategory(const AValue: string; ALevel: Integer);
var
AParentID: Variant;
AExternalID: string;
begin
Assert(DataSet.RecordCount > 0);
AParentID := PK.Value;
if not CheckPossibility(AParentID, AValue) then
Exit;
DataSet.DisableControls;
try
TryPost;
AExternalID := qSearchCategory.CalculateExternalId(AParentID, ALevel - 1);
TryAppend;
Value.F.AsString := AValue;
ParentId.F.AsInteger := AParentID;
ExternalID.F.AsString := AExternalID;
TryPost;
finally
DataSet.EnableControls;
end;
end;
// Добавляет корень дерева
procedure TTreeListW.AddRoot;
begin
Assert(DataSet.State = dsBrowse);
if DataSet.RecordCount = 0 then
begin
TryAppend;
Value.F.AsString := sTreeRootNodeName;
ExternalID.F.AsString := '00000';
TryPost;
end;
end;
function TTreeListW.CheckPossibility(const AParentID: Integer;
const AValue: String): Boolean;
begin
Assert(DataSet.Active);
Result := qSearchCategory.SearchByParentAndValue(AParentID, AValue) = 0;
end;
procedure TTreeListW.Delete;
begin
DataSet.DisableControls;
try
DataSet.Delete;
DataSet.Refresh;
// Если удалили всё, то заново добавляем корень
if DataSet.RecordCount = 0 then
AddRoot;
finally
DataSet.EnableControls;
end;
end;
procedure TTreeListW.FilterByExternalID(AExternalID: string);
begin
if AExternalID.Length > 0 then
begin
DataSet.Filter := Format('%s = ''%s*''', [ExternalID.FieldName,
AExternalID]);
DataSet.Filtered := True;
end
else
DataSet.Filtered := False;
end;
function TTreeListW.GetIsRootFocused: Boolean;
begin
Result := (DataSet.RecordCount > 0) and (ParentId.F.IsNull);
end;
function TTreeListW.GetqSearchCategory: TQuerySearchCategory;
begin
if FqSearchCategory = nil then
FqSearchCategory := TQuerySearchCategory.Create(Self);
Result := FqSearchCategory;
end;
function TTreeListW.LocateByExternalID(AExternalID: string;
AOptions: TFDDataSetLocateOptions = []): Boolean;
begin
Assert(not AExternalID.IsEmpty);
Result := FDDataSet.LocateEx(ExternalID.FieldName, AExternalID, AOptions);
end;
procedure TTreeListW.LocateToRoot;
begin
FDDataSet.LocateEx(ParentId.FieldName, NULL, []);
end;
procedure TTreeListW.SmartRefresh;
var
rc: Integer;
begin
rc := DataSet.RecordCount;
inherited;
// Если была одна запись а стало больше
if (rc = 1) and (DataSet.RecordCount > 1) then
FAfterSmartRefresh.CallEventHandlers(Self);
end;
end.
|
unit main;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, Menus, ExtCtrls,
ComCtrls, Buttons, ActnList, StdCtrls, RichMemo, RichMemoUtils,
about, rtfprocessor;
type
{ TfrmMain }
TfrmMain = class(TForm)
actFileOpen: TAction;
actHelpAbout: TAction;
actGenerateCMT: TAction;
actInsertMark: TAction;
actFileSave: TAction;
mmoLog: TMemo;
mniFileSave: TMenuItem;
mniInsertMark: TMenuItem;
mniInsert: TMenuItem;
mmoMain: TRichMemo;
lstActions: TActionList;
mniGenerateCMT: TMenuItem;
mniGenerate: TMenuItem;
mniFileOpen: TMenuItem;
mniHelpAbout: TMenuItem;
mniHelp: TMenuItem;
mniFile: TMenuItem;
mnuMain: TMainMenu;
diaOpen: TOpenDialog;
pnlToolbar: TPanel;
btnFileOpen: TSpeedButton;
btnGenerateCMT: TSpeedButton;
progressBar: TProgressBar;
diaSave: TSaveDialog;
SpeedButton1: TSpeedButton;
SpeedButton2: TSpeedButton;
Splitter1: TSplitter;
StatusBar1: TStatusBar;
procedure actFileOpenExecute(Sender: TObject);
procedure actFileSaveExecute(Sender: TObject);
procedure actGenerateCMTExecute(Sender: TObject);
procedure actHelpAboutExecute(Sender: TObject);
procedure actInsertMarkExecute(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
procedure StateBusy;
procedure StateNormal;
procedure ProcessCommandline;
procedure LoadFile(filename: String);
procedure GenerateCmt(dest: String);
public
procedure procProgress(perc: Integer);
procedure procLog(message: String);
end;
var
frmMain: TfrmMain;
implementation
{$R *.lfm}
{ TfrmMain }
procedure TfrmMain.FormCreate(Sender: TObject);
begin
frmMain.Caption := Application.Title;
end;
procedure TfrmMain.actHelpAboutExecute(Sender: TObject);
begin
frmAbout.Show;
end;
procedure TfrmMain.actInsertMarkExecute(Sender: TObject);
var
ft : TFontParams;
begin
mmoMain.GetTextAttributes(mmoMain.SelStart, ft);
ft.Style:=[fsBold];
ft.Color:=clWhite;
ft.BkColor:=clMaroon;
ft.HasBkClr:=True;
InsertFontText(mmoMain, '÷', ft, mmoMain.SelStart);
mmoMain.SelStart := mmoMain.SelStart + 1;
end;
procedure TfrmMain.FormActivate(Sender: TObject);
begin
ProcessCommandline();
end;
procedure TfrmMain.actFileOpenExecute(Sender: TObject);
begin
if (diaOpen.Execute) then
begin
LoadFile(diaOpen.FileName);
end;
end;
procedure TfrmMain.actFileSaveExecute(Sender: TObject);
var
outstream: TFileStream;
begin
begin
outstream := TFileStream.Create(diaOpen.FileName, fmOpenWrite);
try
mmoMain.SaveRichText(outstream);
finally
outstream.Free;
end;
end;
end;
procedure TfrmMain.actGenerateCMTExecute(Sender: TObject);
begin
diaSave.InitialDir := ExtractFilePath(diaOpen.FileName);
diaSave.FileName := ExtractFileName(diaOpen.FileName.SubString(0, diaOpen.FileName.LastIndexOf('.'))+'.cmt.twm');
if (diaSave.Execute) then
begin
GenerateCmt(diaSave.FileName);
Application.MessageBox('Generation finished', PChar(Application.Title));
end;
end;
procedure TfrmMain.procProgress(perc: Integer);
begin
progressbar.Position := perc;
Application.ProcessMessages;
end;
procedure TfrmMain.procLog(message: String);
begin
mmoLog.Lines.Add(message);
Application.ProcessMessages;
end;
procedure TfrmMain.StateBusy;
begin
Cursor := crHourGlass;
pnlToolbar.Enabled := False;
end;
procedure TfrmMain.StateNormal;
begin
Cursor := crDefault;
pnlToolbar.Enabled := True;
end;
procedure TfrmMain.ProcessCommandline;
begin
if Application.HasOption('generatecmt') then
begin
LoadFile(Application.Params[2]);
GenerateCmt(Application.Params[3]);
Application.Terminate;
end;
end;
procedure TfrmMain.GenerateCmt(dest: String);
var rtfProcessor: TRtfProcessor;
begin
rtfProcessor := TRtfProcessor.Create;
rtfProcessor.OnProgress := @procProgress;
rtfProcessor.OnLog := @procLog;
rtfProcessor.processRtf(mmoMain.Rtf, dest);
rtfProcessor.Free;
end;
procedure TfrmMain.LoadFile(filename: String);
var
instream: TFileStream;
begin
instream := TFileStream.Create(filename, fmOpenRead);
try
mmoMain.LoadRichText(instream);
finally
instream.Free;
end;
Caption := Application.Title + ' - ' + ExtractFileName(filename);
end;
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit DSRESTExpertsUI;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DSServerWebBrokerExpertsUI, ExpertsUIWizard, DSProjectLocationWizardPage;
type
TDSRESTExpertsUIModule = class(TDSServerWebBrokerExpertsUIModule)
procedure DataModuleCreate(Sender: TObject);
procedure WebServerProjectWizardLoadImage(Sender: TCustomExpertsWizard;
var AImage: TBitmap);
protected
procedure SetDefaults; override;
end;
var
DSRESTExpertsUIModule: TDSRESTExpertsUIModule;
implementation
uses DSServerDSnResStrs, DSServerFeatures;
{$R *.dfm}
procedure TDSRESTExpertsUIModule.DataModuleCreate(Sender: TObject);
begin
inherited;
// WebServerProjectWizard.Caption := SNewDSRESTAppExpertCaption;
//// hcDDataSnapWebApplication = 4351;
//// hcDDataSnapStandAloneApplication = 4352;
//// hcDDataSnapRESTApplication = 4353; '
// WebServerProjectWizard.HelpContext := 4353;
// Features := [dsHTTPProtocol, dsServerMethodClass, dsWebFiles, dsSampleMethods, dsSampleWebFiles];
// WizardType := wtWebBrokerRest;
// EnablePages;
end;
procedure TDSRESTExpertsUIModule.SetDefaults;
begin
inherited;
WebServerProjectWizard.Caption := SNewDSRESTAppExpertCaption;
WebServerProjectWizard.HelpContext := 4353;
Features := [dsHTTPProtocol, dsServerMethodClass, dsWebFiles, dsSampleMethods, dsSampleWebFiles];
WizardType := wtWebBrokerRest;
end;
procedure TDSRESTExpertsUIModule.WebServerProjectWizardLoadImage(
Sender: TCustomExpertsWizard; var AImage: TBitmap);
begin
AImage := TBitmap.Create;
try
AImage.LoadFromResourceName(HInstance, 'WIZARDRESTPROJECT'); // Do not localize
except
FreeAndNil(AImage);
end;
end;
end.
|
{ GS1 interface library for FPC and Lazarus
Copyright (C) 2020-2021 Lagunov Aleksey alexs75@yandex.ru
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version with the following modification:
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,and
to copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the terms
and conditions of the license of that module. An independent module is a
module which is not derived from or based on this library. If you modify
this library, you may extend this exception to your version of the library,
but you are not obligated to do so. If you do not wish to do so, delete this
exception statement from your version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
for more details.
You should have received a copy of the GNU Library General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit lp_ship_goods_csv;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
{ TProduct }
TProduct = class
private
FProductCost: Currency;
FProductTax: Currency;
FUITCode: string;
FUITUCode: string;
procedure SetProductCost(AValue: Currency);
procedure SetProductTax(AValue: Currency);
procedure SetUITCode(AValue: string);
procedure SetUITUCode(AValue: string);
public
//КИ,
property UITCode:string read FUITCode write SetUITCode;
//КИТУ,
property UITUCode:string read FUITUCode write SetUITUCode;
//Цена за единицу,
property ProductCost:Currency read FProductCost write SetProductCost;
//Сумма НДС
property ProductTax:Currency read FProductTax write SetProductTax;
end;
TProductClass = class of TProduct;
{ TProducts }
TProductsEnumerator = class;
TProducts = class
private
FList:TFPList;
FBaseClass:TProductClass;
function GetCount: Integer;
function GetItem(AIndex: Integer): TProduct;
protected
function InternalAddObject:TProduct;
function InternalGetItem(AIndex: Integer):TProduct;
public
constructor Create(ABaseClass:TProductClass);
procedure Clear;
destructor Destroy; override;
function GetEnumerator: TProductsEnumerator;
property Count:Integer read GetCount;
property Items[AIndex:Integer]:TProduct read GetItem; default;
end;
{ TProductsEnumerator }
TProductsEnumerator = class
private
FList: TProducts;
FPosition: Integer;
public
constructor Create(AList: TProducts);
function GetCurrent: TProduct;
function MoveNext: Boolean;
property Current: TProduct read GetCurrent;
end;
{ TShipGoods }
TShipGoods = class(TObject)
private
FDocumentDate: string;
FDocumentNum: string;
FOwnerInn: string;
FProducts: TProducts;
FReceiverInn: string;
FSale: string;
FSenderInn: string;
FStContractId: string;
FTransferDate: string;
FTurnoverType: string;
FVersion: string;
FwithdrawalDate: string;
FWithdrawalType: string;
procedure SetDocumentDate(AValue: string);
procedure SetDocumentNum(AValue: string);
procedure SetOwnerInn(AValue: string);
procedure SetReceiverInn(AValue: string);
procedure SetSale(AValue: string);
procedure SetSenderInn(AValue: string);
procedure SetStContractId(AValue: string);
procedure SetTransferDate(AValue: string);
procedure SetTurnoverType(AValue: string);
procedure SetVersion(AValue: string);
procedure SetwithdrawalDate(AValue: string);
procedure SetWithdrawalType(AValue: string);
private
procedure DoLoadHeader(S:string);
procedure DoLoadRow(S:string);
public
constructor Create;
destructor Destroy; override;
procedure Clear;
procedure LoadFromFile(AFileName:string);
procedure LoadFromStream(AStream:TStream); virtual;
published
//ИНН отправителя,
property SenderInn:string read FSenderInn write SetSenderInn;
//ИНН получателя,
property ReceiverInn:string read FReceiverInn write SetReceiverInn;
//ИНН собственника,
property OwnerInn:string read FOwnerInn write SetOwnerInn;
//Дата отгрузки товара,
property TransferDate:string read FTransferDate write SetTransferDate;
//Номер первичного документа,
property DocumentNum:string read FDocumentNum write SetDocumentNum;
//Дата первичного документа,
property DocumentDate:string read FDocumentDate write SetDocumentDate;
//Вид оборота товаров,
property TurnoverType:string read FTurnoverType write SetTurnoverType;
//Причина вывода из оборота,
property WithdrawalType:string read FWithdrawalType write SetWithdrawalType;
//Дата вывода из оборота,
property withdrawalDate:string read FwithdrawalDate write SetwithdrawalDate;
//Идентификатор гос.контракта,
property StContractId:string read FStContractId write SetStContractId;
//Отгрузка неучастнику,
property Sale:string read FSale write SetSale;
//Версия
property Version:string read FVersion write SetVersion;
property Products:TProducts read FProducts;
end;
implementation
uses StrUtils;
{ TProductsEnumerator }
constructor TProductsEnumerator.Create(AList: TProducts);
begin
FList := AList;
FPosition := -1;
end;
function TProductsEnumerator.GetCurrent: TProduct;
begin
Result := TProduct(FList.FList[FPosition]);
end;
function TProductsEnumerator.MoveNext: Boolean;
begin
Inc(FPosition);
Result := FPosition < FList.Count;
end;
{ TProduct }
procedure TProduct.SetProductCost(AValue: Currency);
begin
if FProductCost=AValue then Exit;
FProductCost:=AValue;
end;
procedure TProduct.SetProductTax(AValue: Currency);
begin
if FProductTax=AValue then Exit;
FProductTax:=AValue;
end;
procedure TProduct.SetUITCode(AValue: string);
begin
if FUITCode=AValue then Exit;
FUITCode:=AValue;
end;
procedure TProduct.SetUITUCode(AValue: string);
begin
if FUITUCode=AValue then Exit;
FUITUCode:=AValue;
end;
{ TProducts }
function TProducts.GetCount: Integer;
begin
Result:=FList.Count;
end;
function TProducts.GetItem(AIndex: Integer): TProduct;
begin
Result:=TProduct(InternalGetItem(AIndex));
end;
function TProducts.InternalAddObject: TProduct;
begin
Result:=FBaseClass.Create;
FList.Add(Result);
end;
function TProducts.InternalGetItem(AIndex: Integer): TProduct;
begin
Result:=TProduct(FList[AIndex]);
end;
constructor TProducts.Create(ABaseClass: TProductClass);
begin
inherited Create;
FList:=TFPList.Create;
FBaseClass:=ABaseClass;
end;
procedure TProducts.Clear;
var
i: Integer;
begin
for i:=0 to FList.Count-1 do
TProduct(FList[i]).Free;
FList.Clear;
end;
destructor TProducts.Destroy;
begin
Clear;
FreeAndNil(FList);
inherited Destroy;
end;
function TProducts.GetEnumerator: TProductsEnumerator;
begin
Result:=TProductsEnumerator.Create(Self);
end;
{ TShipGoods }
procedure TShipGoods.DoLoadHeader(S: string);
var
A: TStringArray;
begin
//ИНН отправителя,ИНН получателя,ИНН собственника,Дата отгрузки товара,Номер первичного документа,Дата первичного документа,Вид оборота товаров,Причина вывода из оборота, Дата вывода из оборота,Идентификатор гос.контракта,Отгрузка неучастнику,Версия
A:=S.Split(',', '"');
SenderInn:=A[0]; //ИНН отправителя,
ReceiverInn:=A[1]; //ИНН получателя,
OwnerInn:=A[2]; //ИНН собственника,
TransferDate:=A[3]; //Дата отгрузки товара,
DocumentNum:=A[4]; //Номер первичного документа,
DocumentDate:=A[5]; //Дата первичного документа,
TurnoverType:=A[6]; //Вид оборота товаров,
WithdrawalType:=A[7]; //Причина вывода из оборота,
withdrawalDate:=A[8]; //Дата вывода из оборота,
StContractId:=A[9]; //Идентификатор гос.контракта,
Sale:=A[10]; //Отгрузка неучастнику,
Version:=A[11]; //Версия
end;
procedure TShipGoods.DoLoadRow(S: string);
var
R: TProduct;
A: TStringArray;
begin
//КИ,КИТУ,Цена за единицу,Сумма НДС
A:=S.Split(',', '"');
R:=FProducts.InternalAddObject;
R.FUITCode:=AnsiDequotedStr(A[0], '"');
R.FUITUCode:=AnsiDequotedStr(A[1], '"');
Val(A[2], R.FProductCost);
Val(A[3], R.FProductTax);
end;
procedure TShipGoods.SetDocumentDate(AValue: string);
begin
if FDocumentDate=AValue then Exit;
FDocumentDate:=AValue;
end;
procedure TShipGoods.SetDocumentNum(AValue: string);
begin
if FDocumentNum=AValue then Exit;
FDocumentNum:=AValue;
end;
procedure TShipGoods.SetOwnerInn(AValue: string);
begin
if FOwnerInn=AValue then Exit;
FOwnerInn:=AValue;
end;
procedure TShipGoods.SetReceiverInn(AValue: string);
begin
if FReceiverInn=AValue then Exit;
FReceiverInn:=AValue;
end;
procedure TShipGoods.SetSale(AValue: string);
begin
if FSale=AValue then Exit;
FSale:=AValue;
end;
procedure TShipGoods.SetSenderInn(AValue: string);
begin
if FSenderInn=AValue then Exit;
FSenderInn:=AValue;
end;
procedure TShipGoods.SetStContractId(AValue: string);
begin
if FStContractId=AValue then Exit;
FStContractId:=AValue;
end;
procedure TShipGoods.SetTransferDate(AValue: string);
begin
if FTransferDate=AValue then Exit;
FTransferDate:=AValue;
end;
procedure TShipGoods.SetTurnoverType(AValue: string);
begin
if FTurnoverType=AValue then Exit;
FTurnoverType:=AValue;
end;
procedure TShipGoods.SetVersion(AValue: string);
begin
if FVersion=AValue then Exit;
FVersion:=AValue;
end;
procedure TShipGoods.SetwithdrawalDate(AValue: string);
begin
if FwithdrawalDate=AValue then Exit;
FwithdrawalDate:=AValue;
end;
procedure TShipGoods.SetWithdrawalType(AValue: string);
begin
if FWithdrawalType=AValue then Exit;
FWithdrawalType:=AValue;
end;
constructor TShipGoods.Create;
begin
inherited Create;
FProducts:=TProducts.Create(TProduct);
end;
destructor TShipGoods.Destroy;
begin
FreeAndNil(FProducts);
inherited Destroy;
end;
procedure TShipGoods.Clear;
begin
FProducts.Clear;
end;
procedure TShipGoods.LoadFromFile(AFileName: string);
var
F: TFileStream;
begin
F:=TFileStream.Create(AFileName, fmOpenRead);
LoadFromStream(F);
F.Free;
end;
procedure TShipGoods.LoadFromStream(AStream: TStream);
var
St:TStringList;
i: Integer;
begin
Clear;
if not Assigned(AStream) then Exit;
St:=TStringList.Create;
St.LoadFromStream(AStream);
DoLoadHeader(ST[1]);
for i:=4 to ST.Count-1 do
DoLoadRow(ST[i]);
St.Free;
end;
end.
|
unit PascalCoin.RPC.Block;
interface
uses PascalCoin.RPC.Interfaces;
type
TPascalCoinBlock = class(TInterfacedObject, IPascalCoinBlock)
private
Fblock: Integer;
Fenc_pubkey: String;
Freward: Currency;
Ffee: Currency;
Fver: Integer;
Fver_a: Integer;
Ftimestamp: Integer;
Ftarget: Integer;
Fnonce: Integer;
Fpayload: String;
Fsbh: String;
Foph: String;
Fpow: String;
Foperations: Integer;
Fhashratekhs: Integer;
Fmaturation: Integer;
protected
function GetBlock: Integer;
function GetEnc_PubKey: String;
function GetFee: Currency;
function GetHashRateKHS: Integer;
function GetMaturation: Integer;
function GetNonce: Integer;
function GetOperations: Integer;
function GetOPH: String;
function GetPayload: String;
function GetPOW: String;
function GetReward: Currency;
function GetSBH: String;
function GetTarget: Integer;
function GetTimeStamp: Integer;
function GetVer: Integer;
function GetVer_a: Integer;
procedure SetBlock(const Value: Integer);
procedure SetEnc_PubKey(const Value: String);
procedure SetFee(const Value: Currency);
procedure SetHashRateKHS(const Value: Integer);
procedure SetMaturation(const Value: Integer);
procedure SetNonce(const Value: Integer);
procedure SetOperations(const Value: Integer);
procedure SetOPH(const Value: String);
procedure SetPayload(const Value: String);
procedure SetPOW(const Value: String);
procedure SetReward(const Value: Currency);
procedure SetSBH(const Value: String);
procedure SetTarget(const Value: Integer);
procedure SetTimeStamp(const Value: Integer);
procedure SetVer(const Value: Integer);
procedure SetVer_a(const Value: Integer);
function GetDelphiTimeStamp: TDateTime;
procedure SetDelphiTimeStamp(const Value: TDateTime);
public
end;
implementation
uses System.DateUtils;
{ TPascalCoinBlock }
function TPascalCoinBlock.GetBlock: Integer;
begin
result := Fblock;
end;
function TPascalCoinBlock.GetDelphiTimeStamp: TDateTime;
begin
result := UnixToDateTime(Ftimestamp);
end;
function TPascalCoinBlock.GetEnc_PubKey: String;
begin
result := Fenc_pubkey;
end;
function TPascalCoinBlock.GetFee: Currency;
begin
result := Ffee;
end;
function TPascalCoinBlock.GetHashRateKHS: Integer;
begin
result := Fhashratekhs;
end;
function TPascalCoinBlock.GetMaturation: Integer;
begin
result := Fmaturation;
end;
function TPascalCoinBlock.GetNonce: Integer;
begin
result := Fnonce;
end;
function TPascalCoinBlock.GetOperations: Integer;
begin
result := Foperations;
end;
function TPascalCoinBlock.GetOPH: String;
begin
result := Foph;
end;
function TPascalCoinBlock.GetPayload: String;
begin
result := Fpayload;
end;
function TPascalCoinBlock.GetPOW: String;
begin
result := Fpow;
end;
function TPascalCoinBlock.GetReward: Currency;
begin
result := Freward;
end;
function TPascalCoinBlock.GetSBH: String;
begin
result := Fsbh;
end;
function TPascalCoinBlock.GetTarget: Integer;
begin
result := Ftarget;
end;
function TPascalCoinBlock.GetTimeStamp: Integer;
begin
result := Ftimestamp;
end;
function TPascalCoinBlock.GetVer: Integer;
begin
result := Fver;
end;
function TPascalCoinBlock.GetVer_a: Integer;
begin
result := Fver_a;
end;
procedure TPascalCoinBlock.SetBlock(const Value: Integer);
begin
Fblock := Value;
end;
procedure TPascalCoinBlock.SetDelphiTimeStamp(const Value: TDateTime);
begin
Ftimestamp := DateTimeToUnix(Value);
end;
procedure TPascalCoinBlock.SetEnc_PubKey(const Value: String);
begin
Fenc_pubkey := Value;
end;
procedure TPascalCoinBlock.SetFee(const Value: Currency);
begin
Ffee := Value;
end;
procedure TPascalCoinBlock.SetHashRateKHS(const Value: Integer);
begin
Fhashratekhs := Value;
end;
procedure TPascalCoinBlock.SetMaturation(const Value: Integer);
begin
Fmaturation := Value;
end;
procedure TPascalCoinBlock.SetNonce(const Value: Integer);
begin
Fnonce := Value;
end;
procedure TPascalCoinBlock.SetOperations(const Value: Integer);
begin
Foperations := Value;
end;
procedure TPascalCoinBlock.SetOPH(const Value: String);
begin
Foph := Value;
end;
procedure TPascalCoinBlock.SetPayload(const Value: String);
begin
Fpayload := Value;
end;
procedure TPascalCoinBlock.SetPOW(const Value: String);
begin
Fpow := Value;
end;
procedure TPascalCoinBlock.SetReward(const Value: Currency);
begin
Freward := Value;
end;
procedure TPascalCoinBlock.SetSBH(const Value: String);
begin
Fsbh := Value;
end;
procedure TPascalCoinBlock.SetTarget(const Value: Integer);
begin
Ftarget := Value;
end;
procedure TPascalCoinBlock.SetTimeStamp(const Value: Integer);
begin
Ftimestamp := Value;
end;
procedure TPascalCoinBlock.SetVer(const Value: Integer);
begin
Fver := Value;
end;
procedure TPascalCoinBlock.SetVer_a(const Value: Integer);
begin
Fver_a := Value;
end;
end.
|
unit ProcessViewer;
interface
uses
Windows, SysUtils, Classes, TLHelp32, Math, PSAPI;
type
TWindowItem = record
WCaption: string;
Handle: Int64;
WClass: string;
end;
var
AllWindowsList: array of TWindowItem;
FCount, FCapacity, lcw1, lcw2: Integer;
WClassToFind1, WClassToFind2: string;
FProcessId: DWORD;
function EnumWindowsProc(hWnd: HWND; lParam: LPARAM): Bool; stdcall;
function EnumWindowsClassProc(hWnd: HWND; lParam: LPARAM): Bool; stdcall;
function EnumWindows2ClassProc(hWnd: HWND; lParam: LPARAM): Bool; stdcall;
procedure GetAllWindowsList(const WClassToFind1: string = ''; const WClassToFind2: string = '');
function EnumThreadWndProc(HWND: HWND; aParam: LongInt): Boolean; stdcall;
procedure GetWndThrList(const ThreadID: THandle);
function GetFileNameFromHandle(Handle: Int64): string;
function GetFileNameAndProcessIDFromHandle(Handle: Int64; var ProcessID: THandle): string;
procedure GetProcessIDWindowsList(const ProcessID: DWORD);
function EnumWindowsProcessProc(hWnd: HWND; lParam: LPARAM): Bool; stdcall;
implementation
procedure GetAllWindowsList(const WClassToFind1: string = ''; const WClassToFind2: string = '');
begin
if Length(AllWindowsList) > 0 then
SetLength(AllWindowsList, 0);
if WClassToFind1 = '' then
begin
SetLength(AllWindowsList, 100);
FCount := 0;
FCapacity := 100;
EnumWindows(@EnumWindowsProc, 0);
end
else
begin
lcw1 := Length(WClassToFind1);
if WClassToFind2 = '' then
begin
SetLength(AllWindowsList, 10);
FCount := 0;
FCapacity := 10;
ProcessViewer.WClassToFind1 := WClassToFind1;
EnumWindows(@EnumWindowsClassProc, 0);
end
else
begin
lcw2 := Length(WClassToFind2);
SetLength(AllWindowsList, 20);
FCount := 0;
FCapacity := 20;
ProcessViewer.WClassToFind1 := WClassToFind1;
ProcessViewer.WClassToFind2 := WClassToFind2;
EnumWindows(@EnumWindows2ClassProc, 0);
end;
end;
if Length(AllWindowsList) <> FCount then
SetLength(AllWindowsList, FCount);
end;
function EnumWindowsProc(hWnd: HWND; lParam: LPARAM): Bool;
var
WCaption, WClass: array[0..255] of Char;
begin
try
GetWindowText(hWnd, WCaption, 255);
GetClassName(hwnd, WClass, 255);
Inc(FCount);
if FCount > FCapacity then
begin
FCapacity := Ceil(1.1 * FCount);
SetLength(AllWindowsList, FCapacity);
end;
AllWindowsList[FCount - 1].WCaption := WCaption;
AllWindowsList[FCount - 1].WClass := WClass;
AllWindowsList[FCount - 1].Handle := hWnd;
except
end;
Result := True;
end;
function EnumWindowsClassProc(hWnd: HWND; lParam: LPARAM): Bool;
var
WCaption, WClass: array[0..255] of Char;
i: Integer;
begin
try
GetClassName(hwnd, WClass, 255);
if Integer(StrLen(WClass)) = lcw1 then
begin
i := 0;
while i < lcw1 do
begin
if WClass[i] <> WClassToFind1[i + 1] then
begin
Result := True;
Exit;
end;
Inc(i);
end;
end
else
begin
Result := True;
Exit;
end;
GetWindowText(hWnd, WCaption, 255);
Inc(FCount);
if FCount > FCapacity then
begin
FCapacity := Ceil(1.1 * FCount);
SetLength(AllWindowsList, FCapacity);
end;
AllWindowsList[FCount - 1].WCaption := WCaption;
AllWindowsList[FCount - 1].WClass := WClass;
AllWindowsList[FCount - 1].Handle := hWnd;
except
end;
Result := True;
end;
function EnumWindows2ClassProc(hWnd: HWND; lParam: LPARAM): Bool;
var
WCaption, WClass: array[0..255] of Char;
i, l: Integer;
begin
try
GetClassName(hwnd, WClass, 255);
l := StrLen(WClass);
if l = lcw1 then
begin
i := 0;
while i < lcw1 do
begin
if WClass[i] <> WClassToFind1[i + 1] then
begin
Result := True;
Exit;
end;
Inc(i);
end;
end;
if l = lcw2 then
begin
i := 0;
while i < lcw2 do
begin
if WClass[i] <> WClassToFind2[i + 1] then
begin
Result := True;
Exit;
end;
Inc(i);
end;
end;
GetWindowText(hWnd, WCaption, 255);
Inc(FCount);
if FCount > FCapacity then
begin
FCapacity := Ceil(1.1 * FCount);
SetLength(AllWindowsList, FCapacity);
end;
AllWindowsList[FCount - 1].WCaption := WCaption;
AllWindowsList[FCount - 1].WClass := WClass;
AllWindowsList[FCount - 1].Handle := hWnd;
except
end;
Result := True;
end;
procedure GetWndThrList(const ThreadID: THandle);
begin
if Length(AllWindowsList) > 0 then
SetLength(AllWindowsList, 0);
SetLength(AllWindowsList, 10);
FCount := 0;
FCapacity := 10;
EnumThreadWindows(ThreadID, @EnumThreadWndProc, LongInt(AllWindowsList));
if Length(AllWindowsList) <> FCount then
SetLength(AllWindowsList, FCount);
end;
function EnumThreadWndProc(HWND: HWND; aParam: LongInt): Boolean; stdcall;
var
WCaption, WClass: array[0..255] of Char;
begin
try
GetWindowText(hWnd, WCaption, 255);
GetClassName(hwnd, WClass, 255);
Inc(FCount);
if FCount > FCapacity then
begin
FCapacity := Ceil(1.1 * FCount);
SetLength(AllWindowsList, FCapacity);
end;
AllWindowsList[FCount - 1].WCaption := WCaption;
AllWindowsList[FCount - 1].WClass := WClass;
AllWindowsList[FCount - 1].Handle := hWnd;
except
end;
Result := True;
end;
function GetFileNameFromHandle(Handle: Int64): string;
var
PID: DWord;
aSnapShotHandle: THandle;
ContinueLoop: Boolean;
aProcessEntry32: TProcessEntry32W;
begin
GetWindowThreadProcessID(Handle, @PID);
aSnapShotHandle := CreateToolHelp32SnapShot(TH32CS_SNAPPROCESS, 0);
aProcessEntry32.dwSize := SizeOf(aProcessEntry32);
ContinueLoop := Process32First(aSnapShotHandle, aProcessEntry32);
while Integer(ContinueLoop) <> 0 do
begin
if aProcessEntry32.th32ProcessID = PID then
begin
Result := WideLowerCase(aProcessEntry32.szExeFile);
Break;
end;
ContinueLoop := Process32Next(aSnapShotHandle, aProcessEntry32);
end;
CloseHandle(aSnapShotHandle);
end;
function GetFileNameAndProcessIDFromHandle(Handle: Int64; var ProcessID: THandle): string;
var
PID: DWord;
aSnapShotHandle: THandle;
ContinueLoop: Boolean;
aProcessEntry32: TProcessEntry32W;
begin
GetWindowThreadProcessID(Handle, @PID);
aSnapShotHandle := CreateToolHelp32SnapShot(TH32CS_SNAPPROCESS, 0);
aProcessEntry32.dwSize := SizeOf(aProcessEntry32);
ContinueLoop := Process32First(aSnapShotHandle, aProcessEntry32);
while Integer(ContinueLoop) <> 0 do
begin
if aProcessEntry32.th32ProcessID = PID then
begin
Result := WideLowerCase(aProcessEntry32.szExeFile);
ProcessID := aProcessEntry32.th32ProcessID;
Break;
end;
ContinueLoop := Process32Next(aSnapShotHandle, aProcessEntry32);
end;
CloseHandle(aSnapShotHandle);
end;
function GetFileNameFromPID(PID: DWord): string;
var
aSnapShotHandle: THandle;
ContinueLoop: Boolean;
aProcessEntry32: TProcessEntry32W;
begin
aSnapShotHandle := CreateToolHelp32SnapShot(TH32CS_SNAPPROCESS, 0);
aProcessEntry32.dwSize := SizeOf(aProcessEntry32);
ContinueLoop := Process32First(aSnapShotHandle, aProcessEntry32);
while Integer(ContinueLoop) <> 0 do
begin
if aProcessEntry32.th32ProcessID = PID then
begin
Result := WideLowerCase(aProcessEntry32.szExeFile);
Break;
end;
ContinueLoop := Process32Next(aSnapShotHandle, aProcessEntry32);
end;
CloseHandle(aSnapShotHandle);
end;
procedure GetProcessIDWindowsList(const ProcessID: DWORD);
begin
if Length(AllWindowsList) > 0 then
SetLength(AllWindowsList, 0);
SetLength(AllWindowsList, 100);
FCount := 0;
FCapacity := 100;
FProcessID := ProcessID;
EnumWindows(@EnumWindowsProcessProc, 0);
if Length(AllWindowsList) <> FCount then
SetLength(AllWindowsList, FCount);
end;
function EnumWindowsProcessProc(hWnd: HWND; lParam: LPARAM): Bool;
var
WCaption, WClass: array[0..255] of Char;
PID: DWORD;
begin
try
GetWindowThreadProcessID(hWnd, @PID);
if FProcessID = PID then
begin
GetWindowText(hWnd, WCaption, 255);
GetClassName(hwnd, WClass, 255);
Inc(FCount);
if FCount > FCapacity then
begin
FCapacity := Ceil(1.1 * FCount);
SetLength(AllWindowsList, FCapacity);
end;
AllWindowsList[FCount - 1].WCaption := WCaption;
AllWindowsList[FCount - 1].WClass := WClass;
AllWindowsList[FCount - 1].Handle := hWnd;
end;
except
end;
Result := True;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Data.DBXOpenSSL;
interface
uses
Data.DBXPlatform,
Data.DBXTransport,
System.SysUtils,
IPPeerAPI
;
const
RSA_KEY_LENGTH = 1024;
RSA_KEY_EXPONENT = 3;
type
TKeyUsagePolicy = (kupUseGlobalKey, kupUseLocalKey);
TRSACypher = class sealed
strict private
FLocalKey: PRSAPeer;
FConfederatedKey: PRSAPeer;
FKeyUsagePolicy: TKeyUsagePolicy;
class var
GLOBAL_RSA_KEY: PRSAPeer;
OPEN_SSL_LOADED: Boolean;
OPEN_SSL_LOAD_STATUS: Boolean;
ERR_LOAD: string;
KEY_MONITOR: TObject;
FIPPeerProcs: IIPPeerProcs;
FIPImplementationID: string;
private
class procedure Init;
class procedure Clear;
class function IPPeerProcs: IIPPeerProcs;
class procedure GenerateRSAKey(keyLength: Integer; Exponent: Integer;
Monitor: TObject; var Key: PRSAPeer);
function GetPrivateKey: PRSAPeer;
function GetSynchMonitor: TObject;
protected
class function SSLErrorMessage: string;
class procedure ClearKey(var AKey: PRSAPeer);
public
/// <summary>Allows user to specify non-default IP Implementation for SSL operation implementations</summary>
/// <remarks>If the SSL has already been loaded, this will raise an exception</remarks>
/// <param name="AIPImplementationID">name of IP implementation ID to use instead of default</param>
procedure InitSSLIPImplementationID(const AIPImplementationID: string);
/// <summary>Lazy loading of Open SSL library</summary>
/// <returns>true if the SSL library was successfully loaded and all
/// cyphers are available. Returns false if an error occurs</returns>
class function LoadSSL: Boolean; overload;
/// <summary>Lazy loading of Open SSL library and creates the global RSA key</summary>
/// <remarks>If the key generation fails a TDBXError exception is thrown</remarks>
/// <param name="keyLength">key length, default RSA_KEY_LENGTH</param>
/// <param name="exponent">key exponent, needs to be a prime number, default RSA_KEY_EXPONENT</param>
class function LoadSSLAndCreateKey(keyLength: Integer = RSA_KEY_LENGTH; Exponent: int64 = RSA_KEY_EXPONENT): Boolean; overload;
/// <summary>Returns the load error message</summary>
/// <returns>String: the error message</returns>
class function ErrorLoad: string;
/// <summary>Generates the global RSA key pair</summary>
/// <remarks>If the key generation fails a TDBXError exception is thrown</remarks>
/// <param name="keyLength">key length, default RSA_KEY_LENGTH</param>
/// <param name="exponent">key exponent, needs to be a prime number, default RSA_KEY_EXPONENT</param>
class procedure GenerateGlobalKey(keyLength: Integer = RSA_KEY_LENGTH; Exponent: int64 = RSA_KEY_EXPONENT);
constructor Create; overload;
constructor Create(KeyUsagePolicy: TKeyUsagePolicy); overload;
destructor Destroy; override;
/// <summary>Generates a RSA key pair</summary>
/// <remarks>If the key generation fails a TDBXError exception is thrown</remarks>
/// <param name="keyLength">key length, default RSA_KEY_LENGTH</param>
/// <param name="exponent">key exponent, needs to be a prime number, default RSA_KEY_EXPONENT</param>
procedure GenerateKey(keyLength: Integer = RSA_KEY_LENGTH; Exponent: int64 = RSA_KEY_EXPONENT);
/// <summary>Returns the public key of the used key. If the policy is local
/// then the local key is used, otherwise the global key is used</summary>
/// <remarks>If the Open SSL library is not loaded it throws a TDBXError</remarks>
/// <returns>Array of byte data with the public key</returns>
function GetPublicKey: TArray<Byte>;
/// <summary>Sets the public key so encryption is possible</summary>
/// <remarks>The public key was obtained through a reciprocal call of GetPublicKey</remarks>
/// <param name="publicKey">Array of byte with the confederated public key</param>
procedure SetConfederatePublicKey(publicKey: TArray<Byte>);
/// <summary>Decrypts data using the private key</summary>
/// <remarks>Decryption is done with the key set according to the policy.
/// For reason of speed noo checks are made about the instance being properly setup</remarks>
/// <param name="data">Encrypted data to be decrypted</param>
function PrivateDecrypt(Data: TArray<Byte>): TArray<Byte>;
/// <summary>Encrypts the clear data using the public key. The data is usually a session key.</summary>
/// <remarks>The instance is expected to be properly setup (confederated key, policy).
/// The data size is expected to be less then the key size - 11.</remarks>
/// <param name="data">Data bytes to be encrypted</param>
function PublicEncrypt(Data: TArray<Byte>): TArray<Byte>;
end;
const
USE_GLOBAL = 'UseGlobalKey';
PUBLIC_KEY = 'PublicKey';
KEY_LENGTH = 'KeyLength';
KEY_EXPONENT = 'KeyExponent';
type
TRSAFilter = class(TTransportFilter)
private
FUseGlobalKey: Boolean;
FRSACypher: TRSACypher;
FKeyLength: Integer;
FKeyExponent: Int64;
private
procedure InitRSA;
protected
function GetParameters: TDBXStringArray; override;
function GetUserParameters: TDBXStringArray; override;
public
constructor Create; override;
destructor Destroy; override;
function ProcessInput(const Data: TArray<Byte>): TArray<Byte>; override;
function ProcessOutput(const Data: TArray<Byte>): TArray<Byte>; override;
function Id: string; override;
function SetConfederateParameter(const ParamName: string; const ParamValue: string): Boolean; override;
function GetParameterValue(const ParamName: string): string; override;
function SetParameterValue(const ParamName: string; const ParamValue: string): Boolean; override;
function IsPublicKeyCryptograph: Boolean; override;
end;
implementation
uses Data.DBXCommon, Data.DBXOpenSSLRes, System.Math;
{ TRSACypher }
class procedure TRSACypher.Clear;
begin
KEY_MONITOR.Free;
end;
class procedure TRSACypher.ClearKey(var AKey: PRSAPeer);
begin
if AKey <> nil then
IPPeerProcs._RSA_free(AKey);
AKey := nil;
end;
constructor TRSACypher.Create;
begin
FKeyUsagePolicy := kupUseGlobalKey;
FLocalKey := nil;
FConfederatedKey := nil;
end;
constructor TRSACypher.Create(KeyUsagePolicy: TKeyUsagePolicy);
begin
FKeyUsagePolicy := KeyUsagePolicy;
end;
destructor TRSACypher.Destroy;
begin
ClearKey(FLocalKey);
ClearKey(FConfederatedKey);
inherited;
end;
class function TRSACypher.ErrorLoad: string;
begin
Result := ERR_LOAD;
end;
class procedure TRSACypher.GenerateGlobalKey(keyLength: Integer; Exponent: int64);
var
Intf: IIPeerProcsGlobals;
begin
Assert(GLOBAL_RSA_KEY = nil);
GenerateRSAKey(keyLength, Exponent, KEY_MONITOR, GLOBAL_RSA_KEY);
if GLOBAL_RSA_KEY <> nil then
if Supports(IPPeerProcs, IIPeerProcsGlobals, Intf) then
// Free this key during finalization
Intf.RSA_register_global(GLOBAL_RSA_KEY);
end;
procedure TRSACypher.GenerateKey(keyLength: Integer; Exponent: int64);
begin
if FKeyUsagePolicy = kupUseGlobalKey then
GenerateGlobalKey(keyLength, Exponent)
else
GenerateRSAKey(keyLength, Exponent, self, FLocalKey);
end;
class procedure TRSACypher.GenerateRSAKey(keyLength, Exponent: Integer; Monitor: TObject; var Key: PRSAPeer);
var
err: string;
begin
if OPEN_SSL_LOAD_STATUS then
begin
TMonitor.Enter(Monitor);
try
ClearKey(Key);
//make exponent valid. Must be an odd number
if Exponent < 3 then
Exponent := 3
else if not Odd(Exponent) then
begin
Inc(Exponent);
end;
Key := IPPeerProcs._RSA_generate_key(keyLength, Exponent);
if Key = nil then
begin
err := SSLErrorMessage;
if err = EmptyStr then
err := SKeyCannotBeGenerated;
raise TDBXError.Create(0, err);
end;
finally
TMonitor.Exit(Monitor);
end;
end
else
raise TDBXError.Create(0, SOpenSSLNotLoaded);
end;
function TRSACypher.GetPrivateKey: PRSAPeer;
begin
if FKeyUsagePolicy = kupUseGlobalKey then
Result := GLOBAL_RSA_KEY
else
Result := FLocalKey;
end;
function TRSACypher.GetPublicKey: TArray<Byte>;
var
Length: Integer;
bufAddr: PByte;
Key: PRSAPeer;
Monitor: TObject;
begin
if OPEN_SSL_LOADED then
begin
if FKeyUsagePolicy = kupUseGlobalKey then
begin
Monitor := KEY_MONITOR;
Key := GLOBAL_RSA_KEY;
end
else
begin
Monitor := self;
Key := FLocalKey;
end;
TMonitor.Enter(Monitor);
try
Length := IPPeerProcs._i2d_RSAPublicKey(Key, nil);
SetLength(Result, Length);
bufAddr := Addr(Result[0]);
IPPeerProcs._i2d_RSAPublicKey(Key, @bufAddr);
finally
TMonitor.Exit(Monitor);
end;
end
else
raise TDBXError.Create(0, SOpenSSLNotLoaded);
end;
function TRSACypher.GetSynchMonitor: TObject;
begin
if FKeyUsagePolicy = kupUseGlobalKey then
Result := KEY_MONITOR
else
Result := self;
end;
class procedure TRSACypher.Init;
begin
OPEN_SSL_LOADED := false;
OPEN_SSL_LOAD_STATUS := false;
GLOBAL_RSA_KEY := nil;
FIPPeerProcs := nil;
FIPImplementationID := '';
KEY_MONITOR := TObject.Create;
end;
procedure TRSACypher.InitSSLIPImplementationID(
const AIPImplementationID: string);
begin
if FIPPeerProcs <> nil then
raise TDBXError.Create(0, sSSLAlreadyLoaded);
FIPImplementationID := AIPImplementationID;
end;
class function TRSACypher.IPPeerProcs: IIPPeerProcs;
begin
if FIPPeerProcs = nil then
FIPPeerProcs := IPProcs(FIPImplementationID);
Result := FIPPeerProcs;
end;
class function TRSACypher.LoadSSLAndCreateKey(keyLength: Integer; Exponent: int64): Boolean;
begin
if OPEN_SSL_LOADED then
exit(OPEN_SSL_LOAD_STATUS)
else if LoadSSL then
begin
GenerateGlobalKey(keyLength, Exponent);
exit(true);
end;
exit(false);
end;
class function TRSACypher.LoadSSL: Boolean;
begin
if OPEN_SSL_LOADED then
exit(OPEN_SSL_LOAD_STATUS);
// try to load it
OPEN_SSL_LOADED := true;
try
if IPPeerProcs._SSLLoad() then
begin
IPPeerProcs._ERR_load_crypto_strings();
IPPeerProcs._OpenSSL_add_all_ciphers();
OPEN_SSL_LOAD_STATUS := true;
exit(true);
end
else
begin
OPEN_SSL_LOAD_STATUS := false;
ERR_LOAD := SOpenSSLLoadError;
exit(false);
end;
except
on ex: Exception do
begin
OPEN_SSL_LOAD_STATUS := false;
ERR_LOAD := ex.Message;
exit(false);
end;
end;
end;
function TRSACypher.PrivateDecrypt(Data: TArray<Byte>): TArray<Byte>;
var
Key: PRSAPeer;
Monitor: TObject;
dataIdx, dataLength, keyLength, resultIdx: Integer;
begin
Key := GetPrivateKey;
Monitor := GetSynchMonitor;
keyLength := IPPeerProcs._RSA_size(Key);
dataIdx := 0;
resultIdx := 0;
while dataIdx < Length(Data) do
begin
SetLength(Result, resultIdx + keyLength);
keyLength := Min(keyLength, Length(Data) - dataIdx);
TMonitor.Enter(Monitor);
try
dataLength := IPPeerProcs._RSA_private_decrypt(keyLength, Pointer(IntPtr(Pointer(Data)) + dataIdx),
Pointer(IntPtr(Pointer(Result)) + resultIdx),
Key, IPPeerProcs.RSA_PKCS1_PADDING);
if dataLength = -1 then
raise TDBXError.Create(0, SSLErrorMessage);
if dataLength <> keyLength then
SetLength(Result, resultIdx + dataLength);
Inc(resultIdx, dataLength);
Inc(dataIdx, keyLength);
finally
TMonitor.Exit(Monitor);
end;
end;
end;
function TRSACypher.PublicEncrypt(Data: TArray<Byte>): TArray<Byte>;
var
dataIdx, keyLength, maxLen, resultIdx: Integer;
begin
keyLength := IPPeerProcs._RSA_size(FConfederatedKey);
maxLen := keyLength - 11;
dataIdx := 0;
resultIdx := 0;
while dataIdx < Length(Data) do
begin
SetLength(Result, resultIdx + keyLength);
maxLen := Min(maxLen, Length(Data) - dataIdx);
TMonitor.Enter(self);
try
keyLength := IPPeerProcs._RSA_public_encrypt(maxLen, Pointer(IntPtr(Pointer(Data)) + dataIdx),
Pointer(IntPtr(Pointer(Result)) + resultIdx),
FConfederatedKey, IPPeerProcs.RSA_PKCS1_PADDING);
if keyLength = -1 then
raise TDBXError.Create(0, SSLErrorMessage);
finally
TMonitor.Exit(self);
end;
Inc(dataIdx, maxLen);
Inc(resultIdx, keyLength);
end;
end;
procedure TRSACypher.SetConfederatePublicKey(publicKey: TArray<Byte>);
var
bufAddr: PByte;
begin
bufAddr := Addr(publicKey[0]);
TMonitor.Enter(self);
try
ClearKey(FConfederatedKey);
FConfederatedKey := IPPeerProcs._d2i_RSAPublicKey( nil, @bufAddr, Length(publicKey));
if FConfederatedKey = nil then
raise TDBXError.Create(0, SSLErrorMessage);
finally
TMonitor.Exit(self);
end;
end;
class function TRSACypher.SSLErrorMessage: string;
var
buff: array [0..1023] of Byte;
LWrapper: TPtrWrapper;
begin
LWrapper := TPtrWrapper.Create(@buff[0]);
IPPeerProcs._ERR_error_string(IPPeerProcs._ERR_get_error(), LWrapper);
Result := TMarshal.ReadStringAsAnsi(LWrapper, sizeof(buff));
end;
{ TRSAFilter }
constructor TRSAFilter.Create;
begin
inherited;
FUseGlobalKey := true;
FKeyLength := RSA_KEY_LENGTH;
FKeyExponent := RSA_KEY_EXPONENT;
end;
destructor TRSAFilter.Destroy;
begin
FreeAndNil(FRSACypher);
inherited;
end;
function TRSAFilter.GetParameters: TDBXStringArray;
begin
SetLength(Result, 1);
Result[0] := PUBLIC_KEY;
end;
function TRSAFilter.GetParameterValue(
const ParamName: string): string;
begin
if AnsiCompareStr(ParamName, USE_GLOBAL) = 0 then
begin
if FUseGlobalKey then
exit('true')
else
exit('false');
end;
if AnsiCompareStr(ParamName, PUBLIC_KEY) = 0 then
begin
InitRSA;
exit(Encode(FRSACypher.GetPublicKey, 0, -1));
end;
if AnsiCompareStr(ParamName, KEY_LENGTH) = 0 then
begin
exit(IntToStr(FKeyLength));
end;
if AnsiCompareStr(ParamName, KEY_EXPONENT) = 0 then
begin
exit(IntToStr(FKeyExponent));
end;
Result := EmptyStr;
end;
function TRSAFilter.GetUserParameters: TDBXStringArray;
begin
SetLength(Result, 3);
Result[0] := USE_GLOBAL;
Result[1] := KEY_LENGTH;
Result[2] := KEY_EXPONENT;
end;
function TRSAFilter.Id: string;
begin
Result := 'RSA';
end;
procedure TRSAFilter.InitRSA;
begin
if FRSACypher = nil then
begin
if not TRSACypher.LoadSSLAndCreateKey(FKeyLength, FKeyExponent) then
raise TDBXError.Create(0, TRSACypher.ErrorLoad);
if FUseGlobalKey then
FRSACypher := TRSACypher.Create
else
begin
FRSACypher := TRSACypher.Create(kupUseLocalKey);
FRSACypher.GenerateKey(FKeyLength, FKeyExponent);
end;
end;
end;
function TRSAFilter.IsPublicKeyCryptograph: Boolean;
begin
Result := true;
end;
function TRSAFilter.ProcessInput(const Data: TArray<Byte>): TArray<Byte>;
begin
InitRSA;
Result := FRSACypher.PublicEncrypt(Data)
end;
function TRSAFilter.ProcessOutput(const Data: TArray<Byte>): TArray<Byte>;
begin
InitRSA;
Result := FRSACypher.PrivateDecrypt(Data)
end;
function TRSAFilter.SetConfederateParameter(const ParamName,
ParamValue: string): Boolean;
begin
if AnsiCompareStr(ParamName, PUBLIC_KEY) = 0 then
begin
InitRSA;
FRSACypher.SetConfederatePublicKey(Decode(ParamValue));
exit(true);
end;
Result := false;
end;
function TRSAFilter.SetParameterValue(const ParamName,
ParamValue: string): Boolean;
begin
if AnsiCompareStr(ParamName, USE_GLOBAL) = 0 then
begin
FUseGlobalKey := AnsiCompareText(ParamValue, 'true') = 0;
exit(true);
end;
if AnsiCompareStr(ParamName, KEY_LENGTH) = 0 then
begin
FKeyLength := StrToInt(ParamValue);
exit(true);
end;
if AnsiCompareStr(ParamName, KEY_EXPONENT) = 0 then
begin
FKeyExponent := StrToInt64(ParamValue);
exit(true);
end;
exit(false);
end;
initialization
TRSACypher.Init;
finalization
TRSACypher.Clear;
end.
|
(***********************************************************)
(* xPLRFX *)
(* part of Digital Home Server project *)
(* http://www.digitalhomeserver.net *)
(* info@digitalhomeserver.net *)
(***********************************************************)
unit uxPLRFX_0x56;
interface
Uses uxPLRFXConst, u_xPL_Message, u_xpl_common, uxPLRFXMessages;
procedure RFX2xPL(Buffer : BytesArray; xPLMessages : TxPLRFXMessages);
implementation
Uses SysUtils;
(*
Type $56 - Wind sensors
Buffer[0] = packetlength = $10;
Buffer[1] = packettype
Buffer[2] = subtype
Buffer[3] = seqnbr
Buffer[4] = id1
Buffer[5] = id2
Buffer[6] = directionhigh
Buffer[7] = directionlow
Buffer[8] = av_speedhigh
Buffer[9] = av_speedlow
Buffer[10] = gusthigh
Buffer[11] = gustlow
Buffer[12] = temperaturehigh:7/temperaturesign:1
Buffer[13] = temperaturelow
Buffer[14] = chillhigh:7/chillsign:1
Buffer[15] = chillow
Buffer[16] = battery_level:4/rssi:4
Test strings :
105601122F000087000000140049000079
xPL Schema
sensor.basic
{
device=(wind1-wind6) 0x<hex sensor id>
type=gust
current=<m/sec>
unit=mps
}
sensor.basic
{
device=(wind1-wind6) 0x<hex sensor id>
type=average_speed
current=<m/sec>
unit=mps
}
sensor.basic
{
device=(wind1-wind6) 0x<hex sensor id>
type=direction
current=0-359
}
sensor.basic
{
device=(wind1-wind6) 0x<hex sensor id>
type=temp
current=<degrees celsius>
units=c
}
sensor.basic
{
device=(wind1-wind6) 0x<hex sensor id>
type=chill
current=<degrees celsius>
units=c
}
sensor.basic
{
device=(wind1-wind6) 0x<hex sensor id>
type=battery
current=0-100
}
TO CHECK : what exactly is chill temperature ?
*)
const
// Type
WIND = $56;
// Subtype
WIND1 = $01;
WIND2 = $02;
WIND3 = $03;
WIND4 = $04;
WIND5 = $05;
WIND6 = $06;
var
SubTypeArray : array[1..6] of TRFXSubTypeRec =
((SubType : WIND1; SubTypeString : 'wind1'),
(SubType : WIND2; SubTypeString : 'wind2'),
(SubType : WIND3; SubTypeString : 'wind3'),
(SubType : WIND4; SubTypeString : 'wind4'),
(SubType : WIND5; SubTypeString : 'wind5'),
(SubType : WIND6; SubTypeString : 'wind6'));
procedure RFX2xPL(Buffer : BytesArray; xPLMessages : TxPLRFXMessages);
var
SubType : Byte;
DeviceID : String;
Direction : Integer;
AverageSpeed : Extended;
Gust : Extended;
Temperature : Extended;
TemperatureSign : String;
Chill : Extended;
ChillSign : String;
BatteryLevel : Integer;
xPLMessage : TxPLMessage;
begin
SubType := Buffer[2];
DeviceID := GetSubTypeString(SubType,SubTypeArray)+IntToHex(Buffer[4],2)+IntToHex(Buffer[5],2);
Direction := (Buffer[6] shl 8) + Buffer[7];
if SubType <> WIND5 then
AverageSpeed := ((Buffer[8] shl 8) + Buffer[9]) / 10;
Gust := ((Buffer[10] shl 8) + Buffer[11]) / 10;
if SubType = WIND4 then
begin
if Buffer[12] and $80 > 0 then
TemperatureSign := '-'; // negative value
Buffer[12] := Buffer[12] and $7F; // zero out the temperature sign
Temperature := ((Buffer[12] shl 8) + Buffer[13]) / 10;
if Buffer[14] and $80 > 0 then
ChillSign := '-'; // negative value
Buffer[14] := Buffer[14] and $7F; // zero out the temperature sign
Chill := ((Buffer[14] shl 8) + Buffer[15]) / 10;
end;
if (Buffer[16] and $0F) = 0 then // zero out rssi
BatteryLevel := 0
else
BatteryLevel := 100;
// Create sensor.basic messages
xPLMessage := TxPLMessage.Create(nil);
xPLMessage.schema.RawxPL := 'sensor.basic';
xPLMessage.MessageType := trig;
xPLMessage.source.RawxPL := XPLSOURCE;
xPLMessage.target.IsGeneric := True;
xPLMessage.Body.AddKeyValue('device='+DeviceID);
xPLMessage.Body.AddKeyValue('current='+FloatToStr(Gust));
xPLMessage.Body.AddKeyValue('units=mps');
xPLMessage.Body.AddKeyValue('type=gust');
xPLMessages.Add(xPLMessage.RawXPL);
xPLMessage.Free;
if SubType <> WIND5 then
begin
xPLMessage := TxPLMessage.Create(nil);
xPLMessage.schema.RawxPL := 'sensor.basic';
xPLMessage.MessageType := trig;
xPLMessage.source.RawxPL := XPLSOURCE;
xPLMessage.target.IsGeneric := True;
xPLMessage.Body.AddKeyValue('device='+DeviceID);
xPLMessage.Body.AddKeyValue('current='+FloatToStr(AverageSpeed));
xPLMessage.Body.AddKeyValue('units=mps');
xPLMessage.Body.AddKeyValue('type=average_speed');
xPLMessages.Add(xPLMessage.RawXPL);
xPLMessage.Free;
end;
xPLMessage := TxPLMessage.Create(nil);
xPLMessage.schema.RawxPL := 'sensor.basic';
xPLMessage.MessageType := trig;
xPLMessage.source.RawxPL := XPLSOURCE;
xPLMessage.target.IsGeneric := True;
xPLMessage.Body.AddKeyValue('device='+DeviceID);
xPLMessage.Body.AddKeyValue('current='+IntToStr(Direction));
xPLMessage.Body.AddKeyValue('type=direction');
xPLMessages.Add(xPLMessage.RawXPL);
xPLMessage.Free;
if SubType = WIND4 then
begin
xPLMessage := TxPLMessage.Create(nil);
xPLMessage.schema.RawxPL := 'sensor.basic';
xPLMessage.MessageType := trig;
xPLMessage.source.RawxPL := XPLSOURCE;
xPLMessage.target.IsGeneric := True;
xPLMessage.Body.AddKeyValue('device='+DeviceID);
xPLMessage.Body.AddKeyValue('current='+TemperatureSign+FloatToStr(Temperature));
xPLMessage.Body.AddKeyValue('units=c');
xPLMessage.Body.AddKeyValue('type=temperature');
xPLMessages.Add(xPLMessage.RawXPL);
xPLMessage.Free;
xPLMessage := TxPLMessage.Create(nil);
xPLMessage.schema.RawxPL := 'sensor.basic';
xPLMessage.MessageType := trig;
xPLMessage.source.RawxPL := XPLSOURCE;
xPLMessage.target.IsGeneric := True;
xPLMessage.Body.AddKeyValue('device='+DeviceID);
xPLMessage.Body.AddKeyValue('current='+ChillSign+FloatToStr(Chill));
xPLMessage.Body.AddKeyValue('units=c');
xPLMessage.Body.AddKeyValue('type=chill');
xPLMessages.Add(xPLMessage.RawXPL);
xPLMessage.Free;
end;
xPLMessage := TxPLMessage.Create(nil);
xPLMessage.schema.RawxPL := 'sensor.basic';
xPLMessage.MessageType := trig;
xPLMessage.source.RawxPL := XPLSOURCE;
xPLMessage.target.IsGeneric := True;
xPLMessage.Body.AddKeyValue('device='+DeviceID);
xPLMessage.Body.AddKeyValue('current='+IntToStr(BatteryLevel));
xPLMessage.Body.AddKeyValue('type=battery');
xPLMessages.Add(xPLMessage.RawXPL);
xPLMessage.Free;
end;
end.
|
{***************************************************************
*
* Project : Client
* Unit Name: ClientMain
* Purpose : Demonstrates basic interaction of IdTCPClient with server
* Date : 16/01/2001 - 03:21:02
* History :
*
****************************************************************}
unit ClientMain;
interface
uses
{$IFDEF Linux}
QForms, QGraphics, QControls, QDialogs, QStdCtrls, QExtCtrls,
{$ELSE}
windows, messages, graphics, controls, forms, dialogs, stdctrls, extctrls,
{$ENDIF}
SysUtils, Classes,
IdBaseComponent,
IdComponent, IdTCPConnection, IdTCPClient;
type
TForm2 = class(TForm)
TCPClient: TIdTCPClient;
pnlTop: TPanel;
btnGo: TButton;
lstMain: TListBox;
procedure btnGoClick(Sender: TObject);
private
public
end;
var
Form2: TForm2;
implementation
{$IFDEF MSWINDOWS}{$R *.dfm}{$ELSE}{$R *.xfm}{$ENDIF}
// Any data received from the client is added as a text line in the ListBox
procedure TForm2.btnGoClick(Sender: TObject);
begin
with TCPClient do
begin
Connect;
try
lstMain.Items.Add(ReadLn);
finally
Disconnect;
end;
end;
end;
end.
|
{
AD.A.P.T. Library
Copyright (C) 2014-2018, Simon J Stuart, All Rights Reserved
Original Source Location: https://github.com/LaKraven/ADAPT
Subject to original License: https://github.com/LaKraven/ADAPT/blob/master/LICENSE.md
}
unit ADAPT.Streams.Abstract;
{$I ADAPT.inc}
interface
uses
{$IFDEF ADAPT_USE_EXPLICIT_UNIT_NAMES}
System.Classes, System.SysUtils, System.RTLConsts,
{$IFDEF MSWINDOWS}WinApi.Windows,{$ENDIF MSWINDOWS}
{$IFDEF POSIX}Posix.UniStd,{$ENDIF POSIX}
{$ELSE}
Classes, SysUtils, RTLConsts,
{$IFDEF MSWINDOWS}Windows,{$ENDIF MSWINDOWS}
{$IFDEF POSIX}Posix,{$ENDIF POSIX}
{$ENDIF ADAPT_USE_EXPLICIT_UNIT_NAMES}
ADAPT, ADAPT.Intf,
ADAPT.Collections.Intf,
ADAPT.Streams.Intf,
ADAPT.Comparers.Intf;
{$I ADAPT_RTTI.inc}
type
/// <summary><c>Abstract Base Class for all Stream Caret Types.</c></summary>
/// <remarks>
/// <para><c>This type is NOT Threadsafe.</c></para>
/// </remarks>
TADStreamCaret = class abstract(TADObject, IADStreamCaret)
protected
FPosition: Int64;
/// <summary><c>Weak Rerefence to the owning Stream object.</c></summary>
/// <remarks><c>Use </c>GetStream<c> to cast the Reference back to </c>IADStream<c>.</c></remarks>
FStream: Pointer;
FValid: Boolean;
procedure CheckCaretValid;
{ IADStreamCaret }
function GetIsInvalid: Boolean; virtual;
function GetIsValid: Boolean; virtual;
function GetPosition: Int64; virtual;
function GetStream: IADStream; virtual;
function GetStreamManagement: IADStreamManagement; virtual;
procedure SetPosition(const APosition: Int64); virtual;
public
constructor Create(const AStream: IADStream); reintroduce; overload;
constructor Create(const AStream: IADStream; const APosition: Int64); reintroduce; overload;
destructor Destroy; override;
{ IADStreamCaret }
function Delete(const ALength: Int64): Int64; virtual;
function Insert(const ABuffer; const ALength: Int64): Int64; virtual;
function Read(var ABuffer; const ALength: Int64): Int64; virtual;
function Write(const ABuffer; const ALength: Int64): Int64; virtual;
function Seek(const AOffset: Int64; const AOrigin: TSeekOrigin): Int64; virtual;
procedure Invalidate; virtual;
property IsInvalid: Boolean read GetIsInvalid;
property IsValid: Boolean read GetIsValid;
property Position: Int64 read GetPosition write SetPosition;
property Stream: IADStream read GetStream;
property StreamManagement: IADStreamManagement read GetStreamManagement;
end;
/// <summary><c>Abstract Base Class for all Stream Types.</c></summary>
/// <remarks>
/// <para><c>This type is NOT Threadsafe.</c></para>
/// </remarks>
TADStream = class abstract(TADObject, IADStream, IADStreamManagement)
protected
FCaretList: IADSortedList<IADStreamCaret>;
{ IADStream }
function GetSize: Int64; virtual; abstract;
procedure SetSize(const ASize: Int64); virtual; abstract;
{ IADStreamManagement }
procedure InvalidateCaret(const ACaret: IADStreamCaret; const AFromPosition, ACount: Int64); virtual;
procedure InvalidateCarets(const AFromPosition, ACount: Int64); virtual;
procedure ShiftCaretLeft(const ACaret: IADStreamCaret; const AFromPosition, ACount: Int64); virtual;
procedure ShiftCaretRight(const ACaret: IADStreamCaret; const AFromPosition, ACount: Int64); virtual;
procedure ShiftCaretsLeft(const AFromPosition, ACount: Int64); virtual;
procedure ShiftCaretsRight(const AFromPosition, ACount: Int64); virtual;
procedure UnregisterCaret(const ACaret: IADStreamCaret); virtual;
{ Internal Methods }
function MakeNewCaret: IADStreamCaret; virtual; abstract;
public
constructor Create; override;
destructor Destroy; override;
{ IADStream }
procedure LoadFromFile(const AFileName: String); virtual; abstract;
procedure LoadFromStream(const AStream: IADStream); overload; virtual; abstract;
procedure LoadFromStream(const AStream: TStream); overload; virtual; abstract;
function NewCaret: IADStreamCaret; overload;
function NewCaret(const APosition: Int64): IADStreamCaret; overload;
function NewCaretReader: IADStreamCaretReader; overload;
function NewCaretReader(const APosition: Int64): IADStreamCaretReader; overload;
procedure SaveToFile(const AFileName: String); virtual; abstract;
procedure SaveToStream(const AStream: IADStream); overload; virtual; abstract;
procedure SaveToStream(const AStream: TStream); overload; virtual; abstract;
// Properties
property Size: Int64 read GetSize write SetSize;
end;
implementation
uses
ADAPT.Collections,
ADAPT.Comparers,
ADAPT.Streams; // Used for ADStreamCaretComparer
{ TADStreamCaret }
constructor TADStreamCaret.Create(const AStream: IADStream);
begin
inherited Create;
FStream := @AStream;
end;
constructor TADStreamCaret.Create(const AStream: IADStream; const APosition: Int64);
begin
Create(AStream);
SetPosition(APosition);
end;
procedure TADStreamCaret.CheckCaretValid;
begin
if IsInvalid then
raise EADStreamCaretInvalid.CreateFmt('The binary data at position %d as referenced by this Caret has been removed or modified.', [GetPosition]);
end;
function TADStreamCaret.Delete(const ALength: Int64): Int64;
begin
Result := 0;
CheckCaretValid;
end;
destructor TADStreamCaret.Destroy;
begin
GetStreamManagement.UnregisterCaret(Self);
inherited;
end;
function TADStreamCaret.GetIsInvalid: Boolean;
begin
Result := (not FValid);
end;
function TADStreamCaret.GetIsValid: Boolean;
begin
Result := FValid;
end;
function TADStreamCaret.GetPosition: Int64;
begin
Result := Seek(0, soCurrent);
end;
function TADStreamCaret.GetStream: IADStream;
begin
Result := IADStream(FStream^);
end;
function TADStreamCaret.GetStreamManagement: IADStreamManagement;
begin
Result := GetStream as IADStreamManagement;
end;
function TADStreamCaret.Insert(const ABuffer; const ALength: Int64): Int64;
begin
Result := 0;
CheckCaretValid;
end;
procedure TADStreamCaret.Invalidate;
begin
FValid := False;
end;
function TADStreamCaret.Read(var ABuffer; const ALength: Int64): Int64;
begin
Result := 0;
CheckCaretValid;
end;
function TADStreamCaret.Seek(const AOffset: Int64; const AOrigin: TSeekOrigin): Int64;
begin
Result := 0;
CheckCaretValid;
end;
procedure TADStreamCaret.SetPosition(const APosition: Int64);
begin
FPosition := Seek(APosition, soBeginning);
end;
function TADStreamCaret.Write(const ABuffer; const ALength: Int64): Int64;
begin
Result := 0;
CheckCaretValid;
end;
{ TADStream }
constructor TADStream.Create;
begin
inherited;
FCaretList := TADSortedList<IADStreamCaret>.Create(ADStreamCaretComparer);
end;
destructor TADStream.Destroy;
begin
InvalidateCarets(0, GetSize);
inherited;
end;
procedure TADStream.InvalidateCaret(const ACaret: IADStreamCaret; const AFromPosition, ACount: Int64);
begin
if (ACaret.Position >= AFromPosition) and (ACaret.Position < AFromPosition + ACount) then
ACaret.Invalidate;
end;
procedure TADStream.InvalidateCarets(const AFromPosition, ACount: Int64);
var
I: Integer;
begin
for I := 0 to FCaretList.Count - 1 do
InvalidateCaret(FCaretList[I], AFromPosition, ACount);
end;
function TADStream.NewCaret: IADStreamCaret;
begin
Result := MakeNewCaret;
FCaretList.Add(Result);
end;
function TADStream.NewCaret(const APosition: Int64): IADStreamCaret;
begin
Result := MakeNewCaret;
Result.Position := APosition;
FCaretList.Add(Result);
end;
function TADStream.NewCaretReader: IADStreamCaretReader;
begin
Result := NewCaret;
end;
function TADStream.NewCaretReader(const APosition: Int64): IADStreamCaretReader;
begin
Result := NewCaret(APosition);
end;
procedure TADStream.ShiftCaretLeft(const ACaret: IADStreamCaret; const AFromPosition, ACount: Int64);
begin
if (ACaret.Position >= AFromPosition) and (ACaret.Position < AFromPosition + ACount) then
ACaret.Position := ACaret.Position - ACount;
end;
procedure TADStream.ShiftCaretRight(const ACaret: IADStreamCaret; const AFromPosition, ACount: Int64);
begin
if (ACaret.Position >= AFromPosition) and (ACaret.Position < AFromPosition + ACount) then
ACaret.Position := ACaret.Position + ACount;
end;
procedure TADStream.ShiftCaretsLeft(const AFromPosition, ACount: Int64);
var
I: Integer;
begin
for I := 0 to FCaretList.Count - 1 do
ShiftCaretLeft(FCaretList[I], AFromPosition, ACount);
end;
procedure TADStream.ShiftCaretsRight(const AFromPosition, ACount: Int64);
var
I: Integer;
begin
for I := 0 to FCaretList.Count - 1 do
ShiftCaretRight(FCaretList[I], AFromPosition, ACount);
end;
procedure TADStream.UnregisterCaret(const ACaret: IADStreamCaret);
var
LIndex: Integer;
begin
LIndex := FCaretList.IndexOf(ACaret);
if LIndex > -1 then
FCaretList.Delete(LIndex);
end;
end.
|
unit MediaStream.DataSource.File_;
interface
uses Windows,Classes,SysUtils, SyncObjs, uBaseClasses, MediaStream.DataSource.Base,
MediaProcessing.Definitions,MediaStream.Framer;
type
TMediaStreamDataSource_File = class;
TMediaStreamDataSourceFileEndedHandler = procedure (Sender: TMediaStreamDataSource) of object;
TMediaStreamDataSourceFileEndedEvent = TEventCast<TMediaStreamDataSourceFileEndedHandler>;
TMediaStreamDataSource_File = class (TMediaStreamDataSource)
private
FFileReadThread : TThread;
FFileName: string;
FLastStreamDataTime: TDateTime;
FDataLock: TCriticalSection;
FTransmitVideo: boolean;
FTransmitAudio: boolean;
FLoop: boolean;
FNoTimings: boolean;
FOnFileEnded: TMediaStreamDataSourceFileEndedEvent;
protected
procedure DoConnect(aConnectParams: TMediaStreamDataSourceConnectParams); override;
procedure DoDisconnect; override;
procedure OnDataReceived(const aFormat: TMediaStreamDataHeader;
aData: pointer; aDataSize:cardinal;
aInfo: pointer; aInfoSize: cardinal);
public
constructor Create; override;
destructor Destroy; override;
class function CreateConnectParams: TMediaStreamDataSourceConnectParams; override;
function GetConnectionErrorDescription(aError: Exception): string; override;
procedure Start; override;
procedure Stop; override;
function LastStreamDataTime: TDateTime; override;
function StreamFramer: TStreamFramer;
//Если true, то задержки между кадрами для обеспечения реального режима вопроизведения не выполняются
property NoTimings:boolean read FNoTimings write FNoTimings;
//Возвращает текущую позицию в миллисекундах
function CurrentPosition: int64;
//Длина в миллисекундах
function Length: int64;
property OnFileEnded: TMediaStreamDataSourceFileEndedEvent read FOnFileEnded;
end;
TMediaStreamDataSourceConnectParams_File = class (TMediaStreamDataSourceConnectParams)
private
FFileName: string;
FTransmitVideo: boolean;
FTransmitAudio: boolean;
FLoop: boolean;
public
constructor Create; overload;
constructor Create(
const aUrl: string;
aTransmitVideo: boolean=true;
aTransmitAudio: boolean=true;
aLoop: boolean=true); overload;
procedure Assign(aSource: TMediaStreamDataSourceConnectParams); override;
function ToString: string; override;
property FileName: string read FFileName write FFileName;
property Loop: boolean read FLoop write FLoop;
function ToUrl(aIncludeAuthorizationInfo: boolean): string; override;
procedure Parse(const aUrl: string); override;
end;
implementation
uses ThreadNames, StrUtils, MediaStream.FramerFactory,MediaStream.UrlFormats;
type
TFileReader = class
private
FFramer: TStreamFramer;
FStream : TStream;
FClean: boolean;
public
constructor Create(const aFileName: string; aFramerClass:TStreamFramerClass);
destructor Destroy; override;
procedure Reset;
function GetNextFrame(out aOutFormat: TMediaStreamDataHeader; out aOutData: pointer; out aOutDataSize: cardinal; out aOutInfo: pointer; out aOutInfoSize: cardinal):boolean;
function StreamInfo: TBytes;
function VideoStreamType: TStreamType;
function AudioStreamType: TStreamType;
function CurrentPosition: int64;
//Длина в миллисекундах
function Length: int64;
end;
TReadFileThread = class (TThread)
private
FOwner: TMediaStreamDataSource_File;
FReader: TFileReader;
FOpenLock: TCriticalSection;
FVideoTimeStampBase: int64;
FAudioTimeStampBase: int64;
FAudioTotalSleep: int64;
FAudioSleepHits: int64;
FStreamInfo: TBytes;
protected
procedure ProcessFile;
procedure Execute; override;
public
constructor Create(const aFileName:string; aFramerClass:TStreamFramerClass; aOwner: TMediaStreamDataSource_File);
destructor Destroy; override;
//Текущая позиция в миллисекундах
function CurrentPosition: int64;
//Длина в миллисекундах
function Length: int64;
end;
{ TMediaStreamDataSourceConnectParams_File }
procedure TMediaStreamDataSourceConnectParams_File.Assign(aSource: TMediaStreamDataSourceConnectParams);
var
aSrc:TMediaStreamDataSourceConnectParams_File;
begin
TArgumentValidation.NotNil(aSource);
if not (aSource is TMediaStreamDataSourceConnectParams_File) then
raise EInvalidArgument.CreateFmt('Тип параметров %s не совместим с типом %s',[aSource.ClassName,self.ClassName]);
aSrc:=aSource as TMediaStreamDataSourceConnectParams_File;
FFileName:=aSrc.FFileName;
FTransmitVideo:=aSrc.FTransmitVideo;
FTransmitAudio:=aSrc.FTransmitAudio;
FLoop:=aSrc.FLoop;
end;
constructor TMediaStreamDataSourceConnectParams_File.Create;
begin
FLoop:=true;
FTransmitVideo:=true;
FTransmitAudio:=true;
end;
constructor TMediaStreamDataSourceConnectParams_File.Create(const aUrl: string; aTransmitVideo, aTransmitAudio,aLoop: boolean);
var
s: string;
begin
Create;
FLoop:=aLoop;
if StartsText('file:',aUrl) and ParseFileUrl(aUrl,s) then
FFileName:=s
else
FFileName:=aUrl;
FTransmitVideo:=aTransmitVideo;
FTransmitAudio:=aTransmitAudio;
end;
procedure TMediaStreamDataSourceConnectParams_File.Parse(const aUrl: string);
begin
if not ParseFileUrl(aUrl,FFileName) then
RaiseParseError(aUrl);
end;
function TMediaStreamDataSourceConnectParams_File.ToString: string;
begin
result:=FFileName;
end;
function TMediaStreamDataSourceConnectParams_File.ToUrl(
aIncludeAuthorizationInfo: boolean): string;
begin
result:=MakeFileUrl(FFileName)
end;
{ TMediaStreamDataSource_File }
procedure TMediaStreamDataSource_File.Start;
begin
FDataLock.Enter;
try
FFileReadThread.Resume;
finally
FDataLock.Leave;
end;
end;
procedure TMediaStreamDataSource_File.Stop;
begin
FDataLock.Enter;
try
if FFileReadThread<>nil then
begin
if GetCurrentThread=FFileReadThread.Handle then
raise Exception.Create('Нельзя остановить поток из него же');
FFileReadThread.Suspend;
end;
finally
FDataLock.Leave;
end;
end;
function TMediaStreamDataSource_File.StreamFramer: TStreamFramer;
begin
result:=nil;
if FFileReadThread<>nil then
result:=TReadFileThread(FFileReadThread).FReader.FFramer;
end;
procedure TMediaStreamDataSource_File.DoConnect(aConnectParams: TMediaStreamDataSourceConnectParams);
var
aConnectParams_ : TMediaStreamDataSourceConnectParams_File;
begin
aConnectParams_:=aConnectParams as TMediaStreamDataSourceConnectParams_File;
FFileName:=aConnectParams_.FFileName;
FTransmitVideo:=aConnectParams_.FTransmitVideo;
FTransmitAudio:=aConnectParams_.FTransmitAudio;
FLoop:=aConnectParams_.FLoop;
FreeAndNil(FFileReadThread);
FFileReadThread:=TReadFileThread.Create(FFileName,GetFramerClassFromFileName(FFileName),self);
end;
procedure TMediaStreamDataSource_File.DoDisconnect;
begin
FreeAndNil(FFileReadThread);
end;
constructor TMediaStreamDataSource_File.Create;
begin
inherited;
FDataLock:=TCriticalSection.Create;
FOnFileEnded:=TMediaStreamDataSourceFileEndedEvent.Create;
end;
class function TMediaStreamDataSource_File.CreateConnectParams: TMediaStreamDataSourceConnectParams;
begin
result:=TMediaStreamDataSourceConnectParams_File.Create;
end;
function TMediaStreamDataSource_File.CurrentPosition: int64;
begin
result:=0;
if FFileReadThread<>nil then
result:=TReadFileThread(FFileReadThread).CurrentPosition;
end;
destructor TMediaStreamDataSource_File.Destroy;
begin
Disconnect;
inherited;
FreeAndNil(FOnFileEnded);
FreeAndNil(FDataLock);
end;
function TMediaStreamDataSource_File.GetConnectionErrorDescription(aError: Exception): string;
begin
result:='';
end;
function TMediaStreamDataSource_File.LastStreamDataTime: TDateTime;
begin
if FFileReadThread<>nil then
begin
FDataLock.Enter;
try
result:=FLastStreamDataTime;
finally
FDataLock.Leave;
end;
end
else
result:=0;
end;
function TMediaStreamDataSource_File.Length: int64;
begin
result:=0;
if FFileReadThread<>nil then
result:=TReadFileThread(FFileReadThread).Length;
end;
procedure TMediaStreamDataSource_File.OnDataReceived(const aFormat: TMediaStreamDataHeader;
aData: pointer; aDataSize:cardinal;
aInfo: pointer; aInfoSize: cardinal);
begin
FDataLock.Enter;
try
if (FFileReadThread=nil) then
exit;
FLastStreamDataTime:=Now;
if aFormat.biMediaType=mtAudio then
begin
if FTransmitAudio then
RaiseOnData(aFormat,aData,aDataSize,aInfo,aInfoSize);
end
else if aFormat.biMediaType=mtVideo then
begin
if FTransmitVideo then
RaiseOnData(aFormat,aData,aDataSize,aInfo,aInfoSize);
end;
finally
FDataLock.Leave;
end;
end;
function GetReadThread(aThread : TThread): TReadFileThread;
begin
result:=aThread as TReadFileThread;
Assert(result<>nil);
end;
{ TReadFileThread }
constructor TReadFileThread.Create(const aFileName:string; aFramerClass:TStreamFramerClass; aOwner: TMediaStreamDataSource_File);
begin
FOwner:=aOwner;
FOpenLock:=TCriticalSection.Create;
FReader:=TFileReader.Create(aFileName,aFramerClass);
FStreamInfo:=FReader.StreamInfo;
inherited Create(true);
end;
function TReadFileThread.CurrentPosition: int64;
begin
result:=FReader.CurrentPosition;
end;
destructor TReadFileThread.Destroy;
begin
inherited;
FreeAndNil(FReader);
FreeAndNil(FOpenLock);
end;
procedure TReadFileThread.ProcessFile;
var
aTicks: Cardinal;
aDelay : int64;
aData: pointer;
aDataSize: cardinal;
aInfo: pointer;
aInfoSize: cardinal;
aFormat: TMediaStreamDataHeader;
aStartTicks: cardinal;
aCurrentTicks : cardinal;
aFirstVideoFrame,aFirstAudioFrame : boolean;
aFirstVideoFrameTimestampMs,aFirstAudioFrameTimestampMs,aTimeStampMs,aTimestampDeltaMs: int64;
aFirstVideoFrameTimestamp,aFirstAudioFrameTimestamp, aLastVideoFrameTimestamp,aLastAudioFrameTimestamp: int64;
begin
FOpenLock.Enter;
try
FReader.Reset;
FStreamInfo:=FReader.StreamInfo;
finally
FOpenLock.Leave;
end;
aFirstVideoFrame:=true;
aFirstAudioFrame:=true;
aFirstVideoFrameTimestampMs:=0;
aFirstAudioFrameTimestampMs:=0;
aFirstVideoFrameTimestamp:=0;
aFirstAudioFrameTimestamp:=0;
aLastVideoFrameTimestamp:=0;
aLastAudioFrameTimestamp:=0;
aStartTicks:=GetTickCount;
while not Terminated do
begin
//----------- Читаем фрейм
aFormat.Clear;
if not FReader.GetNextFrame(aFormat,aData,aDataSize, aInfo,aInfoSize) then
break;
aTimeStampMs:=aFormat.TimeStamp*aFormat.TimeKoeff;
//Прежде чем отдать фрейм наружу, посмотрим, сколько нужно подождать от предыдущего фрейма
if (aFormat.biMediaType=mtVideo) then
begin
if (aFirstVideoFrame) then
begin
aFirstVideoFrameTimestampMs:=aTimeStampMs;
aFirstVideoFrameTimestamp:=aFormat.TimeStamp;
end
else begin
aCurrentTicks:=GetTickCount;
if aCurrentTicks<aStartTicks then //Страховка
break;
aTicks:=aCurrentTicks-aStartTicks; //Считаем сколько прошло мс реального времени от момента старта файла
aTimestampDeltaMs:=aTimeStampMs-aFirstVideoFrameTimestampMs;
if (aTimestampDeltaMs>aTicks) {and (aTimestampDeltaMs-aTicks>10) } then //10 мс оставляем на всякие задержки в процессе передачи
aDelay:=aTimestampDeltaMs-aTicks{-10} //Вычитаем из расчетного времени реальное время. Дельта - величина, на сколько надо притормозить
else
aDelay:=0; //Мы не успеваем
//OutputDebugString(PChar(Format('TimeStamp: %d, Delay:%d',[aTimeStampMs,aDelay])));
Assert(aDelay>=0);
if aDelay>0 then
if not FOwner.FNoTimings then
Pause(aDelay)
end;
aLastVideoFrameTimestamp:=aFormat.TimeStamp;
aFirstVideoFrame:=false;
end
else if aFormat.biMediaType=mtAudio then
begin
aLastAudioFrameTimestamp:=aFormat.TimeStamp;
if aFirstAudioFrame then
begin
aFirstAudioFrameTimestamp:=aFormat.TimeStamp;
aFirstAudioFrameTimestampMs:=aTimeStampMs;
end
else begin
if aFirstVideoFrame then
begin
aCurrentTicks:=GetTickCount;
if aCurrentTicks<aStartTicks then //Страховка
break;
aTicks:=aCurrentTicks-aStartTicks; //Считаем сколько прошло мс реального времени от момента старта файла
aTimestampDeltaMs:=aTimeStampMs-aFirstAudioFrameTimestampMs;
if (aTimestampDeltaMs>aTicks) then
aDelay:=aTimestampDeltaMs-aTicks //Вычитаем из расчетного времени реальное время. Дельта - величина, на сколько надо притормозить
else
aDelay:=0; //Мы не успеваем
//OutputDebugString(PChar(Format('TimeStamp: %d, Delay:%d',[aTimeStampMs,aDelay])));
Assert(aDelay>=0);
if aDelay>0 then
if not FOwner.FNoTimings then
begin
inc(FAudioTotalSleep,aDelay);
inc(FAudioSleepHits);
Sleep(aDelay)
end;
end;
end;
aFirstAudioFrame:=false;
end;
if FOwner<>nil then
begin
if aFormat.biMediaType=mtVideo then
inc(aFormat.TimeStamp,FVideoTimeStampBase)
else
inc(aFormat.TimeStamp,FAudioTimeStampBase);
FOwner.OnDataReceived(aFormat,aData,aDataSize,aInfo,aInfoSize);
end;
end;
inc(FVideoTimeStampBase,aLastVideoFrameTimestamp-aFirstVideoFrameTimestamp);
inc(FAudioTimeStampBase,aLastAudioFrameTimestamp-aFirstAudioFrameTimestamp);
end;
procedure TReadFileThread.Execute;
const
aMethodName = 'TReadFileThread.Execute;';
var
aHandler: TMediaStreamDataSourceFileEndedHandler;
begin
SetCurrentThreadName('Source: MediaStream.DataSource.File_.'+ClassName);
while not Terminated do
begin
try
ProcessFile;
except
on E:Exception do
if FOwner<>nil then
; //TODO
end;
for aHandler in FOwner.FOnFileEnded do
aHandler(FOwner);
if not FOwner.FLoop then
break;
end;
end;
function TReadFileThread.Length: int64;
begin
result:=FReader.Length;
end;
{ TFileReader }
constructor TFileReader.Create(const aFileName: string;
aFramerClass: TStreamFramerClass);
begin
FStream:=TFileStream.Create(aFileName,fmOpenRead or fmShareDenyNone);
FFramer:=aFramerClass.Create;
FClean:=true;
//Эта команда нужна:
// 1. она позволяет нам получить формат файла
// 2. она позволяет нам убедиться, что поток валидного формата
FFramer.OpenStream(FStream);
end;
function TFileReader.CurrentPosition: int64;
begin
result:=0;
if FFramer.RandomAccess<>nil then
result:=FFramer.RandomAccess.Position;
end;
destructor TFileReader.Destroy;
begin
FreeAndNil(FFramer);
FreeAndNil(FStream);
inherited;
end;
function TFileReader.GetNextFrame(
out aOutFormat: TMediaStreamDataHeader;
out aOutData: pointer; out aOutDataSize: cardinal;
out aOutInfo: pointer;
out aOutInfoSize: cardinal): boolean;
begin
FClean:=false;
result:=FFramer.GetNextFrame(aOutFormat,aOutData,aOutDataSize,aOutInfo,aOutInfoSize);
end;
function TFileReader.Length: int64;
begin
result:=0;
if FFramer.RandomAccess<>nil then
result:=FFramer.RandomAccess.StreamInfo.Length;
end;
procedure TFileReader.Reset;
begin
if not FClean then
begin
FClean:=true;
FStream.Position:=0;
FFramer.OpenStream(FStream); //Каждый раз заново открываем, потому что нужно сбросить позицию в потоке
end;
end;
function TFileReader.StreamInfo: TBytes;
begin
result:=FFramer.StreamInfo;
end;
function TFileReader.VideoStreamType: TStreamType;
begin
result:=FFramer.VideoStreamType;
end;
function TFileReader.AudioStreamType: TStreamType;
begin
result:=FFramer.AudioStreamType;
end;
initialization
MediaStreamDataSourceFactory.Register('file',TMediaStreamDataSource_File);
end.
|
{
ID: asiapea1
PROG: latin
LANG: PASCAL
}
program latin;
const
maxn=7;
var
fin,fout:text;
row:array[2..maxn-1,1..maxn]of boolean;
col:array[1..maxn,1..maxn]of boolean;
a:array[1..maxn]of byte;
v:array[1..maxn]of boolean;
count:array[2..7]of longint;
{the index means the length of the longest cycle in a[].
When n<=7, all the cycles can be uniquely determined by the longest}
n,i,index:byte;
total:int64;
procedure calindex;
var
i,l,t:byte;
begin
index:=2;fillchar(v,sizeof(v),0);
for i:=1 to n do
if not v[i] then begin
l:=0;t:=i;
repeat
v[t]:=true;t:=a[t];inc(l);
until v[t];
if l>index then index:=l;
end;
end;
procedure search(x,y:byte);
var
i:byte;
begin
for i:=1 to n do
if row[x,i] and col[y,i] then begin
if x=2 then begin
a[y]:=i;
if y=n then begin
calindex;
if count[index]>0 then begin
inc(total,count[index]);
exit;
end;
end;
end;
row[x,i]:=false;col[y,i]:=false;
if y=n then
if x=n-1 then begin inc(count[index]);inc(total);end else search(x+1,2)
else
search(x,y+1);
row[x,i]:=true;col[y,i]:=true;
end;
end;
begin
assign(fin,'latin.in');
reset(fin);
read(fin,n);
close(fin);
assign(fout,'latin.out');
rewrite(fout);
if n=2 then
total:=1
else
if n=7 then begin writeln(fout,'12198297600');close(fout);halt end
else
begin
fillchar(row,sizeof(row),1);
fillchar(col,sizeof(col),1);
fillchar(count,sizeof(count),0);
for i:=2 to n-1 do row[i,i]:=false;
for i:=1 to n do col[i,i]:=false;
total:=0;a[1]:=2;
search(2,2);
for i:=2 to n-1 do
total:=total*i;
end;
writeln(fout,total);
close(fout);
end. |
program iterate_proc;
{никоим образом не программа, просто набросок(полупсевдокод, лол) процедуры, выполняющей шаг расстановки ферзей
* бэктрекингом}
uses crt;
type
TQueenAction = (GetBoard, CheckingIfSolution, FindPlaceToNewQueen);
var
currQueen, itr : byte;
Q: pQueue;
FirstIteration: boolean;
CurrAction: TQueenAction;
board: TBoard;
function Iterate: boolean;
var
copy: TBoard;
begin
if FirstIteration then
begin
{} itr:=1;
{} CurrQueen:=1;
CreateQueue(Q);
PushQueue(Q, 1, GetFreeBoard());
FirstIteration:=False;
end;
case CurrAction of
GetBoard:
begin
if Q=nil then
begin
Iterate:=True;
exit;
end;
PopQueue(Q, currQueen, board);
currAction:=CheckingIfSolution;
itr:=1;
end;
CheckingIfSolution:
begin
if currQueen = N+1 then {we have a new solution, lets remind about it}
begin
writeln('new solution');
//blah-blah
end
else
currAction:=FindPlaceToNewQueen;
end;
FindPlaceToNewQueen:
begin
if board[currQueen, itr] = cFree then
begin
copy:=board;
SetQueenOnBoard(copy, currQueen, itr);
PushQueue(Q, CurrQueen + 1, copy);
end;
if itr=N then
CurrAction:=GetBoard
else
inc(itr);
end;
end;
{отрисовка текущего положения дел}
//write_board;
Iterate:=False;
end;
BEGIN
FirstIteration:=True;
END.
|
{
Ultibo Timezone Builder Tool.
Copyright (C) 2021 - SoftOz Pty Ltd.
Arch
====
<All>
Boards
======
<All>
Licence
=======
LGPLv2.1 with static linking exception (See COPYING.modifiedLGPL.txt)
Credits
=======
Information for this unit was obtained from:
References
==========
Timezone Builder
================
This tool reads all available timezones from the registry on the local computer
and converts them to a TTimezoneList structure to be copied and pasted directly
into the Ultibo Timezone unit.
}
unit Main;
{$MODE Delphi}
interface
uses
LCLIntf,
LCLType,
LMessages,
Messages,
SysUtils,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
StdCtrls,
ExtCtrls,
Registry;
type
TfrmMain = class(TForm)
mmoMain: TMemo;
pnlMain: TPanel;
cmdBuild: TButton;
cmdExit: TButton;
procedure cmdBuildClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure cmdExitClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
type
TTimezoneRec = record {Represents the structure of the TZI value in the Registry}
Bias:LongInt;
StandardBias:LongInt;
DaylightBias:LongInt;
StandardStart:TSystemTime;
DaylightStart:TSystemTime;
end;
const
keyTimezonesNT = '\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones';
var
frmMain: TfrmMain;
function ConvertSingleQuotes(const AValue:String):String;
implementation
{$R *.lfm}
{==============================================================================}
{==============================================================================}
function ConvertSingleQuotes(const AValue:String):String;
var
Count:Integer;
begin
{}
Result:='';
for Count:=1 to Length(AValue) do
begin
{Check for Single Quotes}
if AValue[Count] = '''' then
begin
{Duplicate Single Quotes}
Result:=Result + AValue[Count] + AValue[Count];
end
else
begin
Result:=Result + AValue[Count];
end;
end;
end;
{==============================================================================}
{==============================================================================}
procedure TfrmMain.FormCreate(Sender: TObject);
begin
{}
mmoMain.Text:='Click the build button to build Ultibo timezone information from the current computer';
end;
{==============================================================================}
procedure TfrmMain.FormDestroy(Sender: TObject);
begin
{}
end;
{==============================================================================}
procedure TfrmMain.FormShow(Sender: TObject);
var
Scale:Double;
begin
{}
{Check PixelsPerInch}
if PixelsPerInch > 96 then
begin
{Calculate Scale}
Scale:=(PixelsPerInch / 96);
{Disable Anchors}
cmdBuild.Anchors:=[akLeft,akTop];
cmdExit.Anchors:=[akLeft,akTop];
{Resize Form}
Width:=Trunc(Width * Scale);
Height:=Trunc(Height * Scale);
{Move Buttons}
cmdBuild.Left:=pnlMain.Width - Trunc(171 * Scale); {663 - 492 = 171}
cmdExit.Left:=pnlMain.Width - Trunc(87 * Scale); {663 - 576 = 87}
{Enable Anchors}
cmdBuild.Anchors:=[akRight,akBottom];
cmdExit.Anchors:=[akRight,akBottom];
end;
end;
{==============================================================================}
procedure TfrmMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{}
end;
{==============================================================================}
procedure TfrmMain.cmdBuildClick(Sender: TObject);
var
Count:Integer;
WorkBuffer:String;
Registry:TRegistry;
TimezoneRec:TTimezoneRec;
TimezoneNames:TStringList;
begin
{}
cmdBuild.Enabled:=False;
cmdExit.Enabled:=False;
Registry:=TRegistry.Create;
try
{Clear Text}
mmoMain.Text:='';
{Get Timezone Names}
TimezoneNames:=TStringList.Create;
try
Registry.RootKey:=HKEY_LOCAL_MACHINE;
{Open Key}
if Registry.OpenKeyReadOnly(keyTimezonesNT) then
begin
{Get Names}
Registry.GetKeyNames(TimezoneNames);
{Close Key}
Registry.CloseKey;
{Add Constants}
mmoMain.Lines.Add('const');
mmoMain.Lines.Add(' {Timezone count}');
mmoMain.Lines.Add(' TIMEZONE_COUNT = ' + IntToStr(TimezoneNames.Count) + ';');
mmoMain.Lines.Add('');
{Add Types}
mmoMain.Lines.Add('type');
mmoMain.Lines.Add(' {Timezone List}');
mmoMain.Lines.Add(' PTimezoneList = ^TTimezoneList;');
mmoMain.Lines.Add(' TTimezoneList = record');
mmoMain.Lines.Add(' TimezoneCount:LongWord;');
mmoMain.Lines.Add(' TimezoneData:array[0..(TIMEZONE_COUNT - 1)] of TTimezoneData;');
mmoMain.Lines.Add(' end;');
mmoMain.Lines.Add('');
{Add Header}
mmoMain.Lines.Add('var');
mmoMain.Lines.Add(' {Timezone List}');
mmoMain.Lines.Add(' TimezoneList:TTimezoneList = (');
mmoMain.Lines.Add(' TimezoneCount:' + IntToStr(TimezoneNames.Count) + ';');
mmoMain.Lines.Add(' TimezoneData:(');
mmoMain.Lines.Add('');
{Check each Key}
for Count:=0 to TimezoneNames.Count - 1 do
begin
{Open Subkey}
if Registry.OpenKeyReadOnly(keyTimezonesNT + '\' + TimezoneNames.Strings[Count]) then
begin
{Check Display}
if Registry.ValueExists('Display') then
begin
{Check TZI}
if Registry.ValueExists('TZI') and (Registry.GetDataSize('TZI') >= SizeOf(TTimezoneRec)) then
begin
{Read Timezone Record}
Registry.ReadBinaryData('TZI',TimezoneRec,SizeOf(TTimezoneRec));
{Add Timezone}
mmoMain.Lines.Add(' {' + TimezoneNames.Strings[Count] + '}');
mmoMain.Lines.Add(' (Name:(''' + ConvertSingleQuotes(TimezoneNames.Strings[Count]) + ''');');
mmoMain.Lines.Add(' Description:(''' + ConvertSingleQuotes(Registry.ReadString('Display')) + ''');');
mmoMain.Lines.Add(' Bias:' + IntToStr(TimezoneRec.Bias) + ';');
mmoMain.Lines.Add(' StandardName:(''' + ConvertSingleQuotes(Registry.ReadString('Std')) + ''');');
mmoMain.Lines.Add(' StandardBias:' + IntToStr(TimezoneRec.StandardBias) + ';');
WorkBuffer:=' StandardStart:(wYear:' + IntToStr(TimezoneRec.StandardStart.wYear);
WorkBuffer:=WorkBuffer + ';wMonth:' + IntToStr(TimezoneRec.StandardStart.wMonth);
WorkBuffer:=WorkBuffer + ';wDayOfWeek:' + IntToStr(TimezoneRec.StandardStart.wDayOfWeek);
WorkBuffer:=WorkBuffer + ';wDay:' + IntToStr(TimezoneRec.StandardStart.wDay);
WorkBuffer:=WorkBuffer + ';wHour:' + IntToStr(TimezoneRec.StandardStart.wHour);
WorkBuffer:=WorkBuffer + ';wMinute:' + IntToStr(TimezoneRec.StandardStart.wMinute);
WorkBuffer:=WorkBuffer + ';wSecond:' + IntToStr(TimezoneRec.StandardStart.wSecond);
WorkBuffer:=WorkBuffer + ';wMilliseconds:' + IntToStr(TimezoneRec.StandardStart.wMilliseconds) + ');';
mmoMain.Lines.Add(WorkBuffer);
mmoMain.Lines.Add(' DaylightName:(''' + ConvertSingleQuotes(Registry.ReadString('Dlt')) + ''');');
mmoMain.Lines.Add(' DaylightBias:' + IntToStr(TimezoneRec.DaylightBias) + ';');
WorkBuffer:=' DaylightStart:(wYear:' + IntToStr(TimezoneRec.DaylightStart.wYear);
WorkBuffer:=WorkBuffer + ';wMonth:' + IntToStr(TimezoneRec.DaylightStart.wMonth);
WorkBuffer:=WorkBuffer + ';wDayOfWeek:' + IntToStr(TimezoneRec.DaylightStart.wDayOfWeek);
WorkBuffer:=WorkBuffer + ';wDay:' + IntToStr(TimezoneRec.DaylightStart.wDay);
WorkBuffer:=WorkBuffer + ';wHour:' + IntToStr(TimezoneRec.DaylightStart.wHour);
WorkBuffer:=WorkBuffer + ';wMinute:' + IntToStr(TimezoneRec.DaylightStart.wMinute);
WorkBuffer:=WorkBuffer + ';wSecond:' + IntToStr(TimezoneRec.DaylightStart.wSecond);
WorkBuffer:=WorkBuffer + ';wMilliseconds:' + IntToStr(TimezoneRec.DaylightStart.wMilliseconds) + ');';
mmoMain.Lines.Add(WorkBuffer);
if Count = TimezoneNames.Count - 1 then
begin
mmoMain.Lines.Add(' )');
end
else
begin
mmoMain.Lines.Add(' ),');
end;
mmoMain.Lines.Add('');
end;
end;
Registry.CloseKey;
end;
end;
{Add Footer}
mmoMain.Lines.Add(' )');
mmoMain.Lines.Add(' );');
mmoMain.Lines.Add('');
end;
finally
TimezoneNames.Free;
end;
{Add Completed}
mmoMain.Lines.Add('Build completed, select all of the above text and paste it into the Ultibo timezone module');
finally
Registry.Free;
cmdBuild.Enabled:=True;
cmdExit.Enabled:=True;
end;
end;
{==============================================================================}
procedure TfrmMain.cmdExitClick(Sender: TObject);
begin
{}
Application.Terminate;
end;
{==============================================================================}
{==============================================================================}
end.
|
unit SpriteDevelop;
interface
uses Classes, Controls;
type
TSpriteDevelop = class;
TStageNotifier = procedure(StageManager: TSpriteDevelop; Previous, Current: integer) of object;
TSpriteDevelop = class(TComponent)
private
FCurrentLayer : integer;
FOnLayerChange: TStageNotifier;
procedure SetCurrentLayer(Value: integer);
public
function GetcurrentLayeR: integer;
procedure Refresh;
constructor Create(AOwner: TComponent); override;
procedure SetFOnLayerChange(Value: TStageNotifier);
published
property CurrentLayer: integer read FCurrentLayer write SetCurrentLayer;
property OnLayerChange: TStageNotifier read FOnLayerChange write SetFOnLayerChange;
end;
implementation
constructor TSpriteDevelop.Create(AOwner: TComponent);
begin
FCurrentLayer := 0;
FOnLayerChange:=nil;
inherited Create(AOwner);
end;
procedure TSpriteDevelop.SetCurrentLayer(Value: integer);
begin
if not (csDesigning in ComponentState) then if Assigned(FOnLayerChange) then FOnLayerChange(Self, FCurrentLayer, Value);
FCurrentLayer := Value;
Refresh;
end;
function TSpriteDevelop.GetCurrentLayer: integer;
begin
Result := FCurrentLayer;
end;
procedure TSpriteDevelop.Refresh;
var
i: integer;
begin
for i:=0 to Self.Owner.ComponentCount - 1 do
if Owner.Components[i] is TGraphicControl then
(Owner.Components[i] as TGraphicControl).Invalidate;
end;
procedure TSpriteDevelop.SetFOnLayerChange(Value: TStageNotifier);
begin
FOnLayerChange := Value;
end;
end.
|
unit ComnDirs;
interface
uses Windows, SysUtils, Forms, shlobj;
{{Wrapper над SHGetFolderPath.
Возвращаемый Path без оканчивающего '\'}
function GetSpecialFolderPath(folder : integer) : string;
// утилиты: c:\ProgramData\Prosoft-Systems\EnergoSphere 7
function CommonAppDataPath() : string;
// и c:\ProgramData\Prosoft-Systems\EnergoSphere 7\ECollect (пример для ECollect.exe)
function CommonAppDataPathForExecutable() : string;
function MyDocumentsDir(): string;
{{Возращает путь (без оканчивающего '\') до папки для хранения документов для программы в каталоге документов пользователя (CSIDL_PERSONAL)
E.g. 'C:\Users\USERNAME\Documents\Prosoft-Systems\EnergoSphere 7\ECollect'}
function GetMyDocumentsPathForExecutable(): string;
{{Возращает путь (без оканчивающего '\') до папки для хранения артефактов программы в каталоге данных программы (CSIDL_APPDATA)
E.g. 'C:\Users\USERNAME\AppData\Roaming\Prosoft-Systems\EnergoSphere 7\ECollect'}
function GetAppDataPath(): string;
function CommonDocumentsDir(): string;
implementation
uses SHFolder;
var
FCommonAppDataPath : string = '';
FCommonAppDataPathForExecutable : string = '';
function GetSpecialFolderPath(folder : integer) : string;
const
SHGFP_TYPE_CURRENT = 0;
var
path: array [0..MAX_PATH] of char;
begin
if SUCCEEDED(SHGetFolderPath(0,folder,0,SHGFP_TYPE_CURRENT,@path[0])) then
Result := path
else
Result := '';
end;
function CommonDocumentsDir(): string;
begin
Result := GetSpecialFolderPath(CSIDL_COMMON_DOCUMENTS);
end;
function MyDocumentsDir(): string;
begin
Result := GetSpecialFolderPath(CSIDL_PERSONAL);
end;
function GetProsoftEnergoSpherePath(csIdl: Integer): string;
begin
Result:= Format('%sSitiusATM%s%s',
[IncludeTrailingPathDelimiter(GetSpecialFolderPath(csIdl)), PathDelim,
StringReplace(ExtractFileName(ParamStr(0)), ExtractFileExt(ParamStr(0)), '', [])]);
end;
function GetMyDocumentsPathForExecutable(): string;
begin
Result := GetProsoftEnergoSpherePath(CSIDL_PERSONAL);
end;
function GetAppDataPath(): string;
begin
Result := GetProsoftEnergoSpherePath(CSIDL_APPDATA);
end;
procedure InitPathName();
begin
FCommonAppDataPath := GetSpecialFolderPath(CSIDL_COMMON_APPDATA) + '\SiriusATM\EN Online';
if not ForceDirectories(FCommonAppDataPath) then
FCommonAppDataPath := ''
else begin
FCommonAppDataPathForExecutable := FCommonAppDataPath + '\'
+ StringReplace(ExtractFileName(Application.ExeName), ExtractFileExt(Application.ExeName), '', []);
if not ForceDirectories(FCommonAppDataPathForExecutable) then
FCommonAppDataPathForExecutable := '';
end;
end;
function CommonAppDataPath() : string;
begin
if (FCommonAppDataPath = '') then
InitPathName();
Result := FCommonAppDataPath;
end;
function CommonAppDataPathForExecutable() : string;
begin
if (FCommonAppDataPathForExecutable = '') then
InitPathName();
Result := FCommonAppDataPathForExecutable;
end;
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
OpenGL;
type
TfrmGL = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormResize(Sender: TObject);
private
DC : HDC;
hrc: HGLRC;
ry : GLfloat;
tx : GLfloat;
procedure Detal;
end;
var
frmGL: TfrmGL;
mode : (POINT, LINE, FILL) = LINE;
implementation
{$R *.DFM}
procedure TfrmGL.Detal;
begin
glColor3f (0.0, 0.0, 1.0);
glBegin (GL_POLYGON);
glNormal3f (0, 1, 0);
glVertex3f (6.875, 0, 0);
glVertex3f (10, 0, 0);
glVertex3f (10, 7.0606, 0);
glVertex3f (8.2966, 8.764, 0);
glVertex3f (6.8678, 8.764, 0);
glVertex3f (6.8678, 4.5118, 0);
glEnd;
glBegin (GL_POLYGON);
glVertex3f (3.1322, 4.5118, 0);
glVertex3f (3.1424, 0, 0);
glVertex3f (6.875, 0, 0);
glVertex3f (6.8678, 4.5118, 0);
glEnd;
glBegin (GL_POLYGON);
glVertex3f (3.1322, 4.5118, 0);
glVertex3f (3.1322, 8.764, 0);
glVertex3f (1.7034, 8.764, 0);
glVertex3f (0, 7.0606, 0);
glVertex3f (0, 0, 0);
glVertex3f (3.1424, 0, 0);
glEnd;
glColor3f (1.0, 0.0, 0.0);
glBegin (GL_POLYGON);
glNormal3f (1.0, 0.0, 0.0);
glVertex3f (10, 7.0606, 0);
glVertex3f (10, 0, 0);
glVertex3f (10, 0, -5);
glVertex3f (10, 7.0606, -5);
glEnd;
glBegin (GL_POLYGON);
glNormal3f (1.0, 1.0, 0.0);
glVertex3f (8.2966, 8.764, 0);
glVertex3f (10, 7.0606, 0);
glVertex3f (10, 7.0606, -5);
glVertex3f (8.2966, 8.764, -5);
glEnd;
glBegin (GL_POLYGON);
glNormal3f (0.0, 1.0, 0.0);
glVertex3f (6.8678, 8.764, 0);
glVertex3f (8.2966, 8.764, 0);
glVertex3f (8.2966, 8.764, -5);
glVertex3f (6.8678, 8.764, -5);
glEnd;
glBegin (GL_POLYGON);
glNormal3f (-1.0, 0.0, 0.0);
glVertex3f (6.8678, 4.5118, 0);
glVertex3f (6.8678, 8.764, 0);
glVertex3f (6.8678, 8.764, -5);
glVertex3f (6.8678, 4.5118, -5);
glEnd;
glBegin (GL_POLYGON);
glNormal3f (0.0, 1.0, 0.0);
glVertex3f (6.8678, 4.5118, -5);
glVertex3f (3.1322, 4.5118, -5);
glVertex3f (3.1322, 4.5118, 0);
glVertex3f (6.8678, 4.5118, 0);
glEnd;
glBegin (GL_POLYGON);
glNormal3f (1.0, 0.0, 0.0);
glVertex3f (3.1322, 8.764, 0);
glVertex3f (3.1322, 4.5118, 0);
glVertex3f (3.1322, 4.5118, -5);
glVertex3f (3.1322, 8.764, -5);
glEnd;
glBegin (GL_POLYGON);
glNormal3f (0.0, 1.0, 0.0);
glVertex3f (1.7034, 8.764, 0);
glVertex3f (3.1322, 8.764, 0);
glVertex3f (3.1322, 8.764, -5);
glVertex3f (1.7034, 8.764, -5);
glEnd;
glBegin (GL_POLYGON);
glNormal3f (-1.0, 1.0, 0);
glVertex3f (0, 7.0606, 0);
glVertex3f (1.7034, 8.764, 0);
glVertex3f (1.7034, 8.764, -5);
glVertex3f (0, 7.0606, -5);
glEnd;
glBegin (GL_POLYGON);
glNormal3f (-1.0, 0.0, 0.0);
glVertex3f (0, 7.0606, -5);
glVertex3f (0, 0, -5);
glVertex3f (0, 0, 0);
glVertex3f (0, 7.0606, 0);
glEnd;
glBegin (GL_POLYGON);
glNormal3f (0.0, -1.0, 0.0);
glVertex3f (10, 0, 0);
glVertex3f (6.875, 0, 0);
glVertex3f (3.1424, 0, 0);
glVertex3f (0, 0, 0);
glVertex3f (0, 0, -5);
glVertex3f (3.1424, 0, -5);
glVertex3f (6.875, 0, -5);
glVertex3f (10, 0, -5);
glEnd;
glColor3f (0.0, 0.0, 1.0);
glBegin (GL_POLYGON);
glNormal3f (0.0, 0.0, -1.0);
glVertex3f (6.8678, 4.5118, -5);
glVertex3f (6.8678, 8.764, -5);
glVertex3f (8.2966, 8.764, -5);
glVertex3f (10, 7.0606, -5);
glVertex3f (10, 0, -5);
glVertex3f (6.875, 0, -5);
glEnd;
glBegin (GL_POLYGON);
glVertex3f (6.8678, 4.5118, -5);
glVertex3f (6.875, 0, -5);
glVertex3f (3.1424, 0, -5);
glVertex3f (3.1322, 4.5118, -5);
glEnd;
glBegin (GL_POLYGON);
glVertex3f (0, 7.0606, -5);
glVertex3f (1.7034, 8.764, -5);
glVertex3f (3.1322, 8.764, -5);
glVertex3f (3.1322, 4.5118, -5);
glVertex3f (3.1424, 0, -5);
glVertex3f (0, 0, -5);
glEnd;
end;
{=======================================================================
Перерисовка окна}
procedure TfrmGL.FormPaint(Sender: TObject);
begin
glClear (GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); // очистка буфера цвета
glPushMatrix;
glScalef (0.3, 0.3, 0.3);
glRotatef (ry, 0.0, 1.0, 0.0);
glTranslatef (tx, 0.0, 0.0);
case mode of
POINT : glPolygonMode (GL_FRONT_AND_BACK, GL_POINT);
LINE : glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
FILL : glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
end;
Detal;
glPopMatrix;
SwapBuffers(DC);
end;
{=======================================================================
Формат пикселя}
procedure SetDCPixelFormat (hdc : HDC);
var
pfd : TPixelFormatDescriptor;
nPixelFormat : Integer;
begin
FillChar (pfd, SizeOf (pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat (hdc, @pfd);
SetPixelFormat (hdc, nPixelFormat, @pfd);
end;
{=======================================================================
Создание формы}
procedure TfrmGL.FormCreate(Sender: TObject);
begin
DC := GetDC (Handle);
SetDCPixelFormat(DC);
hrc := wglCreateContext(DC);
wglMakeCurrent(DC, hrc);
glClearColor (0.5, 0.5, 0.75, 1.0); // цвет фона
glLineWidth (1.5);
glEnable (GL_LIGHTING);
glEnable (GL_LIGHT0);
glEnable (GL_DEPTH_TEST);
glEnable (GL_COLOR_MATERIAL);
ry := 0.0;
tx := 0.0;
end;
{=======================================================================
Конец работы приложения}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
wglMakeCurrent(0, 0);
wglDeleteContext(hrc);
ReleaseDC (Handle, DC);
DeleteDC (DC);
end;
procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If Key = VK_ESCAPE then Close;
If Key = VK_LEFT then begin
ry := ry + 2.0;
InvalidateRect(Handle, nil, False);
end;
If Key = VK_RIGHT then begin
ry := ry - 2.0;
InvalidateRect(Handle, nil, False);
end;
If Key = VK_UP then begin
tx := tx - 0.1;
InvalidateRect(Handle, nil, False);
end;
If Key = VK_DOWN then begin
tx := tx + 0.1;
InvalidateRect(Handle, nil, False);
end;
If Key = 49 then begin
mode := POINT;
InvalidateRect(Handle, nil, False);
end;
If Key = 50 then begin
mode := LINE;
InvalidateRect(Handle, nil, False);
end;
If Key = 51 then begin
mode := FILL;
InvalidateRect(Handle, nil, False);
end;
end;
procedure TfrmGL.FormResize(Sender: TObject);
begin
glViewport(0, 0, ClientWidth, ClientHeight);
glMatrixMode (GL_PROJECTION);
glLoadIdentity;
glFrustum (-1, 1, -1, 1, 2, 9);
glMatrixMode (GL_MODELVIEW);
glLoadIdentity;
// этот фрагмент нужен для придания трёхмерности
glTranslatef(0.0, -1.0, -6.0); // перенос объекта - ось Z
glRotatef(30.0, 1.0, 0.0, 0.0); // поворот объекта - ось X
glRotatef(70.0, 0.0, 1.0, 0.0); // поворот объекта - ось Y
InvalidateRect(Handle, nil, False);
end;
end.
|
unit Dimmer;
interface
uses
Winapi.Windows, Winapi.Messages,
System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs;
type
TDimmerForm = class(TForm)
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure Display(const dimForm : TForm);
end;
var
DimmerForm: TDimmerForm;
implementation
{$R *.dfm}
procedure TDimmerForm.Display(const dimForm: TForm);
begin
with Self do
begin
Left := dimForm.Left;
Top := dimForm.Top;
Width := dimForm.Width;
Height := dimForm.Height;
Show;
end;end;
procedure TDimmerForm.FormCreate(Sender: TObject);
begin
AlphaBlend := true;
AlphaBlendValue := 128;
BorderStyle := bsNone;
end;
end.
|
unit FIToolkit.ProjectGroupParser.Parser;
interface
uses
System.SysUtils, System.Types, Xml.XMLIntf;
type
TProjectGroupParser = class sealed
strict private
FXML : IXMLDocument;
private
function GetIncludedProjects : TStringDynArray;
function GetProjectGroupDir : String;
public
constructor Create(const FileName : TFileName);
function GetIncludedProjectsFiles : TArray<TFileName>;
end;
TProjectParser = class sealed
strict private
FXML : IXMLDocument;
private
function GetMainSource : String;
public
constructor Create(const FileName : TFileName);
function GetMainSourceFileName : TFileName;
end;
implementation
uses
System.IOUtils, Xml.XMLDoc, Winapi.ActiveX,
FIToolkit.Commons.Utils,
FIToolkit.ProjectGroupParser.Exceptions, FIToolkit.ProjectGroupParser.Consts;
{ TProjectGroupParser }
constructor TProjectGroupParser.Create(const FileName : TFileName);
begin
inherited Create;
try
FXML := TXMLDocument.Create(FileName);
except
Exception.RaiseOuterException(EProjectGroupParseError.Create);
end;
end;
function TProjectGroupParser.GetIncludedProjects : TStringDynArray;
var
Root, ProjectsGroup, IncludedProject : IXMLNode;
i : Integer;
begin
try
Root := FXML.Node.ChildNodes[STR_GPROJ_ROOT_NODE];
if Assigned(Root) then
begin
ProjectsGroup := Root.ChildNodes[STR_GPROJ_PROJECTS_GROUP_NODE];
if Assigned(ProjectsGroup) then
repeat
IncludedProject := ProjectsGroup.ChildNodes[STR_GPROJ_INCLUDED_PROJECT_NODE];
if not Assigned(IncludedProject) then
ProjectsGroup := ProjectsGroup.NextSibling;
until Assigned(IncludedProject) or not Assigned(ProjectsGroup);
if Assigned(ProjectsGroup) then
for i := 0 to ProjectsGroup.ChildNodes.Count - 1 do
begin
IncludedProject := ProjectsGroup.ChildNodes.Get(i);
if IncludedProject.HasAttribute(STR_GPROJ_INCLUDED_PROJECT_ATTRIBUTE) then
Result := Result + [IncludedProject.Attributes[STR_GPROJ_INCLUDED_PROJECT_ATTRIBUTE]];
end;
end;
except
Exception.RaiseOuterException(EProjectGroupParseError.Create);
end;
if Length(Result) = 0 then
raise EProjectGroupParseError.Create;
end;
function TProjectGroupParser.GetIncludedProjectsFiles : TArray<TFileName>;
var
sRootDir, S : String;
begin
Result := [];
sRootDir := GetProjectGroupDir;
for S in GetIncludedProjects do
with TProjectParser.Create(TPath.Combine(sRootDir, S)) do
try
Result := Result + [GetMainSourceFileName];
finally
Free;
end;
end;
function TProjectGroupParser.GetProjectGroupDir : String;
begin
Result := TPath.GetDirectoryName(FXML.FileName, True);
end;
{ TProjectParser }
constructor TProjectParser.Create(const FileName : TFileName);
begin
inherited Create;
try
FXML := TXMLDocument.Create(FileName);
except
Exception.RaiseOuterException(EProjectParseError.Create);
end;
end;
function TProjectParser.GetMainSource : String;
var
Root, PropertyGroup, MainSource : IXMLNode;
begin
Result := String.Empty;
try
Root := FXML.Node.ChildNodes[STR_DPROJ_ROOT_NODE];
if Assigned(Root) then
begin
PropertyGroup := Root.ChildNodes[STR_DPROJ_PROPERTY_GROUP_NODE];
if Assigned(PropertyGroup) then
repeat
MainSource := PropertyGroup.ChildNodes[STR_DPROJ_MAIN_SOURCE_NODE];
if not Assigned(MainSource) then
PropertyGroup := PropertyGroup.NextSibling;
until Assigned(MainSource) or not Assigned(PropertyGroup);
if Assigned(MainSource) then
Result := MainSource.Text;
end;
except
Exception.RaiseOuterException(EProjectParseError.Create);
end;
if Result.IsEmpty then
raise EProjectParseError.Create;
end;
function TProjectParser.GetMainSourceFileName : TFileName;
begin
Result := TPath.GetDirectoryName(FXML.FileName, True) + GetMainSource;
end;
initialization
CoInitialize(nil);
finalization
CoUninitialize;
end.
|
Unit UnAtualizacao2;
interface
Uses Classes, DbTables,SysUtils;
Type
TAtualiza2 = Class
Private
Aux : TQuery;
DataBase : TDataBase;
procedure AtualizaSenha( Senha : string );
public
function AtualizaTabela(VpaNumAtualizacao : Integer) : Boolean;
function AtualizaBanco : Boolean;
procedure AtualizaPlanoConta;
constructor criar( aowner : TComponent; ADataBase : TDataBase );
end;
Const
CT_SenhaAtual = '9774';
implementation
Uses FunSql, ConstMsg, FunNumeros, Registry, Constantes, FunString, funvalida, AAtualizaSistema;
{*************************** cria a classe ************************************}
constructor TAtualiza2.criar( aowner : TComponent; ADataBase : TDataBase );
begin
inherited Create;
Aux := TQuery.Create(aowner);
DataBase := ADataBase;
Aux.DataBaseName := 'BaseDados';
end;
{*************** atualiza senha na base de dados ***************************** }
procedure TAtualiza2.AtualizaSenha( Senha : string );
var
ini : TRegIniFile;
senhaInicial : string;
begin
try
if not DataBase.InTransaction then
DataBase.StartTransaction;
// atualiza regedit
Ini := TRegIniFile.Create('Software\Systec\Sistema');
senhaInicial := Ini.ReadString('SENHAS','BANCODADOS', ''); // guarda senha do banco
Ini.WriteString('SENHAS','BANCODADOS', Criptografa(senha)); // carrega senha do banco
// atualiza base de dados
LimpaSQLTabela(aux);
AdicionaSQLTabela(Aux, 'grant connect, to DBA identified by ''' + senha + '''');
Aux.ExecSQL;
if DataBase.InTransaction then
DataBase.commit;
ini.free;
except
if DataBase.InTransaction then
DataBase.Rollback;
Ini.WriteString('SENHAS','BANCODADOS', senhaInicial);
ini.free;
end;
end;
{*********************** atualiza o banco de dados ****************************}
function TAtualiza2.AtualizaBanco : boolean;
begin
result := true;
AdicionaSQLAbreTabela(Aux,'Select I_Ult_Alt from Cfg_Geral ');
if Aux.FieldByName('I_Ult_Alt').AsInteger < CT_VersaoBanco Then
result := AtualizaTabela(Aux.FieldByName('I_Ult_Alt').AsInteger);
end;
procedure TAtualiza2.AtualizaPlanoConta;
var
v : TStringList;
laco , conta: integer;
Aux1 : TQuery;
Mascara,Codigo : string;
begin
Aux1 := TQuery.Create(nil);
Aux1.DataBaseName := 'BaseDados';
V := TStringList.create;
AdicionaSQLAbreTabela(aux1, 'Select c_mas_pla from cadempresas where i_cod_emp = 1');
Mascara := aux1.fieldByname('c_mas_pla').AsString;
aux1.close;
AdicionaSQLAbreTabela(aux1, 'Select * from Cad_plano_conta where i_cod_emp = 1');
{ while not aux1.eof do
begin
v.Clear;
codigo := '';
conta := DesmontaCodigo(v, aux1.fieldByname('c_cla_pla').AsString, mascara);
for laco := 0 to v.Count - 1 do
if v.Strings[laco] <> '' then
begin
if codigo <> '' then
codigo := codigo + '.';
codigo := codigo + v.Strings[laco];
ExecutaComandoSql(Aux,' update Cad_Plano_conta ' +
' set C_NIL_00' + inttostr(laco+1)+ ' = ''' +
codigo + '''' +
' where c_cla_pla = ''' + aux1.fieldByname('c_cla_pla').AsString + '''' +
' and i_cod_emp = 1 ');
end;
aux1.Next;
end; }
ExecutaComandoSql(Aux,' update Cad_Plano_conta ' +
' set I_COD_RED = c_cla_pla ');
aux1.close;
aux1.free;
v.free;
end;
{**************************** atualiza a tabela *******************************}
function TAtualiza2.AtualizaTabela(VpaNumAtualizacao : Integer) : Boolean;
var
VpfErro : String;
begin
result := true;
repeat
Try
if VpaNumAtualizacao < 300 Then
begin
VpfErro := '300';
ExecutaComandoSql(Aux,' alter table movnotasfiscaisfor ' +
' modify N_QTD_PRO numeric(17,6) null; ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 300');
end;
if VpaNumAtualizacao < 301 Then
begin
VpfErro := '301';
ExecutaComandoSql(Aux,' insert into cadprodutos(i_seq_pro, i_cod_emp) values (0,1); ' +
' insert into movqdadeproduto(i_seq_pro, i_emp_fil) select 0, i_emp_fil from cadfiliais; ' +
' insert into movtabelapreco(i_seq_pro, i_cod_emp, i_cod_tab) ' +
' select 0,i_cod_emp,I_cod_tab from cadtabelapreco; ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 301' );
end;
if VpaNumAtualizacao < 302 Then
begin
VpfErro := '302';
ExecutaComandoSql(Aux,' insert into cadnatureza(c_cod_nat, c_nom_nat, c_ent_sai, d_ult_alt) ' +
' values(''ECF'', ''Natureza para ECF'', ''S'',now(*)); ' +
' insert into movnatureza(c_cod_nat, i_seq_mov,c_nom_mov, c_ger_fin, c_ent_sai, c_bai_est, c_cal_icm, ' +
' c_ger_com, c_imp_aut, c_ins_ser, c_nat_loc, c_ins_pro, c_mos_not, c_mos_fat, ' +
' d_ult_alt, c_des_not) ' +
' values(''ECF'',1,''ECF'',''S'',''S'',''S'',''S'',''S'',''N'',''S'',''S'',''S'',''N'',''S'',now(*),''ECF''); ' +
' update cadnotafiscais ' +
' set c_cod_nat = ''ECF'', ' +
' i_ite_nat = 1 ' +
' where c_cod_nat is null and c_fla_ecf = ''S''; ' +
' update cadnotafiscais ' +
' set c_ser_not = ''2'' ' +
' where c_fla_ecf = ''S'' and c_ser_not is null; ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 302' );
end;
if VpaNumAtualizacao < 303 Then
begin
VpfErro := '303';
ExecutaComandoSql(Aux,' alter table cad_plano_conta delete c_tip_cus ');
ExecutaComandoSql(Aux,' alter table cad_plano_conta delete c_tip_des ');
ExecutaComandoSql(Aux,' alter table cad_plano_conta add I_TIP_DES integer null');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 303' );
end;
if VpaNumAtualizacao < 304 Then
begin
VpfErro := '304';
ExecutaComandoSql(Aux,' alter table MOVREQUISICAOMATERIAL add D_ULT_ALT date null ');
ExecutaComandoSql(Aux,' update MOVREQUISICAOMATERIAL set D_ULT_ALT = ' + SQLTextoDataAAAAMMMDD(date));
ExecutaComandoSql(Aux,' alter table CADICMSECF add D_ULT_ALT date null ');
ExecutaComandoSql(Aux,' update CADICMSECF set D_ULT_ALT = ' + SQLTextoDataAAAAMMMDD(date));
ExecutaComandoSql(Aux,' alter table MOVITENSCUSTO add D_ULT_ALT date null ');
ExecutaComandoSql(Aux,' update MOVITENSCUSTO set D_ULT_ALT = ' + SQLTextoDataAAAAMMMDD(date));
ExecutaComandoSql(Aux,' alter table MOVSUMARIZAESTOQUE add D_ULT_ALT date null ');
ExecutaComandoSql(Aux,' update MOVSUMARIZAESTOQUE set D_ULT_ALT = ' + SQLTextoDataAAAAMMMDD(date));
ExecutaComandoSql(Aux,' alter table MOVFORMAS add D_ULT_ALT date null ');
ExecutaComandoSql(Aux,' update MOVFORMAS set D_ULT_ALT = ' + SQLTextoDataAAAAMMMDD(date));
ExecutaComandoSql(Aux,' alter table CADTIPOENTREGA add D_ULT_ALT date null ');
ExecutaComandoSql(Aux,' update CADTIPOENTREGA set D_ULT_ALT = ' + SQLTextoDataAAAAMMMDD(date));
ExecutaComandoSql(Aux,' alter table MOVCAIXAESTOQUE add D_ULT_ALT date null ');
ExecutaComandoSql(Aux,' update MOVCAIXAESTOQUE set D_ULT_ALT = ' + SQLTextoDataAAAAMMMDD(date));
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 304' );
end;
if VpaNumAtualizacao < 305 Then
begin
VpfErro := '305';
ExecutaComandoSql(Aux,
' create table PERFIL_RECEBIDO ' +
' ( ' +
' EMP_FIL integer not null, ' +
' COD_PERFIL integer not null, ' +
' DAT_IMPORTACAO date null, ' +
' primary key (EMP_FIL, COD_PERFIL) ' +
' ); ' +
' comment on table PERFIL_RECEBIDO is ''PERFIL RECEBIDOS''; ' +
' comment on column PERFIL_RECEBIDO.EMP_FIL is ''CODIGO EMPRESA FILIAL ''; ' +
' comment on column PERFIL_RECEBIDO.COD_PERFIL is ''CODIGO DPERFIL ''; ' +
' comment on column PERFIL_RECEBIDO.DAT_IMPORTACAO is ''DATA DA ULTIMA IMPORTACAO''; ' +
' create unique index PERFIL_RECEBIDO_PK on PERFIL_RECEBIDO(EMP_FIL asc, COD_PERFIL asc); ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 305' );
end;
if VpaNumAtualizacao < 306 Then
begin
VpfErro := '306';
ExecutaComandoSql(Aux,' alter table cfg_fiscal add C_MOS_INA char(1) null ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 306' );
end;
if VpaNumAtualizacao < 307 Then
begin
VpfErro := '307';
ExecutaComandoSql(Aux,' drop index REF_9027_FK;' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 307' );
end;
if VpaNumAtualizacao < 308 Then
begin
VpfErro := '308';
ExecutaComandoSql(Aux,' create index CP_NOME on CADCLIENTES (C_NOM_CLI asc); ' +
' create index CP_SERIE on CadNotaFIscais(I_EMP_FIL, C_SER_NOT, C_FLA_ECF asc); ' +
' alter table cfg_financeiro add C_SEN_TRA char(1) null ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 308' );
end;
if VpaNumAtualizacao < 309 Then
begin
VpfErro := '309';
ExecutaComandoSql(Aux,
' create table MOVGRUPOUSUARIO ' +
' ( ' +
' I_EMP_FIL integer not null, ' +
' I_COD_USU integer not null, ' +
' I_FIL_NEG integer not null, ' +
' primary key (I_EMP_FIL, I_COD_USU, I_FIL_NEG) ' +
' ); ' +
' comment on table MOVGRUPOUSUARIO is ''PERMITE OU NAO O ACESSO A FILIAL''; ' +
' comment on column MOVGRUPOUSUARIO.I_EMP_FIL is ''CODIGO EMPRESA FILIAL ''; ' +
' comment on column MOVGRUPOUSUARIO.I_COD_USU is ''CODIGO DO USUARIO ''; ' +
' comment on column MOVGRUPOUSUARIO.I_FIL_NEG is ''CODIGO DO FILIAL QUE NAO PODE SER ACESSADO ''; ' +
' create unique index MOVGRUPOUSUARIO_PK on MOVGRUPOUSUARIO (I_EMP_FIL asc, I_COD_USU asc, i_fil_neg ASC); ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 309' );
end;
if VpaNumAtualizacao < 310 Then
begin
VpfErro := '310';
ExecutaComandoSql(Aux,' alter table tabela_exportacao ' +
' add C_PER_UPD char(1) null; ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 310' );
end;
if VpaNumAtualizacao < 311 Then
begin
VpfErro := '311';
ExecutaComandoSql(Aux,' delete movformas ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 311' );
end;
if VpaNumAtualizacao < 312 Then
begin
VpfErro := '312';
ExecutaComandoSql(Aux,' create table MOVFORMA ' +
' ( ' +
' I_EMP_FIL integer not null, ' +
' I_NRO_LOT integer not null, ' +
' I_LAN_REC integer not null, ' +
' I_NRO_PAR integer not null, ' +
' I_COD_FRM integer null, ' +
' N_VLR_MOV numeric(17,3) null, ' +
' C_NRO_CON char(13) null, ' +
' C_NRO_DOC char(20) null, ' +
' C_NOM_CHE char(50) null, ' +
' D_ULT_ALT date null, ' +
' D_CHE_VEN date null, ' +
' I_COD_BAN integer null, ' +
' primary key (I_EMP_FIL, I_NRO_LOT, I_LAN_REC, I_NRO_PAR) ' +
' ); ' +
' comment on table MOVFORMA is ''MOVFORMA''; ' +
' comment on column MOVFORMA.I_EMP_FIL is ''CODIGO DA FILIAL''; ' +
' comment on column MOVFORMA.I_NRO_LOT is ''SEQUENCIAL DO MOVIMENTO''; ' +
' comment on column MOVFORMA.I_LAN_REC is ''NUMERO DO LANCAMENTO''; ' +
' comment on column MOVFORMA.I_NRO_PAR is ''NUMERO DA PARCELA''; ' +
' comment on column MOVFORMA.I_COD_FRM is ''CODIGO DA FORMA DE PAGAMENTO''; ' +
' comment on column MOVFORMA.N_VLR_MOV is ''VALOR DO MOVIMENTO''; ' +
' comment on column MOVFORMA.C_NRO_CON is ''NUMERO DA CONTA''; ' +
' comment on column MOVFORMA.C_NRO_DOC is ''NUMERO DO DOCUMENTO''; ' +
' comment on column MOVFORMA.C_NOM_CHE is ''NOMINAL DO CHEQUE''; ' +
' comment on column MOVFORMA.D_ULT_ALT is ''DATA DE ALTERACAO''; ' +
' comment on column MOVFORMA.D_CHE_VEN is ''VENCIMENTO DO CHEQUE''; ' +
' comment on column MOVFORMA.I_COD_BAN is ''CODIGO DO BANCO''; ' +
' alter table MOVFORMA ' +
' add foreign key FK_MOVFORMA_REF_17882_MOVCONTA (I_EMP_FIL, I_LAN_REC, I_NRO_PAR) ' +
' references MOVCONTASARECEBER (I_EMP_FIL, I_LAN_REC, I_NRO_PAR) on update restrict on delete restrict; ' +
' alter table MOVFORMA ' +
' add foreign key FK_MOVFORMA_REF_17883_CADBANCO (I_COD_BAN) ' +
' references CADBANCOS (I_COD_BAN) on update restrict on delete restrict; ' +
' alter table MOVFORMA ' +
' add foreign key FK_MOVFORMA_REF_17883_CADFORMA (I_COD_FRM) ' +
' references CADFORMASPAGAMENTO (I_COD_FRM) on update restrict on delete restrict; ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 312' );
end;
if VpaNumAtualizacao < 313 Then
begin
VpfErro := '313';
ExecutaComandoSql(Aux,' create unique index MOVFORMA on MOVFORMA (I_EMP_FIL asc, I_NRO_LOT asc, I_NRO_PAR asc, I_LAN_REC asc); ' +
' create unique index MOVFORMA_PK on MOVFORMA (I_EMP_FIL asc, I_NRO_LOT asc, I_LAN_REC asc, I_NRO_PAR asc); ' +
' create index Ref_178825_FK on MOVFORMA (I_EMP_FIL asc, I_LAN_REC asc, I_NRO_PAR asc); ' +
' create index Ref_178832_FK on MOVFORMA (I_COD_BAN asc); ' +
' create index Ref_178835_FK on MOVFORMA (I_COD_FRM asc); ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 313' );
end;
if VpaNumAtualizacao < 314 Then
begin
VpfErro := '314';
ExecutaComandoSql(Aux,' insert into movforma( i_emp_fil, i_nro_lot, i_cod_frm, ' +
' n_vlr_mov, c_nro_con,c_nro_doc, c_nom_che, ' +
' d_ult_alt, i_lan_rec, i_nro_par, d_che_ven, i_cod_ban) ' +
' select i_emp_fil, i_lan_rec, i_cod_frm, isnull(n_vlr_che,n_vlr_par), ' +
' isnull(c_con_che,c_nro_con),isnull(c_nro_che, c_nro_doc), null, ' +
' d_ult_alt, i_lan_rec, i_nro_par, d_che_ven, i_cod_ban ' +
' from movcontasareceber ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 314' );
end;
if VpaNumAtualizacao < 315 Then
begin
VpfErro := '315';
ExecutaComandoSql(Aux,' alter table movcontasareceber ' +
' drop foreign key FK_BANCOS; ' +
' alter table movcontasareceber ' +
' drop foreign key FK_CADCONTAS; ' +
' alter table movcontasareceber ' +
' drop foreign key FK_MOVBANCOS; ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 315' );
end;
if VpaNumAtualizacao < 316 Then
begin
VpfErro := '316';
ExecutaComandoSql(Aux,' drop index FK_CADCONTAS_FK; ' +
' drop index FK_MOVBANCOS_FK; ' +
' drop index FK_REF_12154_FK; ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 316' );
end;
if VpaNumAtualizacao < 317 Then
begin
VpfErro := '317';
ExecutaComandoSql(Aux,' alter table movcontasareceber ' +
' delete c_nro_con, ' +
' delete c_nro_doc, ' +
' delete d_che_ven, ' +
' delete i_cod_ban, ' +
' delete c_con_che, ' +
' delete n_vlr_che, ' +
' delete c_nro_che; ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 317' );
end;
if VpaNumAtualizacao < 318 Then
begin
VpfErro := '318';
ExecutaComandoSql(Aux,' create index CP1_MOVFORMA on MOVFORMA(D_CHE_VEN asc); ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 318' );
end;
if VpaNumAtualizacao < 319 Then
begin
VpfErro := '319';
ExecutaComandoSql(Aux,' create table MOVCHEQUEDEVOLVIDO ' +
' ( ' +
' I_EMP_FIL integer not null, ' +
' I_NRO_LAN integer not null, ' +
' I_COD_CLI integer null, ' +
' I_LAN_REC integer null, ' +
' I_NRO_PAR integer null, ' +
' N_VLR_MOV numeric(17,3) null, ' +
' C_NRO_CON char(13) null, ' +
' C_NRO_DOC char(20) null, ' +
' D_ULT_ALT date null, ' +
' D_CHE_VEN date null, ' +
' I_COD_BAN integer null, ' +
' C_SIT_CHE CHAR(1) null, ' +
' primary key (I_EMP_FIL, I_NRO_LAN ) ' +
' ); ' +
' comment on table MOVCHEQUEDEVOLVIDO is ''MOVIMENTO DE CHEQUES DEVOLVIDO''; ' +
' comment on column MOVCHEQUEDEVOLVIDO.I_EMP_FIL is ''CODIGO DA FILIAL''; ' +
' comment on column MOVCHEQUEDEVOLVIDO.I_NRO_LAN is ''SEQUENCIAL DO MOVIMENTO''; ' +
' comment on column MOVCHEQUEDEVOLVIDO.I_COD_CLI is ''SEQUENCIAL DO MOVIMENTO''; ' +
' comment on column MOVCHEQUEDEVOLVIDO.I_LAN_REC is ''NUMERO DO LANCAMENTO''; ' +
' comment on column MOVCHEQUEDEVOLVIDO.I_NRO_PAR is ''NUMERO DA PARCELA''; ' +
' comment on column MOVCHEQUEDEVOLVIDO.N_VLR_MOV is ''VALOR DO MOVIMENTO''; ' +
' comment on column MOVCHEQUEDEVOLVIDO.C_NRO_CON is ''NUMERO DA CONTA''; ' +
' comment on column MOVCHEQUEDEVOLVIDO.C_NRO_DOC is ''NUMERO DO DOCUMENTO''; ' +
' comment on column MOVCHEQUEDEVOLVIDO.D_ULT_ALT is ''DATA DE ALTERACAO''; ' +
' comment on column MOVCHEQUEDEVOLVIDO.D_CHE_VEN is ''VENCIMENTO DO CHEQUE''; ' +
' comment on column MOVCHEQUEDEVOLVIDO.I_COD_BAN is ''CODIGO DO BANCO''; ' +
' comment on column MOVCHEQUEDEVOLVIDO.C_SIT_CHE is ''SITUACAO DO CHEQUE''; ' +
' alter table MOVCHEQUEDEVOLVIDO ' +
' add foreign key FK_MOVCHEQUE_REF_23984 (I_COD_CLI) ' +
' references CADCLIENTES(I_COD_CLI) on update restrict on delete restrict; ' +
' alter table MOVCHEQUEDEVOLVIDO ' +
' add foreign key FK_MOVCHEQUE_343_CADBANCO (I_COD_BAN) ' +
' references CADBANCOS (I_COD_BAN) on update restrict on delete restrict; ' +
' create unique index MOVCHEQUE_PK on MOVCHEQUEDEVOLVIDO (I_EMP_FIL asc, I_NRO_LAN asc ); ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 319' );
end;
if VpaNumAtualizacao < 320 Then
begin
VpfErro := '320';
ExecutaComandoSql(Aux,' alter table movforma ' +
' add C_SIT_FRM char(1) null, ' +
' add I_LAN_BAC integer null; ' +
' update movForma set c_sit_frm = ''C'' ;');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 320' );
end;
if VpaNumAtualizacao < 321 Then
begin
VpfErro := '321';
ExecutaComandoSql(Aux,' alter table CRP_PARCIAL ' +
' drop foreign key FK_REF_36344; ' +
' alter table MOV_DIARIO ' +
' drop foreign key FK_REF_36359; ' +
' alter table MOV_DIARIO ' +
' drop foreign key FK_REF_31497; ' +
' alter table MOV_ALTERACAO ' +
' drop foreign key FK_REF_40679; ');
ExecutaComandoSql(Aux,' update cadusuarios ' +
' set i_cod_usu = cast( i_emp_fil ||''0'' || i_cod_usu as integer) ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 321' );
end;
if VpaNumAtualizacao < 322 Then
begin
VpfErro := '322';
ExecutaComandoSql(Aux,' drop index FK_REF_295_FK; ' +
' drop index MOVGRUPOFORM_PK; ' +
' alter TABLE MOVGRUPOFORM drop primary key; ' +
' alter table MOVGRUPOFORM ' +
' drop foreign key FK_REF_295; ' +
' update movgrupoform ' +
' set i_cod_gru = cast( i_emp_fil ||''0'' || i_cod_gru as integer); ' +
' alter table movgrupoform ' +
' delete i_emp_fil; ' +
' alter table MovGrupoForm add primary key (i_cod_gru, c_cod_fom); ' +
' create index MovGrupoForm_PK on MovGrupoForm (i_cod_gru, c_cod_fom); ' +
' alter table CADUSUARIOS ' +
' drop foreign key FK_REF_275; ' +
' alter table CADGRUPOS ' +
' drop foreign key FK_REF_328; ' +
' drop index CADGRUPOS_PK; ' +
' drop index FK_REF_328_FK; ' +
' alter TABLE CADGRUPOS drop primary key; ' +
' update cadgrupos ' +
' set i_cod_gru = cast( i_emp_fil ||''0'' || i_cod_gru as integer); ' +
' update cadusuarios ' +
' set i_cod_gru = cast( i_emp_fil ||''0'' || i_cod_gru as integer); ' +
' alter table Cadgrupos add primary key (i_cod_gru); ' +
' create index CADGRUPOS_PK on CadGrupos (i_cod_gru); ' +
' alter table cadusuarios ' +
' add foreign key FK_CADUSUGRU_REF_1234 (I_COD_GRU) ' +
' references CADGRUPOS(I_COD_GRU) on update restrict on delete restrict; ' +
' alter table movgrupoform ' +
' add foreign key FK_CADGRUFOR_REF_12334 (I_COD_GRU) ' +
' references CADGRUPOS(I_COD_GRU) on update restrict on delete restrict; ' +
' drop index CADUSUARIOS_PK; ' +
' alter TABLE CADUSUARIOS drop primary key; ' +
' alter table CadUsuarios add primary key (i_cod_usu); ' +
' create index CADUSUARIOS_PK on CadUsuarios(i_cod_usu); ' +
' alter table cadusuarios ' +
' add foreign key FK_CADFILIAL_REF_12345 (I_EMP_FIL) ' +
' references CADFILIAIS(I_EMP_FIL) on update restrict on delete restrict; ' +
' alter table cadgrupos ' +
' add foreign key FK_CADFILIAL_REF_1234 (I_EMP_FIL) ' +
' references CADFILIAIS(I_EMP_FIL) on update restrict on delete restrict; ' +
' create index FK_CADFILIAL_234 on CadUsuarios(i_emp_fil); ' +
' create index FK_CADFILIAL_2578 on CadGrupos(i_emp_fil); ' +
' delete MOVGRUPOUSUARIO; commit; ' +
' drop index MOVGRUPOUSUARIO_PK; ' +
' alter table MOVGRUPOUSUARIO drop primary key; ' +
' alter table MOVGRUPOUSUARIO add primary key (i_cod_usu, i_fil_neg); ' +
' create index MOVGRUPOUSUARIO_PK on MOVGRUPOUSUARIO(i_cod_usu, i_fil_neg); ' +
' alter table MOVGRUPOUSUARIO add D_ULT_ALT date null; ' +
' alter table MOVGRUPOUSUARIO delete I_EMP_FIL; ' +
' alter table MOVGRUPOUSUARIO ' +
' add foreign key FK_CADUSUARIOPER_REF_496 (I_COD_USU) ' +
' references CADUSUARIOS(I_COD_USU) on update restrict on delete restrict; ' +
' create index FK_MOVGRUPOUSUARIO_1244 on MOVGRUPOUSUARIO(i_cod_usu); ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 322' );
end;
if VpaNumAtualizacao < 323 Then
begin
VpfErro := '323';
ExecutaComandoSql(Aux,' update cadclientes set i_cod_usu = cast(110 || i_cod_usu as integer) where i_cod_usu is not null; ' +
' update cadcontasapagar ' +
' set i_cod_usu = cast(i_emp_fil || ''0'' || i_cod_usu as integer) ' +
' where i_cod_usu is not null; ' +
' update cadcontasareceber ' +
' set i_cod_usu = cast(i_emp_fil || ''0'' || i_cod_usu as integer) ' +
' where i_cod_usu is not null; ' +
' update cadnotafiscais ' +
' set i_cod_usu = cast(i_emp_fil || ''0'' || i_cod_usu as integer) ' +
' where i_cod_usu is not null; ' +
' update cadorcamentos ' +
' set i_cod_usu = cast(i_emp_fil || ''0'' || i_cod_usu as integer) ' +
' where i_cod_usu is not null; ' +
' update cadOrdemServico ' +
' set i_cod_usu = cast(i_emp_fil || ''0'' || i_cod_usu as integer) ' +
' where i_cod_usu is not null; ' +
' update cadOrdemServico ' +
' set i_cod_ate = cast(i_emp_fil || ''0'' || i_cod_ate as integer) ' +
' where i_cod_ate is not null; ' +
' update cadRequisicaoMaterial ' +
' set i_cod_usu = cast(i_emp_fil || ''0'' || i_cod_usu as integer) ' +
' where i_cod_usu is not null; ' +
' update cadRequisicaoMaterial ' +
' set i_usu_req = cast(i_emp_fil || ''0'' || i_usu_req as integer) ' +
' where i_usu_req is not null; ' +
' update MovCaixaEstoque ' +
' set i_cod_usu = cast(i_emp_fil || ''0'' || i_cod_usu as integer) ' +
' where i_cod_usu is not null; ' +
' update movcontasapagar ' +
' set i_cod_usu = cast(i_emp_fil || ''0'' || i_cod_usu as integer) ' +
' where i_cod_usu is not null; ' +
' update movcontasareceber ' +
' set i_cod_usu = cast(i_emp_fil || ''0'' || i_cod_usu as integer) ' +
' where i_cod_usu is not null; ' +
' update movordemservico ' +
' set i_cod_usu = cast(i_emp_fil || ''0'' || i_cod_usu as integer) ' +
' where i_cod_usu is not null; ' +
' update movHistoricoCliente ' +
' set i_cod_usu = cast(110 || i_cod_usu as integer) ' +
' where i_cod_usu is not null; ' +
' update crp_parcial ' +
' set cod_usuario = cast(110 || cod_usuario as integer) ' +
' where cod_usuario is not null; ' +
' update mov_alteracao ' +
' set cod_usuario_alteracao = cast(110 || cod_usuario_alteracao as integer) ' +
' where cod_usuario_alteracao is not null; ' +
' update mov_diario ' +
' set cod_usuario_abertura = cast(110 || cod_usuario_abertura as integer) ' +
' where cod_usuario_abertura is not null; ' +
' update mov_diario ' +
' set cod_usuario_Fechamento = cast(110 || cod_usuario_fechamento as integer) ' +
' where cod_usuario_fechamento is not null; ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 323' );
end;
if VpaNumAtualizacao < 324 Then
begin
VpfErro := '324';
ExecutaComandoSql(Aux,' alter table CadUsuarios ' +
' add C_FIL_NEG varChar(100) null; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 324' );
end;
if VpaNumAtualizacao < 325 Then
begin
VpfErro := '325';
ExecutaComandoSql(Aux,' alter table CadUsuarios ' +
' add I_FIL_INI integer null; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 325' );
end;
if VpaNumAtualizacao < 326 Then
begin
VpfErro := '326';
ExecutaComandoSql(Aux,' alter table CadProdutos ' +
' add I_ORI_MER integer null; ' +
' update cadprodutos set i_ori_mer = 0;');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 326' );
end;
if VpaNumAtualizacao < 327 Then
begin
VpfErro := '327';
ExecutaComandoSql(Aux,' alter table cfg_fiscal ' +
' delete c_cst_not; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 327' );
end;
if VpaNumAtualizacao < 328 Then
begin
VpfErro := '328';
ExecutaComandoSql(Aux,' alter table movnatureza ' +
' add C_ATI_NAT char(1) null, ' +
' add C_NAT_IMP char(10) null, ' +
' add C_CLI_FOR char(1) null; ' +
' update movnatureza set c_cli_for = c_ent_sai; ' +
' update movnatureza mov ' +
' set c_nat_imp = (select c_cod_nat from cadnatureza mov1 where mov.c_cod_nat = mov1.c_cod_nat); ' +
' alter table CadNotafiscais ' +
' drop foreign Key CADNATUREZA_FK_234; ' +
' alter table MovNatureza ' +
' drop foreign Key FK_MOVNATUR_REF_67857_CADNATUR; ' +
' update movnatureza mov ' +
' set c_ent_sai = (select c_ent_sai from cadnatureza mov1 where mov.c_cod_nat = mov1.c_cod_nat); ' +
' drop table cadnatureza; ' +
' alter table movnatureza rename CADNATUREZA; ' +
' drop index MOVNATUREZA_PK; ' +
' alter TABLE cadnatureza drop primary key; ' +
' update cadnatureza ' +
' set c_cod_nat = c_cod_nat ||''.'' || i_seq_mov; ' +
' alter table cadnatureza delete i_seq_mov; ' +
' alter table cadnatureza add primary key (C_COD_NAT); ' +
' create index CADNATUREZA_PK on cadnatureza (C_COD_NAT); ' +
' update cadNotaFiscais ' +
' set c_cod_nat = c_cod_nat ||''.'' || i_ite_nat; ' +
' update movNotasFiscaisFor ' +
' set c_cod_nat = c_cod_nat ||''.'' || i_ite_nat; ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 328' );
end;
if VpaNumAtualizacao < 329 Then
begin
VpfErro := '329';
ExecutaComandoSql(Aux,' update cadnotafiscais ' +
' set c_cod_nat = null ' +
' where c_cod_nat not in( select c_cod_nat from cadnatureza); ' +
' update movnotasfiscaisfor ' +
' set c_cod_nat = null ' +
' where c_cod_nat not in( select c_cod_nat from cadnatureza); ' +
' alter table CadNotaFiscais ' +
' add foreign key FK_NATUREZA_REF_121 (C_COD_NAT) ' +
' references CadNatureza(C_COD_NAT) on update cascade on delete restrict; ' +
' alter table MovNotasFiscaisFor ' +
' add foreign key FK_NATUREZA_REF_345 (C_COD_NAT) ' +
' references CadNatureza(C_COD_NAT) on update cascade on delete restrict; ' +
' alter table cadnotafiscais delete i_ite_nat; ' +
' alter table MOvnotasfiscaisfor delete i_ite_nat; ' +
' create index FK_CADNAT_8498 on MovNotasFiscaisFor (C_COD_NAT); ' +
' alter table cadnatureza add C_TIP_NAT char(1) null; ' +
' alter table cadnatureza ' +
' rename c_nom_mov to C_NOM_NAT; ' +
' update cadnatureza set c_ati_nat = ''S'';' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 329' );
end;
if VpaNumAtualizacao < 330 Then // CADEMITENTES
begin
VpfErro := '330';
ExecutaComandoSql(Aux,'create table CADEMITENTES ' +
'( '+
' I_COD_EMI integer not null, ' +
' C_NOM_EMI char(50) null, ' +
' C_TIP_PES char(1) null, ' +
' D_ULT_ALT date null, ' +
' C_CGC_EMI char(18) null, ' +
' C_CPF_EMI char(14) null, ' +
' primary key (I_COD_EMI) ' +
');'+
' create table CADFACTORI ' + // CADFACTORI
'( '+
' I_EMP_FIL integer not null, ' +
' I_LAN_FAC integer not null, ' +
' I_COD_CLI integer not null, ' +
' D_DAT_MOV date null, ' +
' D_ULT_ALT date null, ' +
' N_PER_CPM numeric(17,5) null, ' +
' N_VAL_TOT numeric(17,5) null, ' +
' primary key (I_EMP_FIL, I_LAN_FAC) ' +
');'+
' create table MOVFACTORI ' + // MOVFACTORI
'( '+
' I_EMP_FIL integer not null, ' +
' I_LAN_FAC integer not null, ' +
' I_NRO_LAN integer not null, ' +
' I_COD_EMI integer null,' +
' I_COD_BAN integer null, ' +
' C_NRO_DOC char(20) null, ' +
' N_VLR_DOC numeric(17,2) null, ' +
' D_DAT_VEN date null, ' +
' I_DIA_VEN integer null, ' +
' N_PER_JUR numeric(17,5) null, ' +
' N_VLR_JUR numeric(17,2) null, ' +
' N_TOT_LIQ numeric(17,2) null, ' +
' C_TIP_DOC char(1) null, ' +
' D_DAT_PAG date null, ' +
' N_VLR_PAG numeric(17,2) null, ' +
' D_ULT_ALT date null, ' +
' N_PER_CPM numeric(17,5) null, ' +
' N_VLR_CPM numeric(17,2) null, ' +
' D_EMI_DOC date null, ' +
' C_NRO_CON char(13) null, ' +
' C_SIT_DOC char(1) null, ' +
' D_DAT_DEV date null, ' +
' D_DAT_DEP date null, ' +
' D_DAT_REN date null, ' +
' D_DAT_REA date null, ' +
' primary key (I_EMP_FIL, I_LAN_FAC, I_NRO_LAN) ' +
');'+
// COMENTÁRIOS
' comment on table CADFACTORI is ''CADASTRAR FACTORING ''; ' +
' comment on table CADEMITENTES is ''CADASTRAR EMITENTES'';' +
' comment on table MOVFACTORI is ''MOVIMENTO DA FACTORI''; ' +
' alter table MOVFACTORI ' +
' add foreign key FK_MOVFACTO_REF_17466_CADFACTO (I_EMP_FIL, I_LAN_FAC)' +
' references CADFACTORI (I_EMP_FIL, I_LAN_FAC) on update restrict on delete restrict; ' +
' alter table MOVFACTORI ' +
' add foreign key FK_MOVFACTO_REF_112_CADEMITE (I_COD_EMI) '+
' references CADEMITENTES (I_COD_EMI) on update restrict on delete restrict; ' +
' create unique index CADEMITENTES_PK on CADEMITENTES (I_COD_EMI asc); ' +
' create index "FK_CADFACTO_REF_17465_CADCLIEN(foreign key)" on CADFACTORI (I_COD_CLI asc); ' +
' create index "FK_CADFACTO_REF_17465_CADFILIA(foreign key)" on CADFACTORI (I_EMP_FIL asc); ' +
' create index Ref_174652_FK on CADFACTORI (I_EMP_FIL asc); ' +
' create index Ref_174656_FK on CADFACTORI (I_COD_CLI asc); ' +
' create unique index CADFACTORI_PK on CADFACTORI (I_EMP_FIL asc, I_LAN_FAC asc); ' +
' create index "FK_MOVFACTO_REF_17555_CADBANCO(foreign key)" on MOVFACTORI (I_COD_BAN asc); ' +
' create index Ref_175550_FK on MOVFACTORI (I_COD_BAN asc); ' +
' create unique index MOVFACTORI_PK on MOVFACTORI (I_EMP_FIL asc, I_LAN_FAC asc, I_NRO_LAN asc); ' +
' create index FK_MOVFACTO_REF_17466_CADFACTO_FK on MOVFACTORI (I_EMP_FIL asc, I_LAN_FAC asc); ' +
' create index Ref_112_FK on MOVFACTORI (I_COD_EMI asc)');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 330');
end;
if VpaNumAtualizacao < 331 Then
begin
VpfErro := '331';
ExecutaComandoSql(Aux,' alter table cfg_fiscal ' +
' add C_PER_NOT char(1) null; ' +
' alter table cfg_servicos ' +
' add C_KIT_ORC char(1) null;');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 331' );
end;
if VpaNumAtualizacao < 332 Then
begin
VpfErro := '332';
ExecutaComandoSql(Aux,' alter table CadClientes ' +
' add C_NOM_FAN VarChar(30) null; ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 332' );
end;
if VpaNumAtualizacao < 333 Then
begin
VpfErro := '333';
ExecutaComandoSql(Aux,' alter table CadNatureza ' +
' add C_GER_IMP Char(1) null; ' +
' update cadnatureza set c_ger_imp = c_mos_fat ;' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 333' );
end;
if VpaNumAtualizacao < 334 Then
begin
VpfErro := '334';
ExecutaComandoSql(Aux,' alter table CadNatureza ' +
' add C_NOT_CUP Char(1) null; ' +
' update cadnatureza set c_not_cup = ''N'' ;' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 334' );
end;
if VpaNumAtualizacao < 335 Then
begin
VpfErro := '335';
ExecutaComandoSql(Aux,' alter table CadNatureza ' +
' add C_FIL_PER Char(20) null; ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 335' );
end;
if VpaNumAtualizacao < 336 Then
begin
VpfErro := '336';
ExecutaComandoSql(Aux,' alter table Perfil_Exportacao ' +
' add FILIAL_EXPORTACAO Char(40) null; ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 336' );
end;
if VpaNumAtualizacao < 337 Then
begin
VpfErro := '337';
ExecutaComandoSql(Aux,' alter table cadordemservico ' +
' add C_CHA_TEC char(1) null, ' +
' add C_TIP_CHA char(1) null; ' +
' alter table cfg_financeiro ' +
' add C_PLA_ABE char(1) null; ' +
' alter table cfg_fiscal ' +
' add C_CAR_INA integer null; ' +
' update cadnatureza ' +
' set c_cod_nat = ''ECF'' ' +
' where c_nat_imp = ''ECF'';');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 337' );
end;
if VpaNumAtualizacao < 338 Then
begin
VpfErro := '338';
ExecutaComandoSql(Aux,' alter table CADVENDEDORES ' +
' add C_ATI_VEN char(1) null, ' +
' add I_EMP_FIL integer null, ' +
' add I_IND_VEN integer null; ' +
' Update CADVENDEDORES set C_ATI_VEN = ''S'' ;');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 338' );
end;
if VpaNumAtualizacao < 339 Then
begin
VpfErro := '339';
ExecutaComandoSql(Aux,' alter table CFG_MODULO ' +
' add FLA_ACADEMICO char(1) null; ' +
' Update CFG_MODULO set FLA_ACADEMICO = ''F'' ;');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 339' );
end;
if VpaNumAtualizacao < 340 Then
begin
VpfErro := '340';
ExecutaComandoSql(Aux,' alter table CadUsuarios ' +
' add C_MOD_ACA char(1) null; ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 340' );
end;
if VpaNumAtualizacao < 341 Then
begin
VpfErro := '341';
ExecutaComandoSql(Aux,' alter table CadContasaReceber ' +
' add I_NRO_MAT integer null; ' +
' alter table cadempresas ' +
' add C_MAS_AUL char(15) null; ' +
' alter table cfg_geral ' +
' add I_TIP_NOM integer null;' +
' update cfg_geral set i_tip_nom = 1');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 341' );
end;
if VpaNumAtualizacao < 342 Then
begin
VpfErro := '342';
ExecutaComandoSql(Aux,' alter table CadContasaReceber ' +
' rename I_NRO_MAT to I_COD_MAT; ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 342' );
end;
if VpaNumAtualizacao < 343 Then
begin
VpfErro := '343';
ExecutaComandoSql(Aux,' alter table CFG_GERAL ' +
' add D_ULT_EXP date null; ' +
' update cfg_geral set d_ult_exp = ''1998/01/01'';');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 343' );
end;
if VpaNumAtualizacao < 344 Then
begin
VpfErro := '344';
ExecutaComandoSql(Aux,' alter table CFG_GERAL ' +
' add C_MAN_COP char(1) null, ' +
' add C_MAN_COR char(1) null; ' +
' update cfg_geral set c_man_cop = ''T'';' +
' update cfg_geral set c_man_cor = ''T'';' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 344' );
end;
if VpaNumAtualizacao < 345 Then
begin
VpfErro := '345';
ExecutaComandoSql(Aux,' alter table CFG_FINANCEIRO ' +
' add C_RET_MES char(1) null ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 345' );
end;
if VpaNumAtualizacao < 346 Then
begin
VpfErro := '346';
ExecutaComandoSql(Aux,' alter table MOVCONTASARECEBER ' +
' add D_DAT_EST date null, ' +
' add I_USU_EST integer null; ' +
' alter table MOVCONTASAPAGAR ' +
' add D_DAT_EST date null, ' +
' add I_USU_EST integer null; ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 346' );
end;
if VpaNumAtualizacao < 347 Then
begin
VpfErro := '347';
ExecutaComandoSql(Aux,' alter table CFG_GERAL' +
' add I_VER_PER integer null ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 347' );
end;
if VpaNumAtualizacao < 348 Then
begin
VpfErro := '348';
ExecutaComandoSql(Aux,' alter table CadOrdemServico' +
' delete c_vlr_per ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 348' );
end;
if VpaNumAtualizacao < 349 Then
begin
VpfErro := '349';
ExecutaComandoSql(Aux,' alter table CadOrdemServico' +
' add I_NRO_ATE integer null' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 349' );
end;
if VpaNumAtualizacao < 350 Then
begin
VpfErro := '350';
ExecutaComandoSql(Aux,' alter table CFG_FISCAL' +
' add C_NAT_ORS char(10) null;' +
' alter table CFG_SERVICOS ' +
' add I_SIT_ORC integer null ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 350' );
end;
if VpaNumAtualizacao < 351 Then
begin
VpfErro := '351';
ExecutaComandoSql(Aux,' update cadordemservico ' +
' set c_cha_tec = ''N'' ' +
' where c_cha_tec is null; ' +
' update cadordemservico ' +
' set c_tip_cha = ''N'' ' +
' where c_tip_cha is null ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 351' );
end;
if VpaNumAtualizacao < 352 Then
begin
VpfErro := '352';
ExecutaComandoSql(Aux,' alter table CFG_SERVICOS ' +
' add C_ADI_OBS char(1) null ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 352' );
end;
if VpaNumAtualizacao < 353 Then
begin
VpfErro := '353';
ExecutaComandoSql(Aux,' create index CP_CONTRATO on CADCONTASARECEBER (I_COD_MAT asc); ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 353' );
end;
if VpaNumAtualizacao < 354 Then
begin
VpfErro := '354';
ExecutaComandoSql(Aux,' alter table CadNatureza ' +
' add C_CST_PAD char(3) null ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 354' );
end;
if VpaNumAtualizacao < 355 Then
begin
VpfErro := '355';
ExecutaComandoSql(Aux,' alter table CFG_GERAL ' +
' add C_VER_DAT char(3) null ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 355' );
end;
if VpaNumAtualizacao < 356 Then
begin
VpfErro := '356';
ExecutaComandoSql(Aux,' alter table CFG_SERVICOS ' +
' add C_VAL_ORC char(1) null ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 356' );
end;
if VpaNumAtualizacao < 357 Then
begin
VpfErro := '357';
ExecutaComandoSql(Aux,' create table MOVATENDIMENTOLABOS ' + // MOVATENDIMENTOLABOS
' ( ' +
' I_EMP_FIL integer not null, ' +
' I_COD_ORS integer not null, ' +
' I_SEQ_MOV integer not null, ' +
' I_COD_USU integer null, ' +
' H_HOR_INI time null, ' +
' H_HOR_FIM time null, ' +
' D_DAT_TRA date null, ' +
' D_ULT_ALT date null, ' +
' primary key (I_EMP_FIL, I_COD_ORS, I_SEQ_MOV) ' +
' ); ' +
' comment on table MOVATENDIMENTOLABOS is ''MOVATENDIMENTOLABOS''; ' +
' comment on column MOVATENDIMENTOLABOS.I_EMP_FIL is ''EMPRESA FILIAL''; ' +
' comment on column MOVATENDIMENTOLABOS.I_COD_ORS is ''CODIGO DA ORDEM DE SERVICO''; ' +
' comment on column MOVATENDIMENTOLABOS.I_SEQ_MOV is ''SEQUENCIAL DA TABELA''; ' +
' comment on column MOVATENDIMENTOLABOS.I_COD_USU is ''CODIGO DO USUARIO (TCNICO)''; ' +
' comment on column MOVATENDIMENTOLABOS.H_HOR_INI is ''HORA DO INICIO DO TRABALHO''; ' +
' comment on column MOVATENDIMENTOLABOS.H_HOR_FIM is ''HORA DO FINAL DO TRABALHO''; ' +
' comment on column MOVATENDIMENTOLABOS.D_DAT_TRA is ''DATA DO TRABALHO''; ' +
' comment on column MOVATENDIMENTOLABOS.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''; ' +
' alter table MOVATENDIMENTOLABOS ' +
' add foreign key FK_MOVATEND_REF_11_CADORDEM (I_EMP_FIL, I_COD_ORS) ' +
' references CADORDEMSERVICO (I_EMP_FIL, I_COD_ORS) on update restrict on delete restrict; ' +
' create unique index MOVATENDIMENTOLABOS_PK on MOVATENDIMENTOLABOS (I_EMP_FIL asc, I_COD_ORS asc, I_SEQ_MOV asc); ' +
' create index Ref_11_FK on MOVATENDIMENTOLABOS (I_EMP_FIL asc, I_COD_ORS asc); ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 357');
end;
if VpaNumAtualizacao < 358 Then //MOVATENDIMENTOCAMPOOS
begin
VpfErro := '358';
ExecutaComandoSql(Aux,' create table MOVATENDIMENTOCAMPOOS ' +
' ( ' +
' I_EMP_FIL integer not null, ' +
' I_COD_ORS integer not null, ' +
' I_SEQ_MOV integer not null, ' +
' I_COD_USU integer null, ' +
' I_INS_USU integer null, ' +
' I_KME_INI integer null, ' +
' I_KME_FIN integer null, ' +
' I_KME_TOT integer null, ' +
' I_INS_INI integer null, ' +
' I_INS_FIN integer null, ' +
' I_INS_TOT integer null, ' +
' H_HOR_INI time null, ' +
' H_HOR_FIM time null, ' +
' H_INS_INI time null, ' +
' H_INS_FIM time null, ' +
' H_HOR_TOT time null, ' +
' D_DAT_INI date null, ' +
' D_INS_INI date null, ' +
' D_ULT_ALT date null, ' +
' primary key (I_EMP_FIL, I_COD_ORS, I_SEQ_MOV) ' +
' ); ' +
' comment on table MOVATENDIMENTOCAMPOOS is ''MOVATENDIMENTOCAMPOOS''; ' +
' comment on column MOVATENDIMENTOCAMPOOS.I_EMP_FIL is ''EMPRESA FILIAL''; ' +
' comment on column MOVATENDIMENTOCAMPOOS.I_COD_ORS is ''CODIGO DA ORDEM DE SERVICO''; ' +
' comment on column MOVATENDIMENTOCAMPOOS.I_SEQ_MOV is ''SEQUENCIAL DA TABELA''; ' +
' comment on column MOVATENDIMENTOCAMPOOS.I_COD_USU is ''CODIGO DO USUARIO (TECNICO)''; ' +
' comment on column MOVATENDIMENTOCAMPOOS.D_DAT_INI is ''DATA DO INICIO DO TRABALHO''; ' +
' comment on column MOVATENDIMENTOCAMPOOS.H_HOR_INI is ''HOTA DE INICIO DO TRABALHO''; ' +
' comment on column MOVATENDIMENTOCAMPOOS.H_HOR_FIM is ''HOTA DO FIM DO TRABALHO''; ' +
' comment on column MOVATENDIMENTOCAMPOOS.I_KME_INI is ''KILOMETRAGEM INICIAL''; ' +
' comment on column MOVATENDIMENTOCAMPOOS.I_KME_FIN is ''KILOMETRAGEM FINAL''; ' +
' comment on column MOVATENDIMENTOCAMPOOS.I_KME_TOT is ''KILOMETRAGEM TOTAL''; ' +
' comment on column MOVATENDIMENTOCAMPOOS.D_ULT_ALT is ''DATA DA ULTIMA ALTERACAO''; ' +
' comment on column MOVATENDIMENTOCAMPOOS.I_INS_USU is ''CODIFGO DO TECNICO DA DEVOLUCAO''; ' +
' comment on column MOVATENDIMENTOCAMPOOS.D_INS_INI is ''DATA DA DEVOLUCAO''; ' +
' comment on column MOVATENDIMENTOCAMPOOS.H_INS_INI is ''HORA DE INICIO DA DEVOLUCAO''; ' +
' comment on column MOVATENDIMENTOCAMPOOS.H_INS_FIM is ''HORA DO FINAL DA DEVOLUCAO''; ' +
' comment on column MOVATENDIMENTOCAMPOOS.H_HOR_TOT is ''HORA TOTAL ATENDIMENTO/ABERTURA''; ' +
' comment on column MOVATENDIMENTOCAMPOOS.I_INS_INI is ''KILOMATRAGEM INCICAL DA DEVOLUCAO''; ' +
' comment on column MOVATENDIMENTOCAMPOOS.I_INS_FIN is ''KILOMETRAGEM FINAL DA DECOLUCAO''; ' +
' comment on column MOVATENDIMENTOCAMPOOS.I_INS_TOT is ''KILOMETRAGEM TOTAL DA DEVOLUCAO''; ' +
' alter table MOVATENDIMENTOCAMPOOS ' +
' add foreign key FK_MOVATEND_REF_18_CADORDEM (I_EMP_FIL, I_COD_ORS) ' +
' references CADORDEMSERVICO (I_EMP_FIL, I_COD_ORS) on update restrict on delete restrict; ' +
' create unique index MOVATENDIMENTOCAMPOOS_PK on MOVATENDIMENTOCAMPOOS (I_EMP_FIL asc, I_COD_ORS asc, I_SEQ_MOV asc); ' +
' create index Ref_18_FK on MOVATENDIMENTOCAMPOOS (I_EMP_FIL asc, I_COD_ORS asc); ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 358' );
end;
if VpaNumAtualizacao < 359 Then
begin
VpfErro := '359';
ExecutaComandoSql(Aux,' alter table CadNatureza ' +
' add C_SOM_IPI char(1) null ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 359' );
end;
if VpaNumAtualizacao < 360 Then
begin
VpfErro := '360';
ExecutaComandoSql(Aux,' alter table CadNatureza ' +
' add C_ICM_EST char(1) null; ' +
' update cadnatureza set C_ICM_EST = ''N''; ' +
' update cadnatureza set C_SOM_IPI = ''N''; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 360' );
end;
if VpaNumAtualizacao < 361 Then
begin
VpfErro := '361';
ExecutaComandoSql(Aux,' alter table MOVATENDIMENTOCAMPOOS ' +
' modify H_HOR_INI timestamp; ' +
' alter table MOVATENDIMENTOCAMPOOS ' +
' modify H_HOR_FIM timestamp; ' +
' alter table MOVATENDIMENTOCAMPOOS ' +
' modify H_INS_INI timestamp; ' +
' alter table MOVATENDIMENTOCAMPOOS ' +
' modify H_INS_FIM timestamp; ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 361' );
end;
if VpaNumAtualizacao < 362 Then
begin
VpfErro := '362';
ExecutaComandoSql(Aux,' alter table MovOrcamentos ' +
' add C_IMP_VAL char(1) null; ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 362' );
end;
if VpaNumAtualizacao < 363 Then
begin
VpfErro := '363';
ExecutaComandoSql(Aux,'create table CFG_FACTORI ' + //CFG_FACTORI
' ( ' +
' C_JUR_DIA char(1) NULL,' +
' C_SEN_LIB char(15) NULL ' +
' );' +
' comment on table CFG_FACTORI is ''CONFIGURACOES FACTORING '';' +
' comment on column CFG_FACTORI.C_JUR_DIA is ''CALCULA JURO DIARIO'';' +
' comment on column CFG_FACTORI.C_SEN_LIB is ''SENHA DE LIBERACAO PARA ALTERAR VALOR'';' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 363' );
end;
if VpaNumAtualizacao < 364 Then
begin
VpfErro := '364';
ExecutaComandoSql(Aux,' alter table CadEmitentes ' +
' add C_CID_EMI char(25) null, '+
' add C_EST_EMI char(2) null; ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 364' );
end;
if VpaNumAtualizacao < 365 Then
begin
VpfErro := '365';
ExecutaComandoSql(Aux,' alter table CadEmitentes ' +
' add I_COD_CID integer null; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 365' );
end;
if VpaNumAtualizacao < 366 Then
begin
VpfErro := '366';
ExecutaComandoSql(Aux,' alter table CadOrdemServico ' +
' add C_ACE_EMP varchar(60) null; ' +
' alter table CadOrdemServico ' +
' modify c_cha_tec char(8) null; ' +
' alter table MOVEQUIPAMENTOOS ' +
' modify C_ORC_EQU char(10) null; ' +
' alter table MOVEQUIPAMENTOOS ' +
' delete C_GAR_EQU; ' +
' update CadOrdemServico ' +
' set c_cha_tec = ''Balcao''; ' +
' update MOVEQUIPAMENTOOS ' +
' set c_orc_equ = ''Orcamento''; ' +
' Alter table MovTerceiroOS ' +
' add C_ACE_TER varchar(60) null, ' +
' add I_COD_TRA integer null, ' +
' add C_MOD_GRA varchar(60) null, ' +
' add C_LAU_GAR varchar(30) null; ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 366' );
end;
if VpaNumAtualizacao < 367 Then
begin
VpfErro := '367';
ExecutaComandoSql(Aux,' Alter table CadUsuarios ' +
' add C_CPF_USU char(14) null, ' +
' add C_FON_USU char(20) null, ' +
' add C_MAI_USU varchar(60) null, ' +
' add C_RAM_USU integer null; ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 367' );
end;
if VpaNumAtualizacao < 368 Then
begin
VpfErro := '368';
ExecutaComandoSql(Aux,' Alter table CAD_DOC ' +
' add C_MAT_PER char(1) null; ' +
' Update CAD_DOC ' +
' set C_MAT_PER = ''M''; ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 368' );
end;
if VpaNumAtualizacao < 369 Then
begin
VpfErro := '369';
ExecutaComandoSql(Aux,' create table TEMPORARIADOC (' +
' I_EMP_FIL integer null, ' +
' I_LAN_REC integer null, ' +
' I_NRO_PAR integer null); ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 369' );
end;
if VpaNumAtualizacao < 370 Then
begin
VpfErro := '370';
ExecutaComandoSql(Aux,' alter table TEMPORARIADOC ' +
' add C_EXT_VAL varchar(100) null; ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 370' );
end;
if VpaNumAtualizacao < 371 Then
begin
VpfErro := '371';
ExecutaComandoSql(Aux,' alter table CFG_GERAL ' +
' add C_ALI_REL char(10) null; ' +
' update cfg_geral set c_ali_rel = ''SigRel'' ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 371' );
end;
if VpaNumAtualizacao < 372 Then
begin
VpfErro := '372';
ExecutaComandoSql(Aux,' alter table CadOrdemServico ' +
' add I_COD_EQU integer null, ' +
' add I_COD_MAR integer null, ' +
' add I_COD_MOD integer null, ' +
' add C_VOL_ENT char(10) null, ' +
' add C_ORC_EQU char(25) null, ' +
' add C_NRO_NOT char(40) null, ' +
' add C_DEF_APR varchar(250) null, ' +
' add C_NRO_SER char(20) null, ' +
' add C_ACE_EQU varchar(100) null ' );
ExecutaComandoSql(Aux,
' comment on column CadOrdemServico.I_COD_EQU is ''CODIGO DA EQUIPAMENTO''; ' +
' comment on column CadOrdemServico.I_COD_MAR is ''CODIGO DA MARCA''; ' +
' comment on column CadOrdemServico.I_COD_MOD is ''CODIGO DO MODELO''; ' +
' comment on column CadOrdemServico.C_ACE_EQU is ''ACESSORIOS DO EQUIPAMENTO''; ' +
' comment on column CadOrdemServico.C_ORC_EQU is ''FAZER ORCAMENTO S/N''; ' +
' comment on column CadOrdemServico.C_DEF_APR is ''DEFEITO APRESENTADO''; ' +
' comment on column CadOrdemServico.C_NRO_NOT is ''NUMERO DA NOTA CASO GARANTIA''; ' +
' comment on column CadOrdemServico.C_NRO_SER is ''NUMERO DE SERIE DO EQUIPAMENTO''; ' +
' comment on column CadOrdemServico.C_VOL_ENT is ''VOLTAGEM DO EQUIPAMENTO''; ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 372' );
end;
if VpaNumAtualizacao < 373 Then
begin
VpfErro := '373';
ExecutaComandoSql(Aux,
' alter table CadOrdemServico ' +
' add foreign key FK_CADORDEM_REF_CADMODEL (I_COD_MOD) ' +
' references CADMODELO (I_COD_MOD) on update restrict on delete restrict; ' +
' alter table CadOrdemServico ' +
' add foreign key FK_CADORDEM_REF_CADMARCA (I_COD_MAR) ' +
' references CADMARCAS (I_COD_MAR) on update restrict on delete restrict; ' +
' alter table CadOrdemServico ' +
' add foreign key FK_CADORDEM_REF_CADEQUIP (I_COD_EQU) ' +
' references CADEQUIPAMENTOS (I_COD_EQU) on update restrict on delete restrict; ' );
ExecutaComandoSql(Aux,
' create index Ref_Modelo_FK on CadOrdemServico (I_COD_MOD asc); ' +
' create index Ref_Marca on CadOrdemServico (I_COD_MAR asc); ' +
' create index Ref_Equi_FK on CadOrdemServico (I_COD_EQU asc); ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 373' );
end;
if VpaNumAtualizacao < 374 Then
begin
VpfErro := '374';
ExecutaComandoSql(Aux,
' update cadordemservico cad ' +
' set I_COD_EQU = (select max( i_cod_equ) from MOVEQUIPAMENTOOS where i_cod_ors = cad.i_cod_ors and i_emp_fil = cad.i_emp_fil), ' +
' I_COD_MAR = (select max( i_cod_mar) from MOVEQUIPAMENTOOS where i_cod_ors = cad.i_cod_ors and i_emp_fil = cad.i_emp_fil), ' +
' I_COD_MOD = (select max(i_cod_mod) from MOVEQUIPAMENTOOS where i_cod_ors = cad.i_cod_ors and i_emp_fil = cad.i_emp_fil), ' +
' C_VOL_ENT = (select max(c_vol_ent) from MOVEQUIPAMENTOOS where i_cod_ors = cad.i_cod_ors and i_emp_fil = cad.i_emp_fil), ' +
' C_ORC_EQU = (select max(c_orc_equ) from MOVEQUIPAMENTOOS where i_cod_ors = cad.i_cod_ors and i_emp_fil = cad.i_emp_fil), ' +
' C_NRO_NOT = (select max(c_nro_not) from MOVEQUIPAMENTOOS where i_cod_ors = cad.i_cod_ors and i_emp_fil = cad.i_emp_fil), ' +
' C_DEF_APR = (select max(c_def_apr) from MOVEQUIPAMENTOOS where i_cod_ors = cad.i_cod_ors and i_emp_fil = cad.i_emp_fil), ' +
' C_NRO_SER = (select max(c_nro_ser) from MOVEQUIPAMENTOOS where i_cod_ors = cad.i_cod_ors and i_emp_fil = cad.i_emp_fil), ' +
' C_ACE_EQU = (select max(c_ace_equ) from MOVEQUIPAMENTOOS where i_cod_ors = cad.i_cod_ors and i_emp_fil = cad.i_emp_fil); ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 374' );
end;
if VpaNumAtualizacao < 375 Then
begin
VpfErro := '375';
ExecutaComandoSql(Aux,' Drop table MOVEQUIPAMENTOOS ' );
ExecutaComandoSql(Aux,' Drop table CadCor ' );
ExecutaComandoSql(Aux,' Drop table CadTipo ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 375' );
end;
if VpaNumAtualizacao < 376 Then
begin
VpfErro := '376';
ExecutaComandoSql(Aux,' alter table movterceiroos ' +
' add C_NRO_SER char(20) null, ' +
' add I_COD_EQU integer null, ' +
' add I_COD_MAR integer null, ' +
' add I_COD_MOD integer null; ' );
ExecutaComandoSql(Aux,
' alter table movterceiroos ' +
' add foreign key FK_CADMODEL (I_COD_MOD) ' +
' references CADMODELO (I_COD_MOD) on update restrict on delete restrict; ' +
' alter table movterceiroos ' +
' add foreign key FK_CADMARCA (I_COD_MAR) ' +
' references CADMARCAS (I_COD_MAR) on update restrict on delete restrict; ' +
' alter table movterceiroos ' +
' add foreign key FK_CADEQUIP (I_COD_EQU) ' +
' references CADEQUIPAMENTOS (I_COD_EQU) on update restrict on delete restrict; ' );
ExecutaComandoSql(Aux,
' create index Ref_123_Modelo_FK on movterceiroos (I_COD_MOD asc); ' +
' create index Ref_124_Marca_FK on movterceiroos (I_COD_MAR asc); ' +
' create index Ref_125_Equi_FK on movterceiroos (I_COD_EQU asc); ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 376' );
end;
if VpaNumAtualizacao < 377 Then
begin
VpfErro := '377';
ExecutaComandoSql(Aux,' update movterceiroos mov ' +
' set i_cod_equ = ( select max(i_cod_equ) from cadordemservico cad where cad.i_cod_ors = mov.i_cod_ors and cad.i_emp_fil = mov.I_emp_fil), ' +
' i_cod_mar = ( select max(i_cod_equ) from cadordemservico cad where cad.i_cod_ors = mov.i_cod_ors and cad.i_emp_fil = mov.I_emp_fil), ' +
' i_cod_mod = ( select max(i_cod_equ) from cadordemservico cad where cad.i_cod_ors = mov.i_cod_ors and cad.i_emp_fil = mov.I_emp_fil), ' +
' c_nro_ser = ( select max(c_nro_ser) from cadordemservico cad where cad.i_cod_ors = mov.i_cod_ors and cad.i_emp_fil = mov.I_emp_fil); ' );
ExecutaComandoSql(Aux,' alter table cadordemservico ' +
' modify T_HOR_PRE timestamp; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 377' );
end;
if VpaNumAtualizacao < 378 Then
begin
VpfErro := '378';
ExecutaComandoSql(Aux,' update CadOrdemServico ' +
' set C_ORC_EQU = ''Garantia de Servico ''' +
' where C_ORC_EQU = ''Garantia'';');
ExecutaComandoSql(Aux,' alter table cfg_servicos ' +
' add C_INA_SER char(1) null; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 378' );
end;
if VpaNumAtualizacao < 379 Then
begin
VpfErro := '379';
ExecutaComandoSql(Aux,' alter table Cad_Plano_conta ' +
' add C_NIL_001 char(5) null, ' +
' add C_NIL_002 char(5) null, ' +
' add C_NIL_003 char(5) null, ' +
' add C_NIL_004 char(5) null, ' +
' add C_NIL_005 char(5) null, ' +
' add C_NIL_006 char(5) null, ' +
' add C_NIL_007 char(5) null, ' +
' add I_COD_RED integer null ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 379' );
end;
if VpaNumAtualizacao < 380 Then
begin
VpfErro := '380';
AtualizaPlanoConta;
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 380' );
end;
if VpaNumAtualizacao < 381 Then
begin
VpfErro := '381';
ExecutaComandoSql(Aux,' drop index CadOrdemServico_fk_cadtipo_857;' );
ExecutaComandoSql(Aux,' create index CadOrdemServico_fk_cadtipo on CADOrdemServico (I_COD_ENT asc); ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 381' );
end;
if VpaNumAtualizacao < 382 Then
begin
VpfErro := '382';
ExecutaComandoSql(Aux,' alter table Cfg_geral ' +
' add I_DEC_UNI integer null ' );
ExecutaComandoSql(Aux,' update Cfg_geral ' +
' set I_DEC_UNI = 2 ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 382' );
end;
if VpaNumAtualizacao < 383 Then
begin
VpfErro := '383';
ExecutaComandoSql(Aux,' alter table Cfg_fiscal ' +
' add C_DEV_NOT varchar(100) null ' );
ExecutaComandoSql(Aux,' update Cfg_fiscal ' +
' set C_DEV_NOT = ''Devolução referente a nota fiscal nº ''' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 383' );
end;
if VpaNumAtualizacao < 384 Then
begin
VpfErro := '384';
ExecutaComandoSql(Aux,' alter table MOVFACTORI ' +
' add D_DAT_CAD date null ' );
ExecutaComandoSql(Aux,' update MOVFACTORI ' +
' set D_DAT_CAD = D_EMI_DOC' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 384' );
end;
if VpaNumAtualizacao < 385 Then
begin
VpfErro := '385';
ExecutaComandoSql(Aux,' alter table MOVATENDIMENTOLABOS ' +
' modify H_HOR_INI TimeStamp null, ' +
' modify H_HOR_FIM TimeStamp null ' );
ExecutaComandoSql(Aux,' alter table CADORDEMSERVICO ' +
' add H_HOR_ABE TimeStamp null ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 385' );
end;
if VpaNumAtualizacao < 386 Then
begin
VpfErro := '386';
ExecutaComandoSql(Aux,' alter table CadOrdemServico ' +
' add I_SEQ_NOT integer null, ' +
' add I_NRO_NOT integer null ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 386' );
end;
if VpaNumAtualizacao < 387 Then
begin
VpfErro := '387';
ExecutaComandoSql(Aux,' alter table CadNotaFiscais ' +
' add L_NRO_ORS Long VarChar null ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 387' );
end;
if VpaNumAtualizacao < 388 Then
begin
VpfErro := '388';
ExecutaComandoSql(Aux,' alter table cfg_servicos ' +
' add C_RES_PRO char(1) null ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 388' );
end;
if VpaNumAtualizacao < 389 Then
begin
VpfErro := '389';
ExecutaComandoSql(Aux,' alter table cfg_servicos ' +
' add C_BAI_RES char(1) null ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 389' );
end;
if VpaNumAtualizacao < 390 Then
begin
VpfErro := '390';
ExecutaComandoSql(Aux,' alter table Cad_Plano_conta ' +
' modify C_NIL_001 char(20) null, ' +
' modify C_NIL_002 char(20) null, ' +
' modify C_NIL_003 char(20) null, ' +
' modify C_NIL_004 char(20) null, ' +
' modify C_NIL_005 char(20) null, ' +
' modify C_NIL_006 char(20) null, ' +
' modify C_NIL_007 char(20) null ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 390' );
end;
if VpaNumAtualizacao < 391 Then
begin
VpfErro := '391';
AtualizaPlanoConta;
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 391' );
end;
if VpaNumAtualizacao < 392 Then
begin
VpfErro := '392';
ExecutaComandoSql(Aux,' alter table cfg_servicos ' +
' add C_NRO_EQU char(1) null; ' +
' alter table movordemservico ' +
' add C_RES_PRO char(1) null ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 392' );
end;
if VpaNumAtualizacao < 393 Then
begin
VpfErro := '393';
ExecutaComandoSql(Aux,' update movordemservico ' +
' set C_RES_PRO = ''N'' ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 393' );
end;
if VpaNumAtualizacao < 394 Then
begin
VpfErro := '394';
ExecutaComandoSql(Aux,' alter table CadOrdemServico ' +
' add C_RES_PRO char(1) null '+
' update CadOrdemservico ' +
' set C_RES_PRO = ''N'' ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 394' );
end;
except
result := false;
FAtualizaSistema.MostraErro(Aux.sql,'cfg_geral');
Erro(VpfErro + ' - OCORREU UM ERRO DURANTE A ATUALIZAÇAO DO SISTEMA inSIG.');
exit;
end;
until result;
end;
end.
|
unit MD5.FileList;
// Что должен уметь FileList
// 1.Хранить в себе список файлов вместе со структурой каталогов
// (а также все атрибуты файла: размер, атрибуты, время создания, доступа и последней записи)
// 2.Уметь записывать себя в файл контрольных сумм (обычного и расширенного формата)
// 3.Уметь читать себя из файла контрольных сумм (обычного и расширенного формата)
// 4.Уметь сравнивать себя с другими списками (для выявления "новых" и "отсутствующих" файлов)
// 5.Уметь сравнивать себя с другими списками (по имени, контрольным суммам, атрибутам, чтобы
// выявлять факты переименования/перемещения файлов)
// 6.
interface
//uses
// System.SysUtils,
// System.Classes,
// Windows;
//
//const
// ALL_FILES_MASK = '*'; // NOT *.* !!!
// EXTENDED_PATH_PREFIX = '\\?\';
// SKIP_FOLDER_NAME_1 = '.';
// SKIP_FOLDER_NAME_2 = '..';
// // for MatchMask
// MASK_CHAR_ZERO_OF_MANY = '*';
// MASK_CHAR_ANY = '?';
// MASK_END_OF_STRING = #0;
//
//type
// TFileListInfo = class
// Size: UInt64;
// Attributes: Cardinal;
// CreationTime: TFileTime;
// LastAccessTime: TFileTime;
// LastWriteTime: TFileTime;
// //
// FolderIndex: Integer;
// end;
//
// TFileList = class
// private
// FFolders: TStringList;
// FFiles: TStringList;
// //
// function AddRecord: Integer;
// procedure ScanFolders(const BasePath: String);
// public
// constructor Create;
// destructor Destroy; override;
// /// <summary>
// /// Scan files, starts from BasePath.
// /// </summary>
// procedure ScanFiles(const BasePath: String; Recursive: Boolean);
// /// <summary>
// /// Add file information into list. Check file exist, and get it size,
// /// attributes and time.
// /// </summary>
// /// <param name="FileName">
// /// File name to add to list.
// /// </param>
// /// <returns>
// /// Return index, if file has been added, otherwise -1 (file or path not exist)
// /// </returns>
// function AddFile(const FileName: String): Integer;
// /// <summary>
// /// Add folder information.
// /// </summary>
// /// <returns>
// /// Return folder index.
// /// </returns>
// function AddFolder(const FileFolder: String): Integer;
// end;
//
//implementation
//
//{ TFileList }
//
//function TFileList.AddFile(const FileName: String): Integer;
//var
// WS: TWin32FindDataW;
// H: THandle;
// Index: Integer;
//begin
// H := FindFirstFileW(PChar( EXTENDED_PATH_PREFIX + FileName ), WS);
// if H <> INVALID_HANDLE_VALUE then
// begin
// Index := AddRecord;
// FFiles[Index].Size := MakeUInt64(WS.nFileSizeLow, WS.nFileSizeHigh);
// FFiles[Index].Attributes := WS.dwFileAttributes;
// FFiles[Index].CreationTime := WS.ftCreationTime;
// FFiles[Index].LastAccessTime := WS.ftLastAccessTime;
// FFiles[Index].LastWriteTime := WS.ftLastWriteTime;
// FFiles[Index].FolderIndex := AddFolder(ExtractFilePath(FileName));
// FFiles[Index].FileName := ExtractFileName(FileName);
// FindClose(H);
// Result := Index;
// end else
// begin
// Result := -1;
// end;
//end;
//
//function TFileList.AddFolder(const FileFolder: String): Integer;
//var
// Index: Integer;
//begin
// if FFolders.Find(FileFolder, Index) then Exit(Index);
// Result := FFolders.Add(FileFolder);
//end;
//
//function TFileList.AddRecord: Integer;
//begin
// if FFilesIndex >= Length(FFiles) then
// begin
// SetLength(FFiles, Length(FFiles) + 100);
// end;
// Result := FFilesIndex;
// Inc(FFilesIndex);
//end;
//
//constructor TFileList.Create;
//begin
// FFolders := TStringList.Create;
// FFolders.Sorted := TRUE;
// FFolders.Duplicates := dupIgnore;
// FFolders.OwnsObjects := TRUE;
// //
// FFiles := TStringList.Create;
// FFiles.Sorted := TRUE;
// FFiles.Duplicates := dupAccept;
// FFiles.OwnsObjects := TRUE;
//end;
//
//destructor TFileList.Destroy;
//begin
// FFolders.Free;
// FFiles.Free;
//end;
//
//procedure TFileList.ScanFiles(const BasePath: String; Recursive: Boolean);
//begin
//
//end;
IMPLEMENTATION
end.
|
{ ****************************************************************************** }
{ * ZDB 2.0 Core, create by.qq600585 * }
{ * https://zpascal.net * }
{ * https://github.com/PassByYou888/zAI * }
{ * https://github.com/PassByYou888/ZServer4D * }
{ * https://github.com/PassByYou888/PascalString * }
{ * https://github.com/PassByYou888/zRasterization * }
{ * https://github.com/PassByYou888/CoreCipher * }
{ * https://github.com/PassByYou888/zSound * }
{ * https://github.com/PassByYou888/zChinese * }
{ * https://github.com/PassByYou888/zExpression * }
{ * https://github.com/PassByYou888/zGameWare * }
{ * https://github.com/PassByYou888/zAnalysis * }
{ * https://github.com/PassByYou888/FFMPEG-Header * }
{ * https://github.com/PassByYou888/zTranslate * }
{ * https://github.com/PassByYou888/InfiniteIoT * }
{ * https://github.com/PassByYou888/FastMD5 * }
{ ****************************************************************************** }
unit ZDB2_Core;
{$INCLUDE zDefine.inc}
interface
uses CoreClasses,
{$IFDEF FPC}
FPCGenericStructlist,
{$ENDIF FPC}
PascalStrings, UnicodeMixedLib,
MemoryStream64,
DoStatusIO;
const
C_ZDB2_FileHead = $90909090;
C_ZDB2_MinBlockSize = $40;
type
TZDB2_Core_Space = class;
{$IFDEF ZDB2_Core_Used_Mem64}
TZDB2_Mem = TMem64;
{$ELSE ZDB2_Core_Used_Mem64}
TZDB2_Mem = TMemoryStream64;
{$ENDIF ZDB2_Core_Used_Mem64}
TZDB2_Core_BlockData = packed record
Position: Int64;
Size: Word;
UsedSpace: Word;
ID: Integer;
Prev, Next: Integer;
end;
PZDB2_Core_BlockData = ^TZDB2_Core_BlockData;
TZDB2_Core_BlockCache = record
Mem: TZDB2_Mem;
FlushThisCacheToFile: Boolean;
end;
TZDB2_Core_CustomFileHeader = array [0 .. $FF - 1] of Byte;
PZDB2_Core_CustomFileHeader = ^TZDB2_Core_CustomFileHeader;
TZDB2_Core_BlockPtrList = {$IFDEF FPC}specialize {$ENDIF FPC} TGenericsList<PZDB2_Core_BlockData>;
TZDB2_Core_BlockHnd = array of Integer;
TZDB2_Core_PhysicsBlock = array of TZDB2_Core_BlockData;
TZDB2_Core_PhysicsBlockWriteCache = array of TZDB2_Core_BlockCache;
TZDB2_Core_OnProgress = procedure(Total_, current_: Integer) of object;
TZDB2_Core_OnNoSpace = procedure(Siz_: Int64; var retry: Boolean) of object;
{ stmBigData: DB Size > 10G, < 130TB, block number < 1000*10000, no cache }
{ stmNormal: DB size > 1G, < 10G, block number < 100*10000, open write cache }
{ stmFast: DB size > 100M, < 1G, block number < 10*10000, open read/write cache }
TZDB2_Core_SpaceMode = (stmBigData, stmNormal, stmFast);
TZDB2_Core_SpaceState = record
Physics: Int64;
FreeSpace: Int64;
Cache: Int64;
ReadNum: Int64;
ReadSize: Int64;
WriteNum: Int64;
WriteSize: Int64;
end;
PZDB2_Core_SpaceState = ^TZDB2_Core_SpaceState;
TZDB2_Core_Space = class
private
FAutoCloseIOHnd: Boolean;
FAutoFreeIOHnd: Boolean;
FSpace_IOHnd: PIOHnd;
FCustomFileHeader: TZDB2_Core_CustomFileHeader;
FFreeSpaceIndexProbe: Integer;
FPhyBlockNum: Integer;
FPhyBlock: TZDB2_Core_PhysicsBlock;
FMaxCacheMemory: Int64;
FUsedReadCache: Boolean;
FUsedWriteCache: Boolean;
FPhyBlockWriteCache: TZDB2_Core_PhysicsBlockWriteCache;
FMode: TZDB2_Core_SpaceMode;
FState: TZDB2_Core_SpaceState;
FOnProgress: TZDB2_Core_OnProgress;
FOnNoSpace: TZDB2_Core_OnNoSpace;
{ cache }
function ReadCacheBlock(buff: Pointer; ID: Integer): Boolean;
function WriteCacheBlock(buff: Pointer; siz: Integer; ID: Integer; FlushThisCache_: Boolean): Boolean;
{ Calculate storage size of space table }
function GetTableSize: Int64; overload;
function GetTableSize(PhyBlockNum_: Integer): Int64; overload;
public
constructor Create(IOHnd_: PIOHnd);
destructor Destroy; override;
property AutoCloseIOHnd: Boolean read FAutoCloseIOHnd write FAutoCloseIOHnd;
property AutoFreeIOHnd: Boolean read FAutoFreeIOHnd write FAutoFreeIOHnd;
property Space_IOHnd: PIOHnd read FSpace_IOHnd write FSpace_IOHnd;
function GetCustomFileHeader: PZDB2_Core_CustomFileHeader;
property CustomFileHeader: PZDB2_Core_CustomFileHeader read GetCustomFileHeader;
property PhyBlockNum: Integer read FPhyBlockNum;
property PhyBlock: TZDB2_Core_PhysicsBlock read FPhyBlock;
property MaxCacheMemory: Int64 read FMaxCacheMemory write FMaxCacheMemory;
property UsedReadCache: Boolean read FUsedReadCache write FUsedReadCache;
property UsedWriteCache: Boolean read FUsedWriteCache write FUsedWriteCache;
{ stmBigData: DB Size > 10G, < 130TB, block number < 1000*10000, no cache }
{ stmNormal: DB size > 1G, < 10G, block number < 100*10000, open write cache }
{ stmFast: DB size > 100M, < 1G, block number < 10*10000, open read/write cache }
procedure SetMode(const Value: TZDB2_Core_SpaceMode);
property Mode: TZDB2_Core_SpaceMode read FMode write SetMode;
{ state }
function GetState: PZDB2_Core_SpaceState;
property State: PZDB2_Core_SpaceState read GetState;
{ event }
property OnProgress: TZDB2_Core_OnProgress read FOnProgress write FOnProgress;
property OnNoSpace: TZDB2_Core_OnNoSpace read FOnNoSpace write FOnNoSpace;
{ error }
procedure ErrorInfo(const Text_: SystemString);
{ cache }
procedure DeleteCache(ID: Integer);
procedure ClearCache;
procedure FlushCache;
{ Write space table to physical IO }
procedure WriteTable();
{ Write space table to physical IO, and clear write back buffer + preread buffer + flush cache }
procedure Save();
{ Read space table + scan fragment space }
procedure Open();
{ Scanning space state }
procedure ScanSpace;
{ Prepare data structure space }
procedure PreparePhyBlock(PhyBlockNum_: Int64);
{ build fixed size storage space }
procedure BuildSpace(PhySpaceSize: Int64; BlockSize_: Word);
{ append of fixed size storage space }
procedure AppendSpace(Dest: TZDB2_Core_Space; DestPhySpaceSize: Int64; DestBlockSize_: Word);
{ Optimize storage space seealso to SaveAs }
procedure OptimizeInstance(Dest: TZDB2_Core_Space);
{ Take id as parameter to merge ID into TZDB2_Core_BlockHnd }
function Check(ID_: Integer): Boolean;
function GetSpaceHndID(ID_: Integer): Integer;
function GetSpaceHnd(ID_: Integer): TZDB2_Core_BlockHnd;
{ Write a buffer to automatically fill the space block }
function CheckWriteSpace(Siz_: Int64): Boolean; overload;
function CheckWriteSpace(Siz_: Int64; Space_: TZDB2_Core_BlockPtrList): Boolean; overload;
function WriteData(buff: TZDB2_Mem; var SpaceHnd: TZDB2_Core_BlockHnd): Boolean; overload;
function WriteData(buff: TZDB2_Mem; var ID: Integer): Boolean; overload;
{ read the fragment space and merge the data to buff }
function ReadData(buff: TZDB2_Mem; SpaceHnd: TZDB2_Core_BlockHnd): Boolean; overload;
function ReadData(buff: TZDB2_Mem; ID: Integer): Boolean; overload;
{ remove the fragments. This operation will not reconstruct freespace. our need call ScanSpace to rebuild freespace struct. }
function RemoveData(SpaceHnd: TZDB2_Core_BlockHnd; SafeClean_: Boolean): Boolean; overload;
function RemoveData(ID: Integer; SafeClean_: Boolean): Boolean; overload;
{ data size }
function GetDataSize(SpaceHnd: TZDB2_Core_BlockHnd): Int64; overload;
function GetDataSize(ID: Integer): Int64; overload;
{ physics size }
function GetDataPhysics(SpaceHnd: TZDB2_Core_BlockHnd): Int64; overload;
function GetDataPhysics(ID: Integer): Int64; overload;
class procedure Test();
end;
implementation
var
V_NULLData: array [Word] of Byte;
function TZDB2_Core_Space.ReadCacheBlock(buff: Pointer; ID: Integer): Boolean;
var
p: PZDB2_Core_BlockData;
begin
Result := False;
p := @FPhyBlock[ID];
with FPhyBlockWriteCache[p^.ID] do
if (FUsedReadCache) and (p^.UsedSpace > 0) and (Mem <> nil) then
begin
Mem.Position := 0;
Mem.ReadPtr(buff, p^.UsedSpace);
Mem.Position := 0;
Result := True;
end;
end;
function TZDB2_Core_Space.WriteCacheBlock(buff: Pointer; siz: Integer; ID: Integer; FlushThisCache_: Boolean): Boolean;
var
p: PZDB2_Core_BlockData;
begin
Result := False;
if not FUsedWriteCache then
exit;
p := @FPhyBlock[ID];
with FPhyBlockWriteCache[ID] do
begin
if Mem = nil then
begin
Mem := TZDB2_Mem.Create;
Mem.Size := p^.Size;
FillPtr(Mem.Memory, p^.Size, 0);
inc(FState.Cache, p^.Size);
end;
Mem.Position := 0;
Mem.WritePtr(buff, siz);
Mem.Position := 0;
FlushThisCacheToFile := FlushThisCacheToFile or FlushThisCache_;
end;
Result := True;
if FState.Cache > FMaxCacheMemory then
begin
FlushCache();
end;
end;
function TZDB2_Core_Space.GetTableSize: Int64;
begin
Result := GetTableSize(FPhyBlockNum);
end;
function TZDB2_Core_Space.GetTableSize(PhyBlockNum_: Integer): Int64;
begin
Result := 16 + SizeOf(TZDB2_Core_CustomFileHeader) + SizeOf(TZDB2_Core_BlockData) * PhyBlockNum_;
end;
constructor TZDB2_Core_Space.Create(IOHnd_: PIOHnd);
begin
inherited Create;
FAutoCloseIOHnd := False;
FAutoFreeIOHnd := False;
FSpace_IOHnd := IOHnd_;
FillPtr(@FCustomFileHeader, SizeOf(TZDB2_Core_CustomFileHeader), 0);
FFreeSpaceIndexProbe := 0;
FPhyBlockNum := 0;
SetLength(FPhyBlock, 0);
FMaxCacheMemory := 1024 * 1024 * 64;
FUsedReadCache := False;
FUsedWriteCache := True;
SetLength(FPhyBlockWriteCache, 0);
FMode := stmNormal;
FState.Physics := 0;
FState.FreeSpace := 0;
FState.Cache := 0;
FState.ReadNum := 0;
FState.ReadSize := 0;
FState.WriteNum := 0;
FState.WriteSize := 0;
FOnProgress := nil;
FOnNoSpace := nil;
end;
destructor TZDB2_Core_Space.Destroy;
begin
SetLength(FPhyBlock, 0);
ClearCache;
SetLength(FPhyBlockWriteCache, 0);
if FAutoCloseIOHnd then
umlFileClose(FSpace_IOHnd^);
if FAutoFreeIOHnd then
Dispose(FSpace_IOHnd);
inherited Destroy;
end;
function TZDB2_Core_Space.GetCustomFileHeader: PZDB2_Core_CustomFileHeader;
begin
Result := @FCustomFileHeader;
end;
procedure TZDB2_Core_Space.SetMode(const Value: TZDB2_Core_SpaceMode);
begin
FMode := Value;
case FMode of
stmBigData:
begin
FUsedReadCache := False;
FUsedWriteCache := False;
end;
stmNormal:
begin
FUsedReadCache := False;
FUsedWriteCache := True;
end;
stmFast:
begin
FUsedReadCache := True;
FUsedWriteCache := True;
end;
end;
end;
function TZDB2_Core_Space.GetState: PZDB2_Core_SpaceState;
begin
Result := @FState;
end;
procedure TZDB2_Core_Space.ErrorInfo(const Text_: SystemString);
begin
DoStatus('ZDB2 Core failed - ' + Text_);
end;
procedure TZDB2_Core_Space.DeleteCache(ID: Integer);
begin
with FPhyBlockWriteCache[ID] do
begin
if Mem <> nil then
begin
Dec(FState.Cache, Mem.Size);
DisposeObjectAndNil(Mem);
end;
FlushThisCacheToFile := False;
end;
end;
procedure TZDB2_Core_Space.ClearCache;
var
i: Int64;
begin
i := 0;
while i < Length(FPhyBlockWriteCache) do
with FPhyBlockWriteCache[i] do
begin
DisposeObjectAndNil(Mem);
FlushThisCacheToFile := False;
inc(i);
end;
FState.Cache := 0;
end;
procedure TZDB2_Core_Space.FlushCache;
var
i: Integer;
begin
i := 0;
while i < FPhyBlockNum do
begin
with FPhyBlock[i], FPhyBlockWriteCache[i] do
if Mem <> nil then
begin
if FlushThisCacheToFile then
begin
if not umlFileSeek(FSpace_IOHnd^, Position) then
begin
ErrorInfo('FlushCache: umlFileSeek error.');
exit;
end;
if not umlBlockWrite(FSpace_IOHnd^, Mem.Memory^, UsedSpace) then
begin
ErrorInfo('FlushCache: umlBlockWrite error.');
exit;
end;
FlushThisCacheToFile := False;
end;
DisposeObjectAndNil(Mem);
end;
inc(i);
end;
FState.Cache := 0;
end;
procedure TZDB2_Core_Space.WriteTable();
type
THead_ = packed record
head: Cardinal;
major, minor: Word;
num: Integer;
end;
var
h: THead_;
begin
h.head := C_ZDB2_FileHead;
h.major := 1;
h.minor := 2;
h.num := FPhyBlockNum;
if not umlFileSeek(FSpace_IOHnd^, 0) then
begin
ErrorInfo('WriteTable: umlFileSeek error.');
exit;
end;
if not umlBlockWrite(FSpace_IOHnd^, h, 12) then
begin
ErrorInfo('WriteTable: umlBlockWrite h error.');
exit;
end;
if not umlBlockWrite(FSpace_IOHnd^, FCustomFileHeader, SizeOf(TZDB2_Core_CustomFileHeader)) then
begin
ErrorInfo('WriteTable: umlBlockWrite CustomFileHeader error.');
exit;
end;
if FPhyBlockNum > 0 then
if not umlBlockWrite(FSpace_IOHnd^, FPhyBlock[0], SizeOf(TZDB2_Core_BlockData) * FPhyBlockNum) then
begin
ErrorInfo('WriteTable: umlBlockWrite FPhyBlock error.');
exit;
end;
end;
procedure TZDB2_Core_Space.Save;
begin
WriteTable;
FlushCache;
umlFileUpdate(FSpace_IOHnd^);
end;
procedure TZDB2_Core_Space.Open();
type
THead_ = packed record
head: Cardinal;
major, minor: Word;
end;
var
h: THead_;
num: Integer;
begin
umlFileSeek(FSpace_IOHnd^, 0);
umlBlockRead(FSpace_IOHnd^, h, 8);
if h.head <> C_ZDB2_FileHead then
begin
ErrorInfo('Open: header token error.');
exit;
end;
if (h.major = 1) and (h.minor = 2) then
begin
if not umlBlockRead(FSpace_IOHnd^, num, 4) then
begin
ErrorInfo('Open: umlBlockRead num error.');
exit;
end;
if not umlBlockRead(FSpace_IOHnd^, FCustomFileHeader, SizeOf(TZDB2_Core_CustomFileHeader)) then
begin
ErrorInfo('Open: umlBlockRead FCustomFileHeader error.');
exit;
end;
PreparePhyBlock(num);
if FPhyBlockNum > 0 then
if not umlBlockRead(FSpace_IOHnd^, FPhyBlock[0], SizeOf(TZDB2_Core_BlockData) * FPhyBlockNum) then
begin
ErrorInfo('Open: umlBlockRead FPhyBlock error.');
exit;
end;
ScanSpace();
end
else
begin
ErrorInfo('Open: major/minor info error.');
exit;
end;
end;
procedure TZDB2_Core_Space.ScanSpace;
var
i: Integer;
begin
FFreeSpaceIndexProbe := FPhyBlockNum;
FState.Physics := 0;
FState.FreeSpace := 0;
i := 0;
while i < FPhyBlockNum do
begin
with FPhyBlock[i] do
begin
inc(FState.Physics, Size);
if UsedSpace = 0 then
begin
inc(FState.FreeSpace, Size);
if i < FFreeSpaceIndexProbe then
FFreeSpaceIndexProbe := i;
end;
end;
inc(i);
end;
end;
procedure TZDB2_Core_Space.PreparePhyBlock(PhyBlockNum_: Int64);
var
i: Integer;
begin
FFreeSpaceIndexProbe := 0;
FPhyBlockNum := PhyBlockNum_;
SetLength(FPhyBlock, FPhyBlockNum);
ClearCache;
SetLength(FPhyBlockWriteCache, FPhyBlockNum);
FState.Physics := 0;
FState.FreeSpace := 0;
FState.Cache := 0;
FState.ReadNum := 0;
FState.ReadSize := 0;
FState.WriteNum := 0;
FState.WriteSize := 0;
i := 0;
while i < FPhyBlockNum do
with FPhyBlock[i], FPhyBlockWriteCache[i] do
begin
// block
ID := i;
Prev := -1;
Next := -1;
// cache
Mem := nil;
FlushThisCacheToFile := False;
inc(i);
end;
end;
procedure TZDB2_Core_Space.BuildSpace(PhySpaceSize: Int64; BlockSize_: Word);
var
BlockSize: Word;
m64: TZDB2_Mem;
i: Integer;
begin
if not umlFileSeek(FSpace_IOHnd^, 0) then
begin
ErrorInfo('BuildSpace: umlFileSeek 0 error.');
exit;
end;
BlockSize := umlMax(BlockSize_, C_ZDB2_MinBlockSize);
PreparePhyBlock((PhySpaceSize - GetTableSize(PhySpaceSize div BlockSize)) div BlockSize);
m64 := TZDB2_Mem.Create;
m64.Size := GetTableSize;
m64.Position := 0;
FillPtr(m64.Memory, m64.Size, 0);
if not umlBlockWrite(FSpace_IOHnd^, m64.Memory^, m64.Size) then
begin
ErrorInfo('BuildSpace: umlBlockWrite zero head error.');
exit;
end;
DisposeObject(m64);
i := 0;
while i < FPhyBlockNum do
begin
FPhyBlock[i].Position := umlFilePOS(FSpace_IOHnd^);
FPhyBlock[i].Size := BlockSize;
FPhyBlock[i].UsedSpace := 0;
FPhyBlock[i].ID := i;
FPhyBlock[i].Next := -1;
FPhyBlock[i].Prev := -1;
if not umlBlockWrite(FSpace_IOHnd^, V_NULLData, BlockSize) then
begin
ErrorInfo('BuildSpace: umlBlockWrite NullData error.');
exit;
end;
inc(i);
if Assigned(FOnProgress) then
FOnProgress(FPhyBlockNum, i);
end;
WriteTable();
ScanSpace();
end;
procedure TZDB2_Core_Space.AppendSpace(Dest: TZDB2_Core_Space; DestPhySpaceSize: Int64; DestBlockSize_: Word);
var
DestBlockSize: Word;
m64: TZDB2_Mem;
buff: Pointer;
i: Integer;
begin
if not umlFileSeek(Dest.FSpace_IOHnd^, 0) then
begin
ErrorInfo('AppendSpace: umlFileSeek 0 error.');
exit;
end;
DestBlockSize := umlMax(DestBlockSize_, C_ZDB2_MinBlockSize);
Dest.PreparePhyBlock(FPhyBlockNum + (DestPhySpaceSize div DestBlockSize));
m64 := TZDB2_Mem.Create;
m64.Size := Dest.GetTableSize;
m64.Position := 0;
FillPtr(m64.Memory, m64.Size, 0);
if not umlBlockWrite(Dest.FSpace_IOHnd^, m64.Memory^, m64.Size) then
begin
ErrorInfo('AppendSpace: umlBlockWrite null head error.');
exit;
end;
DisposeObject(m64);
buff := System.GetMemory($FFFF);
i := 0;
while i < FPhyBlockNum do
begin
Dest.FPhyBlock[i] := FPhyBlock[i];
Dest.FPhyBlock[i].Position := umlFilePOS(Dest.FSpace_IOHnd^);
if not umlFileSeek(FSpace_IOHnd^, FPhyBlock[i].Position) then
begin
ErrorInfo('AppendSpace: umlFileSeek PhyPos error.');
exit;
end;
if not umlBlockRead(FSpace_IOHnd^, buff^, FPhyBlock[i].Size) then
begin
ErrorInfo('AppendSpace: umlBlockRead Phy error.');
exit;
end;
if not umlBlockWrite(Dest.FSpace_IOHnd^, buff^, FPhyBlock[i].Size) then
begin
ErrorInfo('AppendSpace: umlBlockWrite Phy error.');
exit;
end;
inc(i);
if Assigned(FOnProgress) then
FOnProgress(FPhyBlockNum, i);
end;
i := FPhyBlockNum;
FillPtr(buff, $FFFF, 0);
while i < Dest.FPhyBlockNum do
begin
Dest.FPhyBlock[i].Position := umlFilePOS(Dest.FSpace_IOHnd^);
Dest.FPhyBlock[i].Size := DestBlockSize;
Dest.FPhyBlock[i].UsedSpace := 0;
Dest.FPhyBlock[i].ID := i;
Dest.FPhyBlock[i].Next := -1;
Dest.FPhyBlock[i].Prev := -1;
if not umlBlockWrite(Dest.FSpace_IOHnd^, V_NULLData, DestBlockSize) then
begin
ErrorInfo('AppendSpace: umlBlockWrite NullData error.');
exit;
end;
inc(i);
if Assigned(FOnProgress) then
FOnProgress(FPhyBlockNum, i);
end;
System.FreeMemory(buff);
Dest.WriteTable();
Dest.ScanSpace();
end;
procedure TZDB2_Core_Space.OptimizeInstance(Dest: TZDB2_Core_Space);
var
m64: TZDB2_Mem;
buff: Pointer;
i: Integer;
begin
if not umlFileSeek(Dest.FSpace_IOHnd^, 0) then
begin
ErrorInfo('OptimizeInstance: umlFileSeek 0 error.');
exit;
end;
Dest.PreparePhyBlock(FPhyBlockNum);
m64 := TZDB2_Mem.Create;
m64.Size := GetTableSize;
m64.Position := 0;
FillPtr(m64.Memory, m64.Size, 0);
if not umlBlockWrite(Dest.FSpace_IOHnd^, m64.Memory^, m64.Size) then
begin
ErrorInfo('OptimizeInstance: umlBlockWrite Null Head error.');
exit;
end;
DisposeObject(m64);
buff := System.GetMemory($FFFF);
i := 0;
while i < FPhyBlockNum do
begin
Dest.FPhyBlock[i] := FPhyBlock[i];
Dest.FPhyBlock[i].Position := umlFilePOS(Dest.FSpace_IOHnd^);
if not umlFileSeek(FSpace_IOHnd^, FPhyBlock[i].Position) then
begin
ErrorInfo('OptimizeInstance: umlFileSeek Phy error.');
exit;
end;
if not umlBlockRead(FSpace_IOHnd^, buff^, FPhyBlock[i].Size) then
begin
ErrorInfo('OptimizeInstance: umlBlockRead Phy error.');
exit;
end;
if not umlBlockWrite(Dest.FSpace_IOHnd^, buff^, FPhyBlock[i].Size) then
begin
ErrorInfo('OptimizeInstance: umlBlockWrite Phy error.');
exit;
end;
inc(i);
if Assigned(FOnProgress) then
FOnProgress(FPhyBlockNum, i);
end;
System.FreeMemory(buff);
Dest.WriteTable();
Dest.ScanSpace();
end;
function TZDB2_Core_Space.Check(ID_: Integer): Boolean;
var
ID, i, num: Integer;
begin
Result := False;
if FPhyBlockNum = 0 then
exit;
ID := ID_;
if (ID < 0) or (ID >= FPhyBlockNum) then
exit;
while FPhyBlock[ID].Prev >= 0 do
if (ID >= 0) and (ID < FPhyBlockNum) and (FPhyBlock[ID].UsedSpace > 0) then
ID := FPhyBlock[ID].Prev
else
exit;
num := 0;
i := ID;
repeat
if FPhyBlock[i].UsedSpace = 0 then
exit;
inc(num);
i := FPhyBlock[i].Next;
until i < 0;
Result := True;
end;
function TZDB2_Core_Space.GetSpaceHndID(ID_: Integer): Integer;
var
ID, i, num: Integer;
begin
Result := -1;
if FPhyBlockNum = 0 then
exit;
ID := ID_;
if (ID < 0) or (ID >= FPhyBlockNum) then
exit;
while FPhyBlock[ID].Prev >= 0 do
if (ID >= 0) and (ID < FPhyBlockNum) and (FPhyBlock[ID].UsedSpace > 0) then
ID := FPhyBlock[ID].Prev
else
exit;
num := 0;
i := ID;
repeat
if FPhyBlock[i].UsedSpace = 0 then
exit;
inc(num);
i := FPhyBlock[i].Next;
until i < 0;
Result := ID;
end;
function TZDB2_Core_Space.GetSpaceHnd(ID_: Integer): TZDB2_Core_BlockHnd;
var
ID, i, num: Integer;
begin
SetLength(Result, 0);
ID := ID_;
if ID < 0 then
exit;
while FPhyBlock[ID].Prev >= 0 do
if (ID >= 0) and (ID < FPhyBlockNum) and (FPhyBlock[ID].UsedSpace > 0) then
ID := FPhyBlock[ID].Prev
else
exit;
num := 0;
i := ID;
repeat
if FPhyBlock[i].UsedSpace = 0 then
exit;
inc(num);
i := FPhyBlock[i].Next;
until i < 0;
SetLength(Result, num);
i := ID;
num := 0;
repeat
Result[num] := i;
inc(num);
i := FPhyBlock[i].Next;
until i < 0;
end;
function TZDB2_Core_Space.CheckWriteSpace(Siz_: Int64): Boolean;
begin
Result := CheckWriteSpace(Siz_, nil);
end;
function TZDB2_Core_Space.CheckWriteSpace(Siz_: Int64; Space_: TZDB2_Core_BlockPtrList): Boolean;
var
tmp: Int64;
i: Integer;
begin
if Space_ <> nil then
Space_.Clear;
Result := False;
if Siz_ = 0 then
exit;
tmp := 0;
i := FFreeSpaceIndexProbe;
while (i < FPhyBlockNum) and (tmp < Siz_) do
with FPhyBlock[i] do
begin
if UsedSpace = 0 then
begin
inc(tmp, Size);
if Space_ <> nil then
Space_.Add(@FPhyBlock[i]);
end;
inc(i);
end;
Result := tmp >= Siz_;
end;
function TZDB2_Core_Space.WriteData(buff: TZDB2_Mem; var SpaceHnd: TZDB2_Core_BlockHnd): Boolean;
var
Space_: TZDB2_Core_BlockPtrList;
tmp: Int64;
i, j: Integer;
p: Pointer;
n: TZDB2_Core_BlockPtrList;
retry: Boolean;
begin
Result := False;
if buff.Size = 0 then
begin
ErrorInfo('WriteData: buff size 0.');
exit;
end;
{ compute space }
Space_ := TZDB2_Core_BlockPtrList.Create;
if not CheckWriteSpace(buff.Size, Space_) then
begin
DisposeObject(Space_);
retry := False;
if Assigned(FOnNoSpace) then
FOnNoSpace(buff.Size, retry);
if retry then
Result := WriteData(buff, SpaceHnd)
else
ErrorInfo('WriteData: No Space.');
exit;
end;
SetLength(SpaceHnd, Space_.Count);
{ fill block }
tmp := buff.Size;
p := buff.Memory;
i := 0;
while i < Space_.Count do
with Space_[i]^ do
begin
if tmp > Size then
begin
if not WriteCacheBlock(p, Size, ID, True) then
begin
if not umlFileSeek(FSpace_IOHnd^, Position) then
begin
ErrorInfo('WriteData: umlFileSeek Block error.');
exit;
end;
if not umlBlockWrite(FSpace_IOHnd^, p^, Size) then
begin
ErrorInfo('WriteData: umlBlockWrite Block error.');
exit;
end;
end;
Dec(FState.FreeSpace, Size);
UsedSpace := Size;
Dec(tmp, Size);
p := GetOffset(p, Size);
SpaceHnd[i] := ID;
inc(i);
end
else
begin
if not WriteCacheBlock(p, tmp, ID, True) then
begin
if not umlFileSeek(FSpace_IOHnd^, Position) then
begin
ErrorInfo('WriteData: umlFileSeek trail Block error.');
exit;
end;
if not umlBlockWrite(FSpace_IOHnd^, p^, tmp) then
begin
ErrorInfo('WriteData: umlBlockWrite trail Block error.');
exit;
end;
end;
Dec(FState.FreeSpace, Size);
UsedSpace := tmp;
SpaceHnd[i] := ID;
inc(i);
Result := True;
break;
end;
end;
DisposeObject(Space_);
// fill link
j := 0;
FPhyBlock[SpaceHnd[0]].Prev := -1;
while j < Length(SpaceHnd) do
begin
if j > 0 then
begin
FPhyBlock[SpaceHnd[j - 1]].Next := SpaceHnd[j];
FPhyBlock[SpaceHnd[j]].Prev := SpaceHnd[j - 1];
end;
inc(j);
end;
FPhyBlock[SpaceHnd[j - 1]].Next := -1;
// chagne state
inc(FState.WriteNum);
inc(FState.WriteSize, buff.Size);
// prepare probe for next
FFreeSpaceIndexProbe := FPhyBlockNum;
i := FPhyBlock[SpaceHnd[j - 1]].ID + 1;
while i < FPhyBlockNum do
with FPhyBlock[i] do
begin
if UsedSpace = 0 then
begin
FFreeSpaceIndexProbe := i;
break;
end
else
inc(i);
end;
end;
function TZDB2_Core_Space.WriteData(buff: TZDB2_Mem; var ID: Integer): Boolean;
var
SpaceHnd: TZDB2_Core_BlockHnd;
begin
Result := WriteData(buff, SpaceHnd);
if Result then
ID := SpaceHnd[0];
SetLength(SpaceHnd, 0);
end;
function TZDB2_Core_Space.ReadData(buff: TZDB2_Mem; SpaceHnd: TZDB2_Core_BlockHnd): Boolean;
var
i: Integer;
Siz_: Int64;
p: Pointer;
begin
Result := False;
if Length(SpaceHnd) = 0 then
begin
ErrorInfo('ReadData: SpaceHnd null error.');
exit;
end;
{ compute queue space }
i := 0;
Siz_ := 0;
while i < Length(SpaceHnd) do
with FPhyBlock[SpaceHnd[i]] do
begin
inc(Siz_, UsedSpace);
inc(i);
end;
{ prepare memory }
buff.Size := Siz_;
if Siz_ = 0 then
exit;
{ read }
i := 0;
p := buff.Memory;
while i < Length(SpaceHnd) do
with FPhyBlock[SpaceHnd[i]] do
begin
if not ReadCacheBlock(p, ID) then
begin
if not umlFileSeek(FSpace_IOHnd^, Position) then
begin
ErrorInfo('ReadData: umlFileSeek error.');
exit;
end;
if not umlBlockRead(FSpace_IOHnd^, p^, UsedSpace) then
begin
ErrorInfo('ReadData: umlBlockRead error.');
exit;
end;
if FUsedReadCache then
WriteCacheBlock(p, UsedSpace, ID, False);
end;
p := GetOffset(p, UsedSpace);
inc(i);
end;
inc(FState.ReadNum);
inc(FState.ReadSize, Siz_);
Result := True;
end;
function TZDB2_Core_Space.ReadData(buff: TZDB2_Mem; ID: Integer): Boolean;
begin
Result := ReadData(buff, GetSpaceHnd(ID));
end;
function TZDB2_Core_Space.RemoveData(SpaceHnd: TZDB2_Core_BlockHnd; SafeClean_: Boolean): Boolean;
var
i: Integer;
begin
Result := (Length(SpaceHnd) > 0) and Check(SpaceHnd[0]);
i := 0;
while i < Length(SpaceHnd) do
with FPhyBlock[SpaceHnd[i]] do
begin
DeleteCache(ID);
UsedSpace := 0;
Prev := -1;
Next := -1;
if ID < FFreeSpaceIndexProbe then
FFreeSpaceIndexProbe := ID;
inc(FState.FreeSpace, Size);
{ safe remove }
if SafeClean_ then
if not WriteCacheBlock(@V_NULLData, Size, ID, True) then
begin
if not umlFileSeek(FSpace_IOHnd^, Position) then
begin
ErrorInfo('RemoveData: umlFileSeek error.');
exit;
end;
if not umlBlockWrite(FSpace_IOHnd^, V_NULLData, Size) then
begin
ErrorInfo('RemoveData: umlBlockWrite error.');
exit;
end;
end;
inc(i);
end;
end;
function TZDB2_Core_Space.RemoveData(ID: Integer; SafeClean_: Boolean): Boolean;
begin
Result := RemoveData(GetSpaceHnd(ID), SafeClean_);
end;
function TZDB2_Core_Space.GetDataSize(SpaceHnd: TZDB2_Core_BlockHnd): Int64;
var
i: Integer;
begin
Result := 0;
i := 0;
while i < Length(SpaceHnd) do
with FPhyBlock[SpaceHnd[i]] do
begin
inc(Result, UsedSpace);
inc(i);
end;
end;
function TZDB2_Core_Space.GetDataSize(ID: Integer): Int64;
begin
Result := GetDataSize(GetSpaceHnd(ID));
end;
function TZDB2_Core_Space.GetDataPhysics(SpaceHnd: TZDB2_Core_BlockHnd): Int64;
var
i: Integer;
begin
Result := 0;
i := 0;
while i < Length(SpaceHnd) do
with FPhyBlock[SpaceHnd[i]] do
begin
inc(Result, Size);
inc(i);
end;
end;
function TZDB2_Core_Space.GetDataPhysics(ID: Integer): Int64;
begin
Result := GetDataPhysics(GetSpaceHnd(ID));
end;
class procedure TZDB2_Core_Space.Test;
var
st1, st2, st3: TZDB2_Core_Space;
hnd1, hnd2, hnd3: TIOHnd;
q, q2: TZDB2_Core_BlockHnd;
m64: TZDB2_Mem;
begin
InitIOHnd(hnd1);
InitIOHnd(hnd2);
InitIOHnd(hnd3);
umlFileCreateAsMemory(hnd1);
umlFileCreateAsMemory(hnd2);
umlFileCreateAsMemory(hnd3);
st1 := TZDB2_Core_Space.Create(@hnd1);
st2 := TZDB2_Core_Space.Create(@hnd2);
st3 := TZDB2_Core_Space.Create(@hnd3);
st1.BuildSpace(1024 * 1024 * 50, 512);
st1.AppendSpace(st2, 1024 * 1024 * 2, 1024);
st1.OptimizeInstance(st3);
m64 := TZDB2_Mem.Create;
m64.Size := 1024 * 1024 * 20;
st1.WriteData(m64, q2);
st1.Save;
st1.WriteData(m64, q);
st1.Save;
m64.Clear;
st1.Open;
st1.ReadData(m64, q);
st1.ReadData(m64, q[2]);
st1.RemoveData(q, True);
st1.ScanSpace;
DisposeObject(m64);
m64 := TZDB2_Mem.Create;
m64.Size := 64;
st1.WriteData(m64, q);
st1.Save;
m64.Clear;
st1.Open;
st1.ReadData(m64, q);
st1.ReadData(m64, q[0]);
st1.RemoveData(q, True);
st1.ScanSpace;
DisposeObject(m64);
m64 := TZDB2_Mem.Create;
m64.Size := 1024;
st1.WriteData(m64, q);
st1.Save;
m64.Clear;
st1.Open;
st1.ReadData(m64, q);
st1.ReadData(m64, q[0]);
st1.RemoveData(q, True);
st1.ScanSpace;
DisposeObject(m64);
st1.RemoveData(q2, True);
st1.ScanSpace;
DisposeObject(st1);
DisposeObject(st2);
DisposeObject(st3);
umlFileClose(hnd1);
umlFileClose(hnd2);
umlFileClose(hnd3);
DoStatus('TZDB2_Core_Space.Test passed.');
end;
initialization
FillPtr(@V_NULLData, $FFFF, 0);
finalization
end.
|
program Z;
uses graphABC;
const
H = 480;
W = 600;
X1 = W div 2;
Y1 = H div 2;
winColor = clWhite;
RAD = 180 / pi;
procedure Brush
(
color: System.Drawing.Color;
style: System.Drawing.Drawing2D.DashStyle;
width: integer
);
{ Sets brush options }
begin
SetPenColor(color);
SetPenStyle(style);
SetPenWidth(width)
end;
Procedure Trapezoid
(
X, // X-axis of the centre of the base
Y, // Y-axis of the centre of the base
{ @par optional 1 } top,
height,
{ @par optional 2 }base,
outlineWidth: integer;
{ @par optional 2 } angle: real; // equal angles at the base
firstColor, // outline color
secondColor: System.Drawing.Color // main color
);
{
Drows isosceles trapezoid by required parameters such as X, Y, height.
You need push one of the optional parameters such as angle and base or top.
Push 0 to ignore an optional parameter.
}
var
lX, rX, ToplX, ToprX, TopY, k: integer;
alfa: real;
{ @var k means distance from edges of the base and top }
{ @var alfa is angle in RAD }
begin
alfa := angle / RAD;
TopY := Y - height;
{ calculating k using pushed optional parameter }
if angle = 0 then
k := (base - top) div 2
else
begin
if angle > 90 then alfa := alfa - pi;
if round(angle) mod 90 = 0 then k := 0
else k := round(height / (sin(alfa) / cos(alfa)))
end;
{
Calculating edges of the base using pushed optional parameter.
If you ignore base it will be equal to 2k.
}
if (base = 0) and (angle <= 90) then base := 2*k;
lX := X - base div 2;
rX := X + base div 2;
{ edges of the top }
ToplX := lX + k;
ToprX := rX - k;
Brush(firstColor, psSolid, outlineWidth);
{ draws trapezoid }
line(lX, Y, rX, Y);
line(lX, Y, ToplX, TopY);
line(rX, Y, ToprX, TopY);
line(ToplX, TopY, ToprX, TopY);
FloodFill(X, (Y - height div 2), secondColor);
end;
begin
SetWindowSize(W, H);
ClearWindow(winColor);
Trapezoid(X1, Y1, 0, -100, -40, 4, 140, clBlack, clRed);
end.
|
unit uUtil;
interface
uses
System.SysUtils, sEdit, sSpinEdit, System.RegularExpressions, System.Classes, Vcl.Clipbrd, Vcl.StdCtrls, Vcl.Controls, WinHttp_XE;
const
UpCaseAlphabat: TSysCharSet = ['A' .. 'Z']; // 65 ~ 90
DownCaseAlphabat: TSysCharSet = ['a' .. 'z']; // 97 ~ 122
Numberic: TSysCharSet = ['0' .. '9']; // 48 ~ 57
SpecialChar: TSysCharSet = ['!' .. '/', ':' .. '@', '[' .. '`', '{' .. '~']; // 32�� Ư������ 33 ~ 47, 58 ~ 64, 91 ~ 96, 123 ~ 126
function WebText(sText : String): String;
function Split(str, delimiter: string): TStringList;
function IsExistChar(src: String; CharSet: TSysCharSet): Boolean;
function GetToken(var sSrc: string; sDelim: string): String;
procedure CheckMouseButtonClipboardTag(Button: TMouseButton);
function IsValidMail(sMail: String): Boolean;
implementation
function WebText(sText: String): String;
begin
sText := StringReplace(sText, '%','%25', [rfReplaceAll]);
sText := StringReplace(sText, ' ','%20', [rfReplaceAll]);
sText := StringReplace(sText, '?','%3F', [rfReplaceAll]);
sText := StringReplace(sText, '=','%3D', [rfReplaceAll]);
sText := StringReplace(sText, '#','%23', [rfReplaceAll]);
sText := StringReplace(sText, '\','%5C', [rfReplaceAll]);
sText := StringReplace(sText, '&','%26%26', [rfReplaceAll]);
result := sText;
end;
function IsExistChar(src: String; CharSet: TSysCharSet): Boolean;
var nCnt, i: Integer;
begin
nCnt := 0;
for i := 1 to Length(src) do
begin
if CharInSet( src[i], CharSet ) then
begin
Inc(nCnt);
end;
end;
Result := nCnt > 0;
end;
//String�� String delimiter�� ������ function
function Split(str, delimiter: string): TStringList;
var
P, dlen, flen: integer;
begin
Result := TStringList.Create;
dlen := Length(delimiter);
flen := Length(str);
repeat
P := Pos(delimiter, str);
if P = 0 then
P := flen + dlen;
Result.Add(copy(str, 1, P - 1));
str := copy(str, P + dlen, flen);
flen := Length(str);
until flen = 0;
end;
function GetToken(var sSrc: string; sDelim: string): String;
var
nPos : Integer;
begin
nPos := Pos(sDelim, sSrc);
if (nPos > 0) then begin
Dec(nPos);
Result := copy(sSrc, 1, nPos);
Delete(sSrc, 1, nPos + Length(sDelim));
end else begin
Result := sSrc;
sSrc := '';
end;
end;
procedure CheckMouseButtonClipboardTag(Button: TMouseButton);
var
sText : String;
begin
if (Button = mbRight) then
begin
sText := Clipboard.AsText;
if (Pos('<', sText) > 0) or (Pos('>', sText) > 0) then
Clipboard.Clear;
end;
end;
function IsValidMail(sMail: String): Boolean;
procedure Split(Delimiter: Char; Str: string; ListOfStrings: TStringList);
begin
ListOfStrings.Clear;
ListOfStrings.Delimiter := Delimiter;
ListOfStrings.StrictDelimiter := True;
ListOfStrings.DelimitedText := Str;
end;
function CheckAllowedLocal(const Str: string): Boolean;
var
i: Integer;
begin
Result := False;
for i := 1 to Length(Str) do
if not CharInSet(Str[i], [
'a' .. 'z', 'A' .. 'Z', '0' .. '9',
'!', '#', '$', '%', '*', '+', '-', '/', '^', '_',
'.'
]) then
Exit;
Result := True;
end;
function CheckAllowedDomain(const Str: string): Boolean;
var
i: Integer;
begin
Result := False;
if Str = '' then
Exit;
if (Str[1] = '-') or (Str[length(str)] = '-') then
Exit;
if Length(Str) > 63 then
Exit;
for i := 1 to Length(Str) do
if not CharInSet(Str[i], ['a' .. 'z', 'A' .. 'Z', '0' .. '9', '-']) then
Exit;
Result := True;
end;
var
sList: TStringList;
i, onPos: Integer;
Local, Domain: string;
begin
Result := False;
onPos := Pos('@', sMail);
if onPos = 0 then
Exit;
Local := Copy(sMail, 1, onPos - 1);
Domain := Copy(sMail, onPos + 1, Length(sMail) - onPos);
if (Length(Local) = 0) or ((Length(Domain) < 5)) then
Exit;
if CheckAllowedLocal(Local) = False then
Exit;
sList := TStringList.Create;
try
Split('.', Domain, sList);
if sList.Count < 2 then
begin
Result := False;
Exit;
end;
for i := 0 to sList.Count - 1 do
begin
if CheckAllowedDomain(Trim(sList.Strings[i])) = False then
Exit;
end;
finally
sList.Free;
end;
Result := True;
end;
end.
|
unit WinPrinterUtils;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils
{$IF Defined(MSWINDOWS)}
,windows, winspool
{$ENDIF}
;
{$IF Defined(MSWINDOWS)}
function GetPrinterDuplexParam(InPrinterName: String): Boolean;
function SetPrinterDuplexObsolete(hWnd: HWND; InDevice: String; InIsItDuplex: Boolean): boolean;
function SetPrinterDuplexGlobally(InPrinterName: String; InIsItDuplex: Boolean; InBroadcastChangeMessage: Boolean): boolean;
{$ENDIF}
implementation
{$IF Defined(MSWINDOWS)}
function GetPrinterDuplexParam(InPrinterName: String): Boolean;
var hPrinter: THANDLE;
MyPDevMode: LPDEVMODE;
dwNeeded, dwRet: LONG;
MySet: DWORD;
MyResult: DWORD;
begin
MyResult := DMDUP_SIMPLEX;
MyPDevMode := nil;
hPrinter := 0;
// Start by opening the printer
if (OpenPrinter(PChar(InPrinterName), @hPrinter, nil)) then begin
// Step 1:
// Allocate a buffer of the correct size.
dwNeeded := DocumentProperties(0,
hPrinter, // Handle to our printer.
PChar(InPrinterName),// Name of the printer.
nil, // Asking for size, so
nil, // these are not used.
0); // Zero returns buffer size.
GetMem(MyPDevMode, dwNeeded);
// Step 2:
// Get the default DevMode for the printer and
// modify it for your needs.
dwRet := DocumentProperties(0,
hPrinter,
PChar(InPrinterName),
MyPDevMode, // The address of the buffer to fill.
nil, // Not using the input buffer.
DM_OUT_BUFFER); // Have the output buffer filled.
if (dwRet <> IDOK) then begin
// If failure, cleanup and return failure.
ClosePrinter(hPrinter);
if MyPDevMode <> nil then begin
freemem(MyPDevMode);
MyPDevMode := nil;
end;
Exit(False);
end;
MyResult := MyPDevMode^.dmDuplex;
// Finished with the printer
ClosePrinter(hPrinter);
// Return the modified DevMode structure.
if MyPDevMode <> nil then begin
freemem(MyPDevMode);
MyPDevMode := nil;
end;
end;
Result := MyResult <> DMDUP_SIMPLEX;
end;
function SetPrinterDuplexObsolete(hWnd: HWND; InDevice: String; InIsItDuplex: Boolean): boolean;
var hPrinter: THANDLE;
MyPDevMode: LPDEVMODE;
MySize: Integer;
dwNeeded, dwRet: LONG;
MyResult: Boolean;
MySet: DWORD;
pd:PRINTER_DEFAULTS;
pi2: PPRINTER_INFO_2A;
begin
// This function does not work correctly
// I think that SetPrinter function is missing
// Anyhow - this is rewritten from microsoft web site
// Check this https://support.microsoft.com/en-us/kb/167345
MyResult := False;
MyPDevMode := nil;
hPrinter := 0;
hWnd := 0;
// Start by opening the printer
FillByte(pd,sizeof(PRINTER_DEFAULTS), 0);
//#define PRINTER_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED|PRINTER_ACCESS_ADMINISTER|PRINTER_ACCESS_USE)
pd.DesiredAccess:=STANDARD_RIGHTS_REQUIRED or 4 or 8;
if (OpenPrinter(PChar(InDevice), @hPrinter, @pd)) then begin
// Step 1:
// Allocate a buffer of the correct size.
dwNeeded := DocumentProperties(hWnd,
hPrinter, // Handle to our printer.
PChar(InDevice),// Name of the printer.
nil, // Asking for size, so
nil, // these are not used.
0); // Zero returns buffer size.
GetMem(MyPDevMode, dwNeeded);
// Step 2:
// Get the default DevMode for the printer and
// modify it for your needs.
dwRet := DocumentProperties(hWnd,
hPrinter,
PChar(InDevice),
MyPDevMode, // The address of the buffer to fill.
nil, // Not using the input buffer.
DM_OUT_BUFFER); // Have the output buffer filled.
if (dwRet <> IDOK) then begin
// If failure, cleanup and return failure.
ClosePrinter(hPrinter);
if MyPDevMode <> nil then begin
freemem(MyPDevMode);
MyPDevMode := nil;
end;
Exit(MyResult);
end;
if InIsItDuplex then begin
if ((MyPDevMode^.dmFields and DM_DUPLEX) <> 0) then begin
MyPDevMode^.dmDuplex := DMDUP_VERTICAL; // DMDUP_HORIZONTAL;
MyPDevMode^.dmFields := DM_DUPLEX;
end;
end
else begin
if ((MyPDevMode^.dmFields and DM_DUPLEX) <> 0) then begin
MyPDevMode^.dmDuplex := DMDUP_SIMPLEX;
MyPDevMode^.dmFields := DM_DUPLEX;
end;
end;
//
// Step 3:
// Merge the new settings with the old.
// This gives the driver an opportunity to update any private
// portions of the DevMode structure.
MySet := DM_IN_BUFFER or // Commands to Merge our changes and
DM_OUT_BUFFER;
dwRet := DocumentProperties(hWnd,
hPrinter,
PChar(InDevice),
MyPDevMode, // Reuse our buffer for output.
MyPDevMode, // Pass the driver our changes.
MySet
); // write the result.
// Finished with the printer
ClosePrinter(hPrinter);
if (dwRet <> IDOK) then begin
// If failure, cleanup and return failure.
if MyPDevMode <> nil then begin
Freemem(MyPDevMode, dwNeeded);
MyPDevMode := nil;
end;
Exit(MyResult);
end;
// Return the modified DevMode structure.
if MyPDevMode <> nil then begin
freemem(MyPDevMode);
MyPDevMode := nil;
Result := True;
end;
end
else begin
Result := False;
end;
end;
function SetPrinterDuplexGlobally(InPrinterName: String; InIsItDuplex: Boolean; InBroadcastChangeMessage: Boolean): boolean;
var MyHandle:THANDLE;
MyPrinterDefaults:PRINTER_DEFAULTS;
MyDWNeeded: DWORD;
MyPPRINTER_INFO_2A: PPRINTER_INFO_2A;
MyPDevMode: PDEVMODE;
MyLastErrorCode: DWORD;
MyDocumentPropertiesRetCode: LONG;
begin
MyLastErrorCode := 0;
result:=false;
fillchar(MyPrinterDefaults, sizeof(PRINTER_DEFAULTSA), #0);
//#define PRINTER_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED|PRINTER_ACCESS_ADMINISTER|PRINTER_ACCESS_USE)
MyPrinterDefaults.DesiredAccess:=STANDARD_RIGHTS_REQUIRED or 4 or 8;
// MyPrinterDefaults.DesiredAccess := PRINTER_NORMAL_ACCESS;
OpenPrinter(pchar(InPrinterName),@MyHandle,@MyPrinterDefaults);
if (MyHandle = 0) then begin
// Cannot get printer hanlde
MyLastErrorCode:=GetLastError;
Exit;
end;
GetPrinter(MyHandle, 2, nil, 0, @MyDWNeeded);
MyPPRINTER_INFO_2A:=PPRINTER_INFO_2A(GlobalAlloc(GPTR, MyDWNeeded));
try
if GetPrinter(MyHandle, 2, pbyte(MyPPRINTER_INFO_2A), MyDWNeeded, @MyDWNeeded) then begin
if ((MyPPRINTER_INFO_2A^.pDevMode^.dmFields and DM_DUPLEX) <> 0) then begin
if InIsItDuplex then begin
MyPPRINTER_INFO_2A^.pDevMode^.dmDuplex := DMDUP_VERTICAL;
MyPPRINTER_INFO_2A^.pDevMode^.dmFields := DM_DUPLEX;
end
else begin
MyPPRINTER_INFO_2A^.pDevMode^.dmDuplex := DMDUP_SIMPLEX;
MyPPRINTER_INFO_2A^.pDevMode^.dmFields := DM_DUPLEX;
end;
MyPPRINTER_INFO_2A^.pSecurityDescriptor:=nil;
MyDocumentPropertiesRetCode := DocumentProperties(0, MyHandle, pchar(InPrinterName), MyPPRINTER_INFO_2A^.pDevMode, MyPPRINTER_INFO_2A^.pDevMode, DM_IN_BUFFER or DM_OUT_BUFFER);
if MyDocumentPropertiesRetCode = IDOK then begin
if SetPrinter(MyHandle, 2, pbyte(MyPPRINTER_INFO_2A), 0) then begin
result := true;
// Broadcast change printer message to all windows application
if InBroadcastChangeMessage then begin
SendMessageTimeout(HWND_BROADCAST, WM_DEVMODECHANGE, 0, LPARAM(pchar(InPrinterName)), SMTO_NORMAL, 1000, MyDWNeeded);
end;
end
else begin
MyLastErrorCode:=GetLastError;
end;
end
else begin
// Unable to set printer properties
MyLastErrorCode := -1;
end;
end;
end;
finally
GlobalFree(LongWord(MyPPRINTER_INFO_2A));
ClosePrinter(MyHandle);
end;
end;
{$ENDIF}
end.
|
unit intensive.Services.Generic;
interface
uses
SimpleInterface,
SimpleDAO,
SimpleAttributes,
SimpleQueryFiredac,
FireDAC.Stan.Intf,
FireDAC.Stan.Option,
FireDAC.Stan.Error,
FireDAC.UI.Intf,
FireDAC.Phys.Intf,
FireDAC.Stan.Def,
FireDAC.Stan.Pool,
FireDAC.Stan.Async,
FireDAC.Phys,
FireDAC.Phys.SQLite,
FireDAC.Phys.SQLiteDef,
FireDAC.Stan.ExprFuncs,
FireDAC.Phys.SQLiteWrapper.Stat,
FireDAC.VCLUI.Wait,
FireDAC.Comp.UI,
Data.DB,
FireDAC.Comp.Client,
intensive.Resources.Interfaces,
intensive.Resources.Conexao,
System.Generics.Collections;
type
iService<T: Class> = interface
function Listar: TDataSet;
function ListarPorId(Id: Integer): TDataSet;
function ListarPorFiltro(Key: String; Value: Variant): TDataSet;
function Inserir: iService<T>;
function Atualizar: iService<T>;
function Excluir: iService<T>; overload;
function Excluir(Field: String; Value: String): iService<T>; overload;
function DataSource(var aDataSource: TDataSource): iService<T>;
function Entity: T;
end;
TService<T: class, constructor> = class(TInterfacedObject, iService<T>)
private
FParent: T;
FConexao: iConexao;
FConn: iSimpleQuery;
FDAO: iSimpleDAO<T>;
FDataSource: TDataSource;
public
constructor Create(Parent: T);
destructor Destroy; override;
class function New(Parent: T): iService<T>;
function Listar: TDataSet;
function ListarPorId(Id: Integer): TDataSet;
function ListarPorFiltro(Key: String; Value: Variant): TDataSet;
function Inserir: iService<T>;
function Atualizar: iService<T>;
function Excluir: iService<T>; overload;
function Excluir(Field: String; Value: String): iService<T>; overload;
function DataSource(var aDataSource: TDataSource): iService<T>;
function Entity: T;
end;
implementation
function TService<T>.Atualizar: iService<T>;
begin
Result := Self;
FDAO.Update(FParent);
end;
constructor TService<T>.Create(Parent: T);
begin
FParent := Parent;
FDataSource := TDataSource.Create(nil);
FConexao := TConexao.New;
FConn := TSimpleQueryFiredac.New(TFDConnection(FConexao.Connect));
FDAO := TSimpleDAO<T>.New(FConn).DataSource(FDataSource);
end;
function TService<T>.DataSource(var aDataSource: TDataSource): iService<T>;
begin
Result := Self;
aDataSource := FDataSource;
end;
destructor TService<T>.Destroy;
begin
FDataSource.DisposeOf;
inherited;
end;
function TService<T>.Excluir: iService<T>;
begin
Result := Self;
FDAO.Delete(FParent);
end;
function TService<T>.Excluir(Field, Value: String): iService<T>;
begin
Result := Self;
FDAO.Delete(Field, Value);
end;
function TService<T>.Inserir: iService<T>;
begin
Result := Self;
FDAO.Insert(FParent);
end;
function TService<T>.Listar: TDataSet;
begin
FDAO.Find;
Result := FDataSource.DataSet;
end;
function TService<T>.ListarPorFiltro(Key: String; Value: Variant): TDataSet;
begin
FDAO.Find(Key, Value);
Result := FDataSource.DataSet;
end;
function TService<T>.ListarPorId(Id: Integer): TDataSet;
begin
FDAO.Find(Id);
Result := FDataSource.DataSet;
end;
class function TService<T>.New(Parent: T): iService<T>;
begin
Result := Self.Create(Parent);
end;
function TService<T>.Entity: T;
begin
Result := FParent;
end;
end.
|
{$R-} {Range checking off}
{$B+} {Boolean complete evaluation on}
{$S+} {Stack checking on}
{$I+} {I/O checking on}
{$N-} {No numeric coprocessor}
{$M 65500,16384,655360} {Turbo 3 default stack and heap}
program FITCURVE; {Fits parameters to a discount function using coupon bond
prices. Uses the simplex algorithm. Requires an input
file with bond data.}
{!USES!}
const memo =
'Function: Pt = exp[B * t* (1-exp(-a * t)) + g * t]';
memo2 =
'Parameters are: a, b, g ';
m = 3; {number of parameters to fit}
nvpp = 2; {total number of variables per data point}
n = 4; {m + 1}
mnp = 200; {maximum number of data points}
lw = 5; {width of line in data fields +1}
alfa = 1.0; {reflection coefficient}
beta = 0.5; {contraction coefficient}
gamma = 2.0; {expansion coefficient}
page = 12;
root2 = 1.414214;
type vector = array[1..n] of real;
BondData = record
Price,
Accrued,
FirstTime,
CpnFact,
Yield,
weight,
Coupon : real;
FlowCount : integer;
end;
index = 0..255;
anystr = string[12];
var done : boolean; {convergence}
i,j : index;
h,l : array[1..n] of index; {number high/low parameters}
np, {number of data points}
maxiter,
OldX, OldY,
niter : integer;
next, {next vertex to be tested}
center, {center of hyperplane described by all
vertices of the simplex excluding the
worst}
mean, error,
maxerr,
p,q, {to compute first simplex}
step : vector; {input starting steps}
simp : array[1..n] of vector; {the simplex}
Bond : array[1..mnp] of BondData;
answer,
FName : anystr; {filename}
FileToRead,
Outfile : text; {input,output}
TimeIn,
ElapsedTime : real;
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
function f (x : vector; B: BondData) : real;
{ x(1..m) the parameters, B has the Bond}
var Time,
DiscSum,
AdjCoup : real;
i : index;
begin
DiscSum := 0.0;
with B do
begin
for i := 1 to FlowCount do
begin
if i = 1 then AdjCoup := Coupon * CpnFact
else AdjCoup := Coupon;
if i = FlowCount then AdjCoup := Coupon + 100;
Time := FirstTime + 0.5 * (i-1);
DiscSum := DiscSum + AdjCoup *
exp(-Time * (x[2] * (1-exp(-x[1]*Time)) + x[3]));
end;
end;
f := DiscSum
end;
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
function Power(base,raise : real) : real;
begin
Power := exp(ln(base) * raise)
end;
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
function BondPrice ( B: BondData) : real;
{ B has the Bond}
var Time,
DiscSum,
AdjCoup : real;
i : index;
begin
DiscSum := 0.0;
with B do
begin
for i := 1 to FlowCount do
begin
if i = 1 then AdjCoup := Coupon * CpnFact
else AdjCoup := Coupon;
if i = FlowCount then AdjCoup := Coupon + 100;
Time := FirstTime + 0.5 * (i-1);
DiscSum := DiscSum + AdjCoup / power(1+Yield/2,Time);
end;
end;
BondPrice := DiscSum - B.Accrued;
end;
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
procedure ComputeWeights;
{the weights are the reciprocal of}
{each bond's price multiplier }
{adjusted so they sum to one (1) }
var i : index;
SumWeight,
PriceUp,
PriceDn : real;
begin
SumWeight := 0.0;
for i := 1 to np do
with Bond[i] do
begin
Yield := Yield - 0.001;
PriceUp := BondPrice(Bond[i]);
Yield := Yield + 0.002;
PriceDn := BondPrice(Bond[i]);
weight := 1 / (PriceUp - PriceDn);
Yield := Yield - 0.001; {restore original Yield}
SumWeight := SumWeight + weight;
end;
for i := 1 to np do
with Bond[i] do
begin
weight := weight / SumWeight;
end
end;
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
procedure SumOfResiduals (var x :vector);
{computes sum of the squared residuals}
{x(1..m) passes the parameters. Result returned in x(n)}
var i : index;
begin
x[n] := 0.0;
for i := 1 to np do
begin
x[n] := x[n] +
Bond[i].weight * sqr(f(x,Bond[i]) - Bond[i].Price);
end
end;
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
{Includes utility subroutines during compliation}
{$I Date.sub}
|
unit xProtocolType;
interface
const
/// <summary>
/// 最大命令值, 下面命令不得超过这个值
/// </summary>
C_MAX_ORDER = 10000;
{通用}
C_GET_VERSION = 1; // 获取版本
C_SET_ADDR = 2; // 获取版本
{语音 时钟}
C_VOICE_PLAY = 10; // 播放语音
C_TIME_SET = 11; // 设置时钟
/// <summary>
/// 获取命令码
/// </summary>
function GetControlCode(const nCommType: Integer) : Integer;
/// <summary>
/// 获取设备码
/// </summary>
function GetDevCode(const nCommType: Integer) : Integer;
/// <summary>
/// 获取命令描述
/// </summary>
function GetCommTypeStr(const nCommType: Integer):string;
/// <summary>
/// 根据设备码和命令码获取命令类型
/// </summary>
function GetCommType(nDevCode, nControlCode : Integer) : Integer;
implementation
function GetCommType(nDevCode, nControlCode : Integer) : Integer;
var
i: Integer;
nC1,nC2 : Integer;
begin
Result := -1;
for i := 0 to C_MAX_ORDER do
begin
nC1 := GetDevCode(i);
nC2 := GetControlCode(i);
if (nDevCode = nC1) and (nControlCode = nC2) then
begin
Result := i;
Break;
end;
end;
end;
function GetControlCode(const nCommType: Integer) : Integer;
begin
case nCommType of
C_GET_VERSION : Result:= $01; // 获取版本
C_SET_ADDR : Result:= $02; // 获取版本
{时钟语音}
C_TIME_SET : Result:= $01; // 设置时钟
C_VOICE_PLAY : Result:= $02; // 播放语音
else
Result := $00;
end;
end;
function GetDevCode(const nCommType: Integer) : Integer;
begin
{通用}
if nCommType in [0..9] then
begin
Result := $00;
end
{语音时钟}
else if nCommType in [10..19] then
begin
Result := $01;
end
else
begin
Result := 0;
end;
end;
function GetCommTypeStr(const nCommType: Integer):string;
var
i : Integer;
begin
case nCommType of
C_GET_VERSION : Result:= '获取版本';
{时钟语音}
C_TIME_SET : Result:= '设置时钟';
C_VOICE_PLAY : Result:= '播放语音';
else
Result := '未定义';
end;
if Length(Result) < 25 then
begin
for i := Length(Result) to 25 do
begin
Result := Result + ' ' ;
end;
end;
end;
end.
|
unit SockAppNotify;
{$R-}
interface
uses
Classes, SysUtils, IdTCPClient, idTCPConnection,
SockTransport, IndySockTransport,
HTTPApp, IdUDPServer, IdSocketHandle, IdUDPClient, SyncObjs, Contnrs;
{$IFDEF LINUX}
const
sExecWaitToken = 'webappdbgtoken';
{$ENDIF}
type
TWebAppInfo = class(TObject)
public
Port: Integer;
FileName: string;
LastAccess: Cardinal;
end;
// Listen for running web applications
TRunningWebAppListener = class(TObject)
private
FList: TObjectList;
FLock: TCriticalSection;
FConnection: TIdUDPServer;
procedure OnUDPRead(Sender: TObject; AData: TStream; ABinding: TIdSocketHandle);
procedure RegisterWebApp(APort: Integer; const AProgID, AFileName: string);
procedure UnregisterWebApp(APort: Integer; const AProgID, AFileName: string);
function FindPort(APort: Integer): Integer;
function FindFileName(AFileName: string): Integer;
function GetActive: Boolean;
function GetPort: Integer;
procedure SetActive(const Value: Boolean);
procedure SetPort(const Value: Integer);
public
property Connection: TIdUDPServer read FConnection;
procedure RemovePort(APort: Integer);
function GetPortOfFileName(AFileName: string): Integer;
property Active: Boolean read GetActive write SetActive;
property Port: Integer read GetPort write SetPort;
constructor Create;
destructor Destroy; override;
end;
// Register a running web app
TRunningWebAppNotifier = class(TObject)
private
FAppPort: Integer;
FConnection: TIdUDPClient;
FProgID: string;
FFileName: string;
FSendRegister: Boolean;
FSendInterval: Cardinal;
procedure Send(const AValue: string);
procedure SendRegister;
procedure StartSenderThread;
procedure StopSenderThread;
public
constructor Create(AAppPort: Integer; const AProgID, AFileName: string);
destructor Destroy; override;
procedure Register;
procedure Unregister;
end;
implementation
uses
RTLConsts, SockAppReg, IniFiles, IdGlobal;
const
iDefaultUDPPort = 8090;
iSendInterval = 500;
{ TRunningWebAppListener }
constructor TRunningWebAppListener.Create;
begin
inherited;
FConnection := TIdUDPServer.Create(nil);
FConnection.DefaultPort := iDefaultUDPPort;
FConnection.OnUDPRead := OnUDPRead;
FConnection.ThreadedEvent := True; // No need to synchronize OnUDPRead
FConnection.ReceiveTimeout := 100;
FLock := TCriticalSection.Create;
FList := TObjectList.Create(True { Owns objects });
end;
destructor TRunningWebAppListener.Destroy;
begin
FConnection.Active := False;
FConnection.Free;
FLock.Free;
FList.Free;
inherited;
end;
const
sRegString = 'Command=%s;Port=%d;ProgID=%s;FileName=%s';
sRegisterCommand = 'R';
sUnregisterCommand = 'U';
resourcestring
sUnknownCommand = 'Unknown command';
procedure TRunningWebAppListener.OnUDPRead(Sender: TObject; AData: TStream;
ABinding: TIdSocketHandle);
var
DataStringStream: TStringStream;
S: TStrings;
Command: string;
Port: Integer;
ProgID: string;
FileName: string;
begin
DataStringStream := TStringStream.Create('');
S := TStringList.Create;
try
DataStringStream.CopyFrom(AData, AData.Size);
ExtractStrings([';'],[], PChar(DataStringStream.DataString), S);
Command := S.Values['Command'];
try
Port := StrToInt(S.Values['Port']);
except
Port := 0;
end;
ProgID := S.Values['ProgID'];
FileName := S.Values['FileName'];
if CompareText(Command, sRegisterCommand) = 0 then
RegisterWebApp(Port, ProgID, FileName)
else if CompareText(Command, sUnregisterCommand) = 0 then
UnregisterWebApp(Port, ProgID, FileName)
else
raise Exception.Create(sUnknownCommand);
finally
DataStringStream.Free;
S.Free;
end;
end;
function TRunningWebAppListener.FindPort(APort: Integer): Integer;
var
I: Integer;
begin
FLock.Enter;
try
for I := 0 to FList.Count - 1 do
if TWebAppInfo(FList[I]).Port = APort then
begin
Result := I;
Exit;
end;
Result := -1;
finally
FLock.Leave;
end;
end;
function TRunningWebAppListener.FindFileName(AFileName: string): Integer;
var
I: Integer;
begin
FLock.Enter;
try
for I := 0 to FList.Count - 1 do
if AnsiCompareFileName(TWebAppInfo(FList[I]).FileName, AFileName) = 0 then
begin
Result := I;
Exit;
end;
Result := -1;
finally
FLock.Leave;
end;
end;
function TRunningWebAppListener.GetPortOfFileName(AFileName: string): Integer;
var
I: Integer;
begin
Result := -1;
FLock.Enter;
try
I := FindFileName(AFileName);
if I >= 0 then
begin
with TWebAppInfo(FList[I]) do
Result := TWebAppInfo(FList[I]).Port
end;
finally
FLock.Leave;
end;
end;
procedure TRunningWebAppListener.RegisterWebApp(APort: Integer; const AProgID, AFileName: string);
var
Info: TWebAppInfo;
I: Integer;
begin
// ProgID is not saved
Assert(AFileName <> '');
FLock.Enter;
try
for I := FList.Count - 1 downto 0 do
begin
Info := TWebAppInfo(FList[I]);
if Info.Port = APort then
FList.Delete(I)
else if AnsiCompareFileName(Info.FileName, AFileName) = 0 then
FList.Delete(I);
end;
Info := TWebAppInfo.Create;
try
Info.Port := APort;
Info.FileName := AFileName;
except
Info.Free;
exit;
end;
FList.Add(Info);
finally
FLock.Leave;
end;
end;
procedure TRunningWebAppListener.UnregisterWebApp(APort: Integer; const AProgID, AFileName: string);
begin
RemovePort(APort);
end;
procedure TRunningWebAppListener.RemovePort(APort: Integer);
var
I: Integer;
begin
FLock.Enter;
try
I := FindPort(APort);
if I >= 0 then
FList.Delete(I);
finally
FLock.Leave;
end;
end;
function TRunningWebAppListener.GetActive: Boolean;
begin
Result := FConnection.Active;
end;
function TRunningWebAppListener.GetPort: Integer;
begin
Result := FConnection.DefaultPort;
end;
procedure TRunningWebAppListener.SetActive(const Value: Boolean);
begin
try
FConnection.Active := Value;
if Value = False then
FConnection.Bindings.Clear;
except
FConnection.Bindings.Clear;
Exit;
end;
end;
procedure TRunningWebAppListener.SetPort(const Value: Integer);
begin
FConnection.DefaultPort := Value;
end;
{ TRunningWebAppNotifier }
type
TTimerThread = class(TThread)
private
FSender: TRunningWebAppNotifier;
public
constructor Create(ASender: TRunningWebAppNotifier);
procedure Execute; override;
end;
{ TTimerThread }
constructor TTimerThread.Create(ASender: TRunningWebAppNotifier);
begin
inherited Create(True);
FreeOnTerminate := True;
FSender := ASender;
Resume;
end;
procedure TTimerThread.Execute;
var
SleepTime: Integer;
Last: Cardinal;
begin
while FSender.FSendRegister and (not Terminated) do
begin
try
Last := IdGlobal.GetTickCount;
Synchronize(FSender.SendRegister);
SleepTime := FSender.FSendInterval - (IdGlobal.GetTickCount - Last);
if SleepTime < 10 then SleepTime := 10;
Sleep(SleepTime);
except
end;
end;
end;
constructor TRunningWebAppNotifier.Create(AAppPort: Integer; const AProgID, AFileName: string);
var
Reg: TCustomIniFile;
begin
FAppPort := AAppPort;
FProgID := AProgID;
FFileName := AFileName;
FConnection := TIdUDPClient.Create(nil);
FConnection.Host := '127.0.0.1';
Reg := CreateRegistry;
try
FConnection.Port := Reg.ReadInteger('', sUDPPort, iDefaultUDPPort);
finally
Reg.Free;
end;
inherited Create;
end;
destructor TRunningWebAppNotifier.Destroy;
begin
FConnection.Free;
inherited;
end;
procedure TRunningWebAppNotifier.Register;
begin
StartSenderThread;
end;
procedure TRunningWebAppNotifier.SendRegister;
begin
if FSendRegister then
Send(Format(sRegString, [sRegisterCommand, FAppPort, FProgID, FFileName]));
end;
procedure TRunningWebAppNotifier.StartSenderThread;
begin
Assert(not FSendRegister);
FSendInterval := 200;
FSendRegister := True;
SendRegister;
TTimerThread.Create(Self);
end;
procedure TRunningWebAppNotifier.StopSenderThread;
begin
FSendRegister := False;
end;
procedure TRunningWebAppNotifier.Send(const AValue: string);
begin
FConnection.Active := True;
try
FConnection.Send(AValue);
finally
FConnection.Active := False;
end;
end;
procedure TRunningWebAppNotifier.Unregister;
begin
StopSenderThread;
Send(Format(sRegString, [sUnregisterCommand, FAppPort, FProgID, FFileName]));
end;
end.
|
{ Copyright (C) 1998-2006, written by Shkolnik Mike, Scalabium Software
E-Mail: mshkolnik@scalabium.com
mshkolnik@yahoo.com
WEB: http://www.scalabium.com
}
unit SMToolBar;
interface
{$I SMVersion.inc}
uses Classes, Messages, Windows, Controls, ComCtrls;
type
TSMToolbar = class(TToolbar)
private
FAdjustToolbar: Boolean;
procedure WMNotify(var Message: TWMNotify); message WM_NOTIFY;
procedure CNNotify(var Message: TMessage); message CN_NOTIFY;
protected
procedure CreateParams(var Params: TCreateParams); override;
function GetButtonState(btn: TToolButton): Byte;
function UpdateItem(Message, FromIndex, ToIndex: Integer): Boolean;
function UpdateItem2(Message, FromIndex, ToIndex: Integer): Boolean;
procedure UpdateButtons;
public
procedure Customize;
end;
procedure Register;
implementation
uses CommCtrl, SysUtils;
procedure Register;
begin
RegisterComponents('SMComponents', [TSMToolbar]);
end;
type
TTBButtonInfo = packed record
cbSize: UINT;
dwMask: DWORD;
idCommand: Integer;
iImage: Integer;
fsState: Byte;
fsStyle: Byte;
cx: Word;
lParam: DWORD;
pszText: PAnsiChar;
cchText: Integer;
end;
const
ComCtlDllName = 'comctl32.dll';
ComCtlVersionIE3 = $00040046;
ComCtlVersionIE4 = $00040047;
ComCtlVersionIE401 = $00040048;
ComCtlVersionIE5 = $00050050;
TBIF_IMAGE = $00000001;
TBIF_TEXT = $00000002;
TBIF_STATE = $00000004;
TBIF_STYLE = $00000008;
TBIF_LPARAM = $00000010;
TBIF_COMMAND = $00000020;
TBIF_SIZE = $00000040;
TBSTATE_MARKED = $80;
TBSTYLE_AUTOSIZE = $0010; // automatically calculate the cx of the button
TB_SETBUTTONINFO = WM_USER + 65;
var
ComCtlVersion: Integer;
const
ButtonStates: array[TToolButtonState] of Word = (TBSTATE_CHECKED,
TBSTATE_PRESSED, TBSTATE_ENABLED, TBSTATE_HIDDEN, TBSTATE_INDETERMINATE,
TBSTATE_WRAP
{$IFDEF SMForDelphi4}
, TBSTATE_ELLIPSES, TBSTATE_MARKED
{$ENDIF}
);
ButtonStyles: array[TToolButtonStyle] of Word = (TBSTYLE_BUTTON, TBSTYLE_CHECK,
TBSTYLE_DROPDOWN, TBSTYLE_SEP, TBSTYLE_SEP {$IFDEF SMForDelphi2006}, BTNS_SHOWTEXT {$ENDIF});
function GetComCtlVersion: Integer;
var
FileName: string;
InfoSize, Wnd: DWORD;
VerBuf: Pointer;
FI: PVSFixedFileInfo;
VerSize: DWORD;
begin
if ComCtlVersion = 0 then
begin
// GetFileVersionInfo modifies the filename parameter data while parsing.
// Copy the string const into a local variable to create a writeable copy.
FileName := ComCtlDllName;
InfoSize := GetFileVersionInfoSize(PChar(FileName), Wnd);
if InfoSize <> 0 then
begin
GetMem(VerBuf, InfoSize);
try
if GetFileVersionInfo(PChar(FileName), Wnd, InfoSize, VerBuf) then
if VerQueryValue(VerBuf, '\', Pointer(FI), VerSize) then
ComCtlVersion := FI.dwFileVersionMS;
finally
FreeMem(VerBuf);
end;
end;
end;
Result := ComCtlVersion;
end;
procedure TSMToolbar.CreateParams(var Params: TCreateParams);
begin
inherited;
with Params do
Style := Style or CCS_ADJUSTABLE;
end;
procedure TSMToolbar.WMNotify(var Message: TWMNotify);
var
pnmTB: PNMToolBar;
begin
inherited;
case Message.NMHdr^.Code of
TBN_GETBUTTONINFO:
begin
pnmTB := PNMToolBar(Message.NMHdr);
if pnmTB^.iItem >= ButtonCount then exit;
pnmTB^.tbButton.iBitmap := pnmTB^.iItem;
pnmTB^.tbButton.idCommand := pnmTB^.iItem;
pnmTB^.tbButton.dwData := LongInt(Buttons[pnmTB^.iItem]);
pnmTB^.tbButton.fsState := TBSTATE_ENABLED;
if not Buttons[pnmTB^.iItem].Visible then
pnmTB^.tbButton.fsState := pnmTB^.tbButton.fsState or TB_ISBUTTONHIDDEN;
pnmTB^.tbButton.fsStyle := TBSTYLE_BUTTON;
pnmTB^.tbButton.bReserved[1] := 0;
pnmTB^.tbButton.bReserved[2] := 0;
pnmTB^.tbButton.iString := 0;
Message.Result := 1;
end;
TBN_TOOLBARCHANGE:
begin
// SendMessage(Handle, TB_SAVERESTORE, 1, LongInt(@TBS));
Message.Result:= 1;
end;
TBN_RESET:
begin
// SendMessage(Handle, TB_SAVERESTORE, 0, LongInt(@TBS));{???}
Message.Result:= 1;
end;
TBN_BEGINADJUST, TBN_BEGINDRAG, TBN_ENDDRAG,
TBN_QUERYDELETE, TBN_QUERYINSERT, TBN_ENDADJUST:
begin
Message.Result:= 1;
end;
end;
end;
procedure TSMToolbar.CNNotify(var Message: TMessage);
var
// PButtonNotify: PTagTBNotify;
pnmTB: PNMToolBar;
// Text: string;
begin
inherited;
//exit;
if Message.Result = 1 then exit;
case PNMHdr(Message.LPARAM)^.Code of
TBN_GETBUTTONINFO:
begin
pnmTB := PNMToolBar(PNMHdr(Message.LPARAM));
if pnmTB^.iItem >= ButtonCount then exit;
pnmTB^.tbButton.iBitmap := pnmTB^.iItem;
pnmTB^.tbButton.idCommand := pnmTB^.iItem;
pnmTB^.tbButton.dwData := LongInt(Buttons[pnmTB^.iItem]);
pnmTB^.tbButton.fsState := TBSTATE_ENABLED;
if not Buttons[pnmTB^.iItem].Visible then
pnmTB^.tbButton.fsState := pnmTB^.tbButton.fsState or TB_ISBUTTONHIDDEN;
pnmTB^.tbButton.fsStyle := TBSTYLE_BUTTON;
pnmTB^.tbButton.bReserved[1] := 0;
pnmTB^.tbButton.bReserved[2] := 0;
pnmTB^.tbButton.iString := 0;
Message.Result := 1;
end;
TBN_TOOLBARCHANGE:
begin
// SendMessage(Handle, TB_SAVERESTORE, 1, LongInt(@TBS));
Message.Result:= 1;
end;
TBN_RESET:
begin
// SendMessage(Handle, TB_SAVERESTORE, 0, LongInt(@TBS));{???}
Message.Result:= 1;
end;
TBN_BEGINADJUST, TBN_BEGINDRAG, TBN_ENDDRAG,
TBN_QUERYDELETE, TBN_QUERYINSERT, TBN_ENDADJUST:
begin
Message.Result:= 1;
end;
end;
exit;
Message.Result:=0;
case PNMHdr(Message.LPARAM)^.Code of
TBN_QUERYINSERT: Message.Result := 1;
TBN_QUERYDELETE: begin
if //((FDrag = dr_None) or (FDrag = dr_Custom)) and
(not FAdjustToolbar) then
Message.Result := 0
else
Message.Result := 1;//Longint(CanDelete(PTagTBNotify(Message.LParam).Item));
end;
TBN_GETBUTTONINFO: begin
{ PButtonNotify := PTagTBNotify(Message.LParam);
if (PButtonNotify^.Item < FToolbarButtons.Count) then
begin
PButtonNotify^.TbButton := FToolbarButtons[PButtonNotify^.Item].Buttonrec;
if (PButtonNotify^.cchText <> 0) then
StrCopy(PButtonNotify^.pszText, PChar(FToolbarButtons.Tips[PButtonNotify^.TbButton.IdCommand]+'1'));
Message.Result := 1;
end
else
if (PButtonNotify^.Item - FToolbarButtons.Count < FAvailableButtons.Count) then
begin
PButtonNotify^.TBButton := FAvailableButtons[PButtonNotify^.Item - FToolbarButtons.Count].ButtonRec;
if (PButtonNotify^.cchText <> 0) then
StrCopy(PButtonNotify^.pszText, PChar(FAvailableButtons.Tips[PButtonNotify^.TbButton.IdCommand]+'2'));
Message.Result := 1;
end
else
} Message.Result := 0;
end;
TBN_BEGINADJUST: begin
FAdjustToolbar := True;
// if Assigned(FOnBeginADJUST) then
// FOnBeginADJUST(Self);
end;
TBN_ENDADJUST: begin
FAdjustToolbar:=False;
// UpdateButtons;
SendMessage(Handle, TB_AutoSize, 0, 0);
Parent.ReAlign;
// if Assigned(FOnENDADJUST) then
// FOnENDADJUST(Self);
end;
TBN_BEGINDRAG: begin
Message.Result := 0;
{ if Assigned(FOnBeginDrag) then
FOnBeginDrag(Self);
} end;
TBN_ENDDRAG: begin
{ if Assigned(FOnEndDrag) then
FOnEndDrag(Self);
} Message.Result := 0;
end;
TBN_TOOLBARCHANGE: begin
if not FAdjustToolbar then
UpdateButtons;
SendMessage(Handle, TB_AutoSize, 0, 0);
Parent.ReAlign;
// if Assigned(FOnTOOLBARCHANGE) then
// FOnTOOLBARCHANGE(Self);
end;
TBN_RESET: begin
{ RestoreResetInfo;
if Assigned(FOnReset) then
FOnReset(Self);
} end;
TBN_CUSTHELP: begin
{ if Assigned(FOnHelp) then
FOnHelp(Self);
} end;
else
end;
end;
function TSMToolBar.GetButtonState(btn: TToolButton): Byte;
begin
Result := 0;
if btn.Down then
if btn.Style = tbsCheck then
Result := Result or ButtonStates[tbsChecked]
else
Result := Result or ButtonStates[tbsPressed];
if btn.Enabled {and ((ToolBar = nil) or ToolBar.Enabled) }then
Result := Result or ButtonStates[tbsEnabled];
if not btn.Visible and not (csDesigning in btn.ComponentState) then
Result := Result or ButtonStates[tbsHidden];
// if Indeterminate then Result := Result or ButtonStates[tbsIndeterminate];
// if Wrap then Result := Result or ButtonStates[tbsWrap];
// if Marked then Result := Result or ButtonStates[tbsMarked];
end;
function TSMToolBar.UpdateItem(Message, FromIndex, ToIndex: Integer): Boolean;
var
Control: TControl;
Button: TTBButton;
CaptionText: string;
Buffer: array[0..4095] of Char;
begin
Control := TControl(Buttons[FromIndex]);
if Control is TToolButton then
with TToolButton(Control) do
begin
FillChar(Button, SizeOf(Button), 0);
if Style in [tbsSeparator, tbsDivider] then
begin
Button.iBitmap := Width;
Button.idCommand := -1;
end
else
begin
if ImageIndex < 0 then
Button.iBitmap := -2 else
Button.iBitmap := ImageIndex;
Button.idCommand := FromIndex;
end;
with Button do
begin
fsStyle := ButtonStyles[Style];
if AutoSize and (GetComCtlVersion >= ComCtlVersionIE4) then
fsStyle := fsStyle or TBSTYLE_AUTOSIZE;
end;
Button.fsState := GetButtonState(TToolButton(Control));
if Grouped then Button.fsStyle := Button.fsStyle or TBSTYLE_GROUP;
Button.dwData := Longint(Control);
if ShowCaptions then
begin
if Caption <> '' then
CaptionText := Caption
else
{ Common control requries at least a space is used when showing button
captions. If any one button's caption is empty (-1) then none of
the buttons' captions will not be displayed. }
CaptionText := ' ';
StrPCopy(Buffer, CaptionText);
{ TB_ADDSTRING requires two null terminators }
Buffer[Length(CaptionText) + 1] := #0;
Button.iString := Self.Perform(TB_ADDSTRING, 0, Longint(@Buffer));
end
else
Button.iString := -1;
end
else
begin
FillChar(Button, SizeOf(Button), 0);
Button.fsStyle := ButtonStyles[tbsSeparator];
Button.iBitmap := Control.Width;
Button.idCommand := -1;
if not Control.Visible and not (csDesigning in Control.ComponentState) then
Button.fsState := Button.fsState or ButtonStates[tbsHidden];
Button.dwData := Longint(Control);
Button.iString := -1;
end;
Result := Self.Perform(Message, ToIndex, Integer(@Button)) <> 0;
end;
function TSMToolBar.UpdateItem2(Message, FromIndex, ToIndex: Integer): Boolean;
var
Control: TControl;
Button: TTBButtonInfo;
CaptionText: string;
Buffer: array[0..4095] of Char;
begin
Control := TControl(Buttons[FromIndex]);
FillChar(Button, SizeOf(Button), 0);
Button.cbSize := SizeOf(Button);
if Control is TToolButton then
with TToolButton(Control) do
begin
Button.dwMask := TBIF_STATE or TBIF_STYLE or TBIF_LPARAM or TBIF_COMMAND
or TBIF_SIZE;
if Style in [tbsSeparator, tbsDivider] then
begin
Button.idCommand := -1;
end
else
begin
Button.dwMask := Button.dwMask or TBIF_IMAGE;
if ImageIndex < 0 then
Button.iImage := -2 else
Button.iImage := ImageIndex;
Button.idCommand := FromIndex;
end;
with Button do
begin
cx := Width;
fsStyle := ButtonStyles[Style];
if AutoSize then fsStyle := fsStyle or TBSTYLE_AUTOSIZE;
if Grouped then Button.fsStyle := Button.fsStyle or TBSTYLE_GROUP;
end;
Button.fsState := GetButtonState(TToolButton(Control));
Button.lParam := Longint(Control);
if ShowCaptions then
begin
if Caption <> '' then
CaptionText := Caption
else
{ Common control requries at least a space is used when showing button
captions. If any one button's caption is empty (-1) then none of
the buttons' captions will not be displayed. }
CaptionText := ' ';
StrPCopy(Buffer, CaptionText);
{ TB_ADDSTRING requires two null terminators }
Buffer[Length(CaptionText) + 1] := #0;
//Button.iString := Self.Perform(TB_ADDSTRING, 0, Longint(@Buffer));
Button.pszText := Buffer;
Button.cchText := Length(CaptionText);
Button.dwMask := Button.dwMask or TBIF_TEXT;
end
else
begin
Button.pszText := nil;
Button.cchText := 0;
end;
if Style in [tbsSeparator, tbsDivider] then
begin
with Button do
begin
dwMask := TBIF_STYLE or TBIF_STATE or TBIF_LPARAM;
fsState := TBSTATE_ENABLED or TBSTATE_WRAP;
fsStyle := TBSTYLE_BUTTON;
end;
end;
end
else
begin
Button.dwMask := TBIF_TEXT or TBIF_STATE or TBIF_STYLE or TBIF_LPARAM or
TBIF_COMMAND or TBIF_SIZE;
Button.fsStyle := ButtonStyles[tbsSeparator];
Button.cx := Control.Width;
Button.idCommand := -1;
Button.lParam := Longint(Control);
Button.pszText := nil;
Button.cchText := 0;
end;
Result := Self.Perform(Message, ToIndex, Integer(@Button)) <> 0;
end;
procedure TSMToolBar.UpdateButtons;
const
BlankButton: TTBButton = (iBitmap: 0; idCommand: 0; fsState: 0;
fsStyle: TBSTYLE_BUTTON; dwData: 0; iString: 0);
var
i: Integer;
Count: Integer;
Style: Longint;
begin
try
HandleNeeded;
Style := GetWindowLong(Handle, GWL_STYLE);
SetWindowLong(Handle, GWL_STYLE, Style and not WS_VISIBLE);
try
Count := ButtonCount;
for i := 0 to ButtonCount - 1 do
begin
if i < Count then
UpdateItem2(TB_SETBUTTONINFO, i, i)
else
UpdateItem(TB_INSERTBUTTON, i, i);
end;
finally
SetWindowLong(Handle, GWL_STYLE, Style);
end;
finally
end;
RepositionButtons(0);
end;
procedure TSMToolbar.Customize;
begin
SendMessage(Self.Handle, TB_CUSTOMIZE, 0, 0);
end;
{Mab heeft geschreven in bericht <68rkgc$ict@Alf.ho.bunge.com.au>...
>Hi all,
>
>I've been experimenting with the TB_CUSTOMIZE message and TToolbar.
>Here's how far I got:
>
>1. Created a new component, descended from TToolbar, and added
>CCS_ADJUSTABLE to its create params.
>
>2. Added a WM_NOTIFY handler to my main form, and checked for
>TBN_QUERYINSERT, returning 1 all the time.
>
>Sweet! Now when I double click on the toolbar, I get a cute "customize
>toolbar" dialog pop up!
>
>Only problem is getting the buttons to appear in the dialog. Has
>anyone successfully handled the TBN_GETBUTTONINFO message? How do I do
>it?
>
>If you'd like to look at this yourself (it took me about an hour to
>figure out the above) then look up TB_CUSTOMIZE in the Win32 API help
>file.
>
>Email me if you'd like to create a customizable toolbar component with
>me!
}
end.
|
unit frmUserList;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Actions, Vcl.ActnList,
Vcl.XPStyleActnCtrls, Vcl.ActnMan, Vcl.Menus, Vcl.ComCtrls, uUserInfo;
type
TfUserList = class(TForm)
lv1: TListView;
pm1: TPopupMenu;
NewUser2: TMenuItem;
N3: TMenuItem;
ChangePassword2: TMenuItem;
EditUser1: TMenuItem;
DeleteUser2: TMenuItem;
N4: TMenuItem;
Refresh2: TMenuItem;
actmgr1: TActionManager;
actNewUser: TAction;
actRefresh: TAction;
actChangePassword: TAction;
actDeleteUser: TAction;
actEditUser: TAction;
procedure actNewUserExecute(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure actRefreshExecute(Sender: TObject);
procedure actEditUserExecute(Sender: TObject);
procedure actDeleteUserExecute(Sender: TObject);
procedure actChangePasswordExecute(Sender: TObject);
private
{ Private declarations }
procedure AddUserList(AUser : TUser);
procedure LoadData;
public
{ Public declarations }
end;
var
fUserList: TfUserList;
implementation
uses
frmUserNew, uUserControl, uUpUsPass;
{$R *.dfm}
procedure TfUserList.actChangePasswordExecute(Sender: TObject);
var
lvItem : TListItem;
begin
lvItem := lv1.Selected;
if lvItem <> nil then
begin
if Assigned(UserControl) then
begin
UserControl.UserUpass(TUser(lvItem.Data));
end;
end;
end;
procedure TfUserList.actDeleteUserExecute(Sender: TObject);
var
AUser : TUser;
begin
if lv1.Selected <> nil then
begin
if MessageBox(0, '确认要删除选择的记录吗?', '提示',
MB_YESNO + MB_ICONQUESTION) = IDYES then
begin
AUser := TUser(lv1.Selected.Data);
if Assigned(UserControl) then
begin
UserControl.DelUser(AUser);
lv1.DeleteSelected;
ShowMessage('删除用户成功!');
end
else
ShowMessage('删除用户失败');
end;
end;
end;
procedure TfUserList.actEditUserExecute(Sender: TObject);
var
AUser : TUser;
lvSel : TListItem;
begin
if lv1.ItemIndex <> -1 then
begin
lvSel := lv1.Selected;
AUser := TUser(lvSel.Data);
with TfUserNew.Create(nil) do
begin
ShowInfo(AUser);
if ShowModal = mrOk then
begin
SaveInfo;
if Assigned(UserControl) then
begin
UserControl.SaveUser(AUser);
with lvSel do
begin
Caption := AUser.LoginName;
SubItems[0] := AUser.FullName;
SubItems[1] := AUser.Description;
Data := AUser;
end;
MessageBox(0, '编辑成功!', '提示', MB_OK);
end;
end;
Free;
end;
end
else
begin
MessageBox(0, '请选择需要编辑的用户!', '提示', MB_OK);
end;
end;
procedure TfUserList.actNewUserExecute(Sender: TObject);
var
AUser : TUser;
begin
with TfUserNew.Create(nil) do
begin
AUser := TUser.Create;
ShowInfo(AUser);
if ShowModal = mrOk then
begin
SaveInfo;
if Assigned(UserControl) then
begin
UserControl.SaveUser(AUser);
AddUserList(AUser);
MessageBox(0, '保存成功!', '提示', MB_OK);
end;
end;
Free;
end;
end;
procedure TfUserList.actRefreshExecute(Sender: TObject);
begin
LoadData;
end;
procedure TfUserList.AddUserList(AUser: TUser);
begin
if Assigned(AUser) then
begin
with lv1.Items.Add, AUser do
begin
Caption := AUser.LoginName;
SubItems.Add(AUser.FullName);
SubItems.Add(AUser.Description);
Data := AUser;
end;
end;
end;
procedure TfUserList.FormShow(Sender: TObject);
begin
LoadData;
end;
procedure TfUserList.LoadData;
var
i : integer;
begin
lv1.Items.Clear;
if Assigned(UserControl) then
begin
with UserControl.UserList do
begin
for i := 0 to Count - 1 do
AddUserList(TUser(Objects[i]));
end;
end;
if lv1.Items.Count > 0 then
lv1.ItemIndex := 0;
end;
end.
|
{$INCLUDE ..\cDefines.inc}
unit cWriters;
{ }
{ Writers v3.03 }
{ }
{ This unit is copyright © 2002-2004 by David J Butler }
{ }
{ This unit is part of Delphi Fundamentals. }
{ Its original file name is cWriters.pas }
{ The latest version is available from the Fundamentals home page }
{ http://fundementals.sourceforge.net/ }
{ }
{ I invite you to use this unit, free of charge. }
{ I invite you to distibute this unit, but it must be for free. }
{ I also invite you to contribute to its development, }
{ but do not distribute a modified copy of this file. }
{ }
{ A forum is available on SourceForge for general discussion }
{ http://sourceforge.net/forum/forum.php?forum_id=2117 }
{ }
{ }
{ Revision history: }
{ 12/05/2002 3.01 Created cWriters unit from cStreams. }
{ AWriter, TFileWriter. }
{ 29/03/2003 3.02 Added TStringWriter. }
{ 21/02/2004 3.03 Added TWideStringWriter. }
{ }
interface
uses
{ Delphi }
Windows,
SysUtils;
{ }
{ AWriter }
{ Writer abstract base class. }
{ }
type
AWriter = class
protected
function GetPosition: Int64; virtual; abstract;
procedure SetPosition(const Position: Int64); virtual; abstract;
function GetSize: Int64; virtual; abstract;
procedure SetSize(const Size: Int64); virtual; abstract;
public
function Write(const Buffer; const Size: Integer): Integer; virtual; abstract;
property Position: Int64 read GetPosition write SetPosition;
property Size: Int64 read GetSize write SetSize;
end;
EWriter = class(Exception);
{ }
{ AWriterEx }
{ Base class for Writer implementations. AWriteEx extends AWriter with }
{ commonly used functions. }
{ }
{ All methods in AWriterEx are implemented using calls to the abstract }
{ methods in AWriter. Writer implementations can override the virtual }
{ methods in AWriterEx with more efficient versions. }
{ }
type
TWriterNewLineType = (nlCR, nlLF, nlCRLF, nlLFCR);
AWriterEx = class(AWriter)
protected
function GetPosition: Int64; override;
procedure SetPosition(const Position: Int64); override;
function GetSize: Int64; override;
procedure SetSize(const Size: Int64); overload; override;
procedure SetAsString(const S: String); virtual;
procedure SetAsWideString(const S: WideString); virtual;
public
procedure RaiseWriteError;
procedure Append;
procedure Truncate; virtual;
procedure Clear; virtual;
property AsString: String write SetAsString;
property AsWideString: WideString write SetAsWideString;
procedure WriteBuffer(const Buffer; const Size: Integer);
procedure WriteStr(const Buffer: String); virtual;
procedure WriteWideStr(const Buffer: WideString); virtual;
procedure WriteByte(const V: Byte); virtual;
procedure WriteWord(const V: Word); virtual;
procedure WriteLongWord(const V: LongWord);
procedure WriteLongInt(const V: LongInt);
procedure WriteInt64(const V: Int64);
procedure WriteSingle(const V: Single);
procedure WriteDouble(const V: Double);
procedure WriteExtended(const V: Extended);
procedure WritePackedString(const V: String);
procedure WritePackedStringArray(const V: Array of String);
procedure WritePackedWideString(const V: WideString);
procedure WriteBufLine(const Buffer; const Size: Integer;
const NewLineType: TWriterNewLineType = nlCRLF);
procedure WriteLine(const S: String;
const NewLineType: TWriterNewLineType = nlCRLF);
end;
{ }
{ TFileWriter }
{ Writer implementation for a file. }
{ }
type
TFileWriterOpenMode = (fwomOpen, // Open existing
fwomTruncate, // Open existing and truncate
fwomCreate, // Always create
fwomCreateIfNotExist); // Create if not exist else open existing
TFileWriterAccessHint = (
fwahNone,
fwahRandomAccess,
fwahSequentialAccess);
TFileWriterOptions = Set of (
fwoWriteThrough);
TFileWriter = class(AWriterEx)
protected
FFileName : String;
FHandle : Integer;
FHandleOwner : Boolean;
FFileCreated : Boolean;
function GetPosition: Int64; override;
procedure SetPosition(const Position: Int64); override;
function GetSize: Int64; override;
procedure SetSize(const Size: Int64); override;
public
constructor Create(const FileName: String;
const OpenMode: TFileWriterOpenMode = fwomCreateIfNotExist;
const Options: TFileWriterOptions = [];
const AccessHint: TFileWriterAccessHint = fwahNone); overload;
constructor Create(const FileHandle: Integer; const HandleOwner: Boolean); overload;
destructor Destroy; override;
property Handle: Integer read FHandle;
property HandleOwner: Boolean read FHandleOwner;
property FileCreated: Boolean read FFileCreated;
function Write(const Buffer; const Size: Integer): Integer; override;
procedure Flush;
procedure DeleteFile;
end;
EFileWriter = class(EWriter);
procedure WriteStrToFile(const FileName: String; const S: String;
const OpenMode: TFileWriterOpenMode = fwomCreate);
procedure AppendStrToFile(const FileName: String; const S: String);
procedure WriteWideStrToFile(const FileName: String; const S: WideString;
const OpenMode: TFileWriterOpenMode = fwomCreate);
procedure AppendWideStrToFile(const FileName: String; const S: WideString);
{ }
{ TStringWriter }
{ Writer implementation for a dynamic string. }
{ }
type
TStringWriter = class(AWriterEx)
protected
FData : String;
FSize : Integer;
FPos : Integer;
function GetPosition: Int64; override;
procedure SetPosition(const Position: Int64); override;
function GetSize: Int64; override;
procedure SetSize(const Size: Int64); overload; override;
procedure SetSize(const Size: Integer); overload;
function GetAsString: String;
procedure SetAsString(const S: String); override;
public
property DataString: String read FData;
property DataSize: Integer read FSize;
property AsString: String read GetAsString write SetAsString;
function Write(const Buffer; const Size: Integer): Integer; override;
procedure WriteStr(const Buffer: String); override;
procedure WriteByte(const V: Byte); override;
end;
{ }
{ TWideStringWriter }
{ Writer implementation for a wide string. }
{ }
type
TWideStringWriter = class(AWriterEx)
protected
FData : WideString;
FSize : Integer;
FPos : Integer;
function GetPosition: Int64; override;
procedure SetPosition(const Position: Int64); override;
function GetSize: Int64; override;
procedure SetSize(const Size: Int64); overload; override;
procedure SetSize(const Size: Integer); overload;
function GetAsWideString: WideString;
procedure SetAsWideString(const S: WideString); override;
public
property DataString: WideString read FData;
property DataSize: Integer read FSize;
property AsWideString: WideString read GetAsWideString write SetAsWideString;
function Write(const Buffer; const Size: Integer): Integer; override;
procedure WriteStr(const Buffer: String); override;
procedure WriteWideStr(const Buffer: WideString); override;
procedure WriteByte(const V: Byte); override;
procedure WriteWord(const V: Word); override;
end;
{ }
{ TOutputWriter }
{ Writer implementation for standard system output. }
{ }
type
TOutputWriter = class(AWriterEx)
public
function Write(const Buffer; const Size: Integer): Integer; override;
end;
implementation
{ }
{ AWriterEx }
{ }
procedure AWriterEx.RaiseWriteError;
begin
raise EWriter.Create('Write error');
end;
function AWriterEx.GetPosition: Int64;
begin
raise EWriter.Create('Abstract error: GetPosition');
end;
procedure AWriterEx.SetPosition(const Position: Int64);
begin
raise EWriter.Create('Abstract error: SetPosition');
end;
function AWriterEx.GetSize: Int64;
begin
raise EWriter.Create('Abstract error: GetSize');
end;
procedure AWriterEx.SetSize(const Size: Int64);
begin
raise EWriter.Create('Abstract error: SetSize');
end;
procedure AWriterEx.Append;
begin
Position := Size;
end;
procedure AWriterEx.Truncate;
begin
Size := Position;
end;
procedure AWriterEx.Clear;
begin
Size := 0;
end;
procedure AWriterEx.WriteBuffer(const Buffer; const Size: Integer);
begin
if Size <= 0 then
exit;
if Write(Buffer, Size) <> Size then
RaiseWriteError;
end;
procedure AWriterEx.WriteStr(const Buffer: String);
begin
WriteBuffer(Pointer(Buffer)^, Length(Buffer));
end;
procedure AWriterEx.WriteWideStr(const Buffer: WideString);
begin
WriteBuffer(Pointer(Buffer)^, Length(Buffer) * Sizeof(WideChar));
end;
procedure AWriterEx.SetAsString(const S: String);
begin
Position := 0;
WriteStr(S);
Truncate;
end;
procedure AWriterEx.SetAsWideString(const S: WideString);
begin
Position := 0;
WriteWideStr(S);
Truncate;
end;
procedure AWriterEx.WriteByte(const V: Byte);
begin
WriteBuffer(V, Sizeof(Byte));
end;
procedure AWriterEx.WriteWord(const V: Word);
begin
WriteBuffer(V, Sizeof(Word));
end;
procedure AWriterEx.WriteLongWord(const V: LongWord);
begin
WriteBuffer(V, Sizeof(LongWord));
end;
procedure AWriterEx.WriteLongInt(const V: LongInt);
begin
WriteBuffer(V, Sizeof(LongInt));
end;
procedure AWriterEx.WriteInt64(const V: Int64);
begin
WriteBuffer(V, Sizeof(Int64));
end;
procedure AWriterEx.WriteSingle(const V: Single);
begin
WriteBuffer(V, Sizeof(Single));
end;
procedure AWriterEx.WriteDouble(const V: Double);
begin
WriteBuffer(V, Sizeof(Double));
end;
procedure AWriterEx.WriteExtended(const V: Extended);
begin
WriteBuffer(V, Sizeof(Extended));
end;
procedure AWriterEx.WritePackedString(const V: String);
begin
WriteLongInt(Length(V));
WriteStr(V);
end;
procedure AWriterEx.WritePackedStringArray(const V: Array of String);
var I, L : Integer;
begin
L := Length(V);
WriteLongInt(L);
For I := 0 to L - 1 do
WritePackedString(V[I]);
end;
procedure AWriterEx.WritePackedWideString(const V: WideString);
begin
WriteLongInt(Length(V));
WriteWideStr(V);
end;
procedure AWriterEx.WriteBufLine(const Buffer; const Size: Integer;
const NewLineType: TWriterNewLineType);
begin
WriteBuffer(Buffer, Size);
Case NewLineType of
nlCR : WriteByte(13);
nlLF : WriteByte(10);
nlCRLF : WriteStr(#13#10);
nlLFCR : WriteStr(#10#13);
end;
end;
procedure AWriterEx.WriteLine(const S: String; const NewLineType: TWriterNewLineType);
begin
WriteBufLine(Pointer(S)^, Length(S), NewLineType);
end;
{ }
{ TFileWriter }
{ }
{$IFNDEF DELPHI6_UP}
procedure RaiseLastOSError;
begin
{$IFDEF FREEPASCAL}
raise Exception.Create('OS Error');
{$ELSE}
RaiseLastWin32Error;
{$ENDIF}
end;
{$ENDIF}
constructor TFileWriter.Create(const FileName: String;
const OpenMode: TFileWriterOpenMode; const Options: TFileWriterOptions;
const AccessHint: TFileWriterAccessHint);
var CreateFile : Boolean;
{$IFDEF OS_WIN32}
F : LongWord;
{$ENDIF}
begin
inherited Create;
FFileName := FileName;
Case OpenMode of
fwomCreate : CreateFile := True;
fwomCreateIfNotExist : CreateFile := not FileExists(FileName);
else
CreateFile := False;
end;
{$IFDEF OS_WIN32}
F := FILE_ATTRIBUTE_NORMAL;
Case AccessHint of
fwahNone : ;
fwahRandomAccess : F := F or FILE_FLAG_RANDOM_ACCESS;
fwahSequentialAccess : F := F or FILE_FLAG_SEQUENTIAL_SCAN;
end;
if fwoWriteThrough in Options then
F := F or FILE_FLAG_WRITE_THROUGH;
if CreateFile then
FHandle := Integer(Windows.CreateFile(PChar(FileName),
GENERIC_READ or GENERIC_WRITE, 0, nil, CREATE_ALWAYS, F, 0))
else
FHandle := Integer(Windows.CreateFile(PChar(FileName),
GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, F, 0));
{$ELSE}
if CreateFile then
FHandle := FileCreate(FileName)
else
FHandle := FileOpen(FileName, fmOpenReadWrite);
{$ENDIF}
if FHandle = -1 then
RaiseLastOSError;
FHandleOwner := True;
FFileCreated := CreateFile;
if OpenMode = fwomTruncate then
if not SetEndOfFile(FHandle) then
raise EFileWriter.Create('File truncate error');
end;
constructor TFileWriter.Create(const FileHandle: Integer; const HandleOwner: Boolean);
begin
inherited Create;
FHandle := FileHandle;
FHandleOwner := HandleOwner;
end;
destructor TFileWriter.Destroy;
begin
if FHandleOwner and (FHandle <> -1) and (FHandle <> 0) then
FileClose(FHandle);
inherited Destroy;
end;
function TFileWriter.GetPosition: Int64;
begin
Result := FileSeek(FHandle, Int64(0), 1);
if Result = -1 then
raise EFileWriter.Create('File error');
end;
procedure TFileWriter.SetPosition(const Position: Int64);
begin
if FileSeek(FHandle, Position, 0) = -1 then
raise EFileWriter.Create('File seek error');
end;
function TFileWriter.GetSize: Int64;
var I : Int64;
begin
I := GetPosition;
Result := FileSeek(FHandle, Int64(0), 2);
SetPosition(I);
if Result = -1 then
raise EFileWriter.Create('File error');
end;
procedure TFileWriter.SetSize(const Size: Int64);
begin
SetPosition(Size);
if not SetEndOfFile(FHandle) then
raise EFileWriter.Create('File resize error');
end;
function TFileWriter.Write(const Buffer; const Size: Integer): Integer;
var I : Integer;
begin
if Size <= 0 then
begin
Result := 0;
exit;
end;
I := FileWrite(FHandle, Buffer, Size);
if I < 0 then
RaiseLastOSError;
Result := I;
end;
procedure TFileWriter.Flush;
begin
if not FlushFileBuffers(FHandle) then
RaiseLastOSError;
end;
procedure TFileWriter.DeleteFile;
begin
if FFileName = '' then
raise EFileWriter.Create('No filename');
if (FHandle <> -1) and (FHandle <> 0) then
FileClose(FHandle);
FHandle := -1;
SysUtils.DeleteFile(FFileName);
end;
procedure WriteStrToFile(const FileName: String; const S: String;
const OpenMode: TFileWriterOpenMode);
var F : TFileWriter;
begin
F := TFileWriter.Create(FileName, OpenMode);
try
F.SetAsString(S);
finally
F.Free;
end;
end;
procedure AppendStrToFile(const FileName: String; const S: String);
var F : TFileWriter;
begin
F := TFileWriter.Create(FileName, fwomCreateIfNotExist);
try
F.Append;
F.WriteStr(S);
finally
F.Free;
end;
end;
procedure WriteWideStrToFile(const FileName: String; const S: WideString;
const OpenMode: TFileWriterOpenMode);
var F : TFileWriter;
begin
F := TFileWriter.Create(FileName, OpenMode);
try
F.SetAsWideString(S);
finally
F.Free;
end;
end;
procedure AppendWideStrToFile(const FileName: String; const S: WideString);
var F : TFileWriter;
begin
F := TFileWriter.Create(FileName, fwomCreateIfNotExist);
try
F.Append;
F.WriteWideStr(S);
finally
F.Free;
end;
end;
{ }
{ TStringWriter }
{ }
function TStringWriter.GetPosition: Int64;
begin
Result := FPos;
end;
procedure TStringWriter.SetPosition(const Position: Int64);
begin
if (Position < 0) or (Position > High(Integer)) then
raise EFileWriter.Create('Invalid position');
FPos := Integer(Position);
end;
function TStringWriter.GetSize: Int64;
begin
Result := FSize;
end;
procedure TStringWriter.SetSize(const Size: Integer);
var L : Integer;
begin
if Size = FSize then
exit;
L := Length(FData);
if Size > L then
begin
// memory allocation strategy
if L = 0 then // first allocation is exactly as request
L := Size else
if Size < 16 then // if grow to < 16 then allocate 16
L := 16 else
L := Size + (Size shr 2); // if grow to > 16 then pre-allocate 1/4
SetLength(FData, L);
end;
FSize := Size;
end;
procedure TStringWriter.SetSize(const Size: Int64);
begin
if Size > High(Integer) then
raise EFileWriter.Create('Invalid size');
SetSize(Integer(Size));
end;
function TStringWriter.GetAsString: String;
var L : Integer;
begin
L := Length(FData);
if L = FSize then
Result := FData else
Result := Copy(FData, 1, FSize);
end;
procedure TStringWriter.SetAsString(const S: String);
begin
FData := S;
FSize := Length(S);
FPos := FSize;
end;
function TStringWriter.Write(const Buffer; const Size: Integer): Integer;
var I, J : Integer;
P : PChar;
begin
if Size <= 0 then
begin
Result := 0;
exit;
end;
I := FPos;
J := I + Size;
if J > FSize then
SetSize(J);
P := Pointer(FData);
Inc(P, I);
Move(Buffer, P^, Size);
Result := Size;
FPos := J;
end;
procedure TStringWriter.WriteStr(const Buffer: String);
begin
Write(Pointer(Buffer)^, Length(Buffer));
end;
procedure TStringWriter.WriteByte(const V: Byte);
var I, J : Integer;
P : PChar;
begin
I := FPos;
J := I + 1;
if J > FSize then
SetSize(J);
P := Pointer(FData);
Inc(P, I);
PByte(P)^ := V;
FPos := J;
end;
{ }
{ TWideStringWriter }
{ }
function TWideStringWriter.GetPosition: Int64;
begin
Result := FPos;
end;
procedure TWideStringWriter.SetPosition(const Position: Int64);
begin
if (Position < 0) or (Position > High(Integer)) then
raise EFileWriter.Create('Invalid position');
FPos := Integer(Position);
end;
function TWideStringWriter.GetSize: Int64;
begin
Result := FSize;
end;
procedure TWideStringWriter.SetSize(const Size: Integer);
var L : Integer;
begin
if Size = FSize then
exit;
L := Length(FData) * Sizeof(WideChar);
if Size > L then
begin
// memory allocation strategy
if L = 0 then // first allocation is exactly as request
L := Size else
if Size < 16 then // if grow to < 16 then allocate 16
L := 16 else
L := Size + (Size shr 2); // if grow to > 16 then pre-allocate 1/4
SetLength(FData, (L + 1) div Sizeof(WideChar));
end;
FSize := Size;
end;
procedure TWideStringWriter.SetSize(const Size: Int64);
begin
if Size > High(Integer) then
raise EFileWriter.Create('Invalid size');
SetSize(Integer(Size));
end;
function TWideStringWriter.GetAsWideString: WideString;
var L : Integer;
begin
L := Length(FData) * Sizeof(WideChar);
if L = FSize then
Result := FData else
Result := Copy(FData, 1, FSize div Sizeof(WideChar));
end;
procedure TWideStringWriter.SetAsWideString(const S: WideString);
begin
FData := S;
FSize := Length(S) * Sizeof(WideChar);
FPos := FSize;
end;
function TWideStringWriter.Write(const Buffer; const Size: Integer): Integer;
var I, J : Integer;
P : PChar;
begin
if Size <= 0 then
begin
Result := 0;
exit;
end;
I := FPos;
J := I + Size;
if J > FSize then
SetSize(J);
P := Pointer(FData);
Inc(P, I);
Move(Buffer, P^, Size);
Result := Size;
FPos := J;
end;
procedure TWideStringWriter.WriteStr(const Buffer: String);
begin
Write(Pointer(Buffer)^, Length(Buffer));
end;
procedure TWideStringWriter.WriteWideStr(const Buffer: WideString);
begin
Write(Pointer(Buffer)^, Length(Buffer) * Sizeof(WideChar));
end;
procedure TWideStringWriter.WriteByte(const V: Byte);
var I, J : Integer;
P : PChar;
begin
I := FPos;
J := I + 1;
if J > FSize then
SetSize(J);
P := Pointer(FData);
Inc(P, I);
PByte(P)^ := V;
FPos := J;
end;
procedure TWideStringWriter.WriteWord(const V: Word);
var I, J : Integer;
P : PChar;
begin
I := FPos;
J := I + 2;
if J > FSize then
SetSize(J);
P := Pointer(FData);
Inc(P, I);
PWord(P)^ := V;
FPos := J;
end;
{ }
{ TOutputWriter }
{ }
function TOutputWriter.Write(const Buffer; const Size: Integer): Integer;
var I : Integer;
P : PByte;
begin
if Size <= 0 then
begin
Result := 0;
exit;
end;
P := @Buffer;
For I := 1 to Size do
begin
System.Write(Char(P^));
Inc(P);
end;
Result := Size;
end;
end.
|
unit uGBProcura;
interface
uses
System.SysUtils, System.Classes, Vcl.Controls, Vcl.ExtCtrls, uGBMontaSelect,
Data.DB, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.Forms;
type
TGBProcura = class(TPanel)
private
_edit : TEdit;
_btn : TBitBtn;
_MS : TGBMontaSelect;
FLookupChave: Variant;
FDataSource: TDataSource;
FDataField: string;
FLookupDescricao: string;
FLookupTabela: string;
FReadOnly: boolean;
FMontaSelect: TGBMontaSelect;
procedure SetLookupChave(const Value: Variant);
procedure setReadOnly(const Value: boolean);
procedure configuraPanel;
procedure configuraEdit;
procedure configuraBtn;
////////////////////////////////////////////////////////////////////////////
/// Edit
////////////////////////////////////////////////////////////////////////////
procedure editChange(Sender: TObject);
////////////////////////////////////////////////////////////////////////////
/// BitBtn
////////////////////////////////////////////////////////////////////////////
procedure btnClick(Sender: TObject);
procedure SetMontaSelect(const Value: TGBMontaSelect);
{ Private declarations }
protected
{ Protected declarations }
public
constructor Create(AOwner: TComponent); override;
{ Public declarations }
published
property DataSource : TDataSource read FDataSource write FDataSource;
property DataField : string read FDataField write FDataField;
property LookupTabela : string read FLookupTabela write FLookupTabela;
property LookupDescricao : string read FLookupDescricao write FLookupDescricao;
property LookupChave : Variant read FLookupChave write SetLookupChave;
property ReadOnly : boolean read FReadOnly write setReadOnly default False;
property MontaSelect : TGBMontaSelect read FMontaSelect write SetMontaSelect;
{ Published declarations }
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Gabalt10', [TGBProcura]);
end;
{ TGBProcura }
procedure TGBProcura.btnClick(Sender: TObject);
begin
if MontaSelect <> nil then
begin
MontaSelect.executar;
if MontaSelect.RetornouValor then
ShowMessage('Ok')
else
ShowMessage('Não');
end;
end;
procedure TGBProcura.configuraBtn;
begin
_btn := TBitBtn.Create(Self);
with _btn do
begin
Parent := Self;
Left := 168;
Top := 1;
Width := 36;
Height := 21;
Align := alRight;
Caption := '...';
TabOrder := 1;
OnClick := btnClick;
end;
end;
procedure TGBProcura.configuraEdit;
begin
_edit := TEdit.Create(Self);
with _edit do
begin
Parent := Self;
Left := 1;
Top := 1;
Width := 167;
Height := 21;
Align := alClient;
TabOrder := 0;
Text := '';
ReadOnly := Self.ReadOnly;
end;
end;
procedure TGBProcura.configuraPanel;
begin
Width := 210;
Height := 27;
BorderStyle := bsSingle;
end;
constructor TGBProcura.Create(AOwner: TComponent);
begin
inherited;
configuraPanel;
configuraBtn;
configuraEdit;
end;
procedure TGBProcura.editChange(Sender: TObject);
begin
if DataSource <> nil then
begin
DataSource.DataSet.FieldByName(DataField).Value := FLookupChave;
end;
end;
procedure TGBProcura.SetLookupChave(const Value: Variant);
begin
FLookupChave := Value;
end;
procedure TGBProcura.SetMontaSelect(const Value: TGBMontaSelect);
begin
FMontaSelect := Value;
end;
procedure TGBProcura.setReadOnly(const Value: boolean);
begin
FReadOnly := Value;
end;
end.
|
unit main;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, SynEdit, SynFacilHighlighter, Resource,
Forms, Controls, ResourceStrings, SplashScreen,
Dialogs, ComCtrls, ExtCtrls, Menus, StdCtrls, ActnList, khexeditor, SettingsFrame,
//The pascal compiler
Compiler,
Configuration;
type
TProjectFile = record
Dirty: boolean;
Editor: TComponent;
FileName: string;
FullFileName: string;
TabSheet: TTabSheet;
TreeNode: TTreeNode;
hlt : TSynFacilSyn;
end;
pProjectFile = ^TProjectFile;
{ TMainForm }
TMainForm = class(TForm)
actDuplicate: TAction;
actShowInExplorer: TAction;
actDelete: TAction;
actCopy: TAction;
actCut: TAction;
actPaste: TAction;
actCopyFullPath: TAction;
actCopyProjectPath: TAction;
actOpenInNewWindow: TAction;
actSearchInDirectory: TAction;
actRename: TAction;
actNewFolder: TAction;
actNewFile: TAction;
ActionList: TActionList;
EditorsPageControl: TPageControl;
EditorsPanel: TPanel;
FeedbackPageControl: TPageControl;
FeedbackPanel: TPanel;
ImageList16: TImageList;
MainMenu: TMainMenu;
miProjNewFile: TMenuItem;
miCut: TMenuItem;
miPaste: TMenuItem;
MenuItem12: TMenuItem;
miAddProjectFolder: TMenuItem;
miRemoveProjectFolder: TMenuItem;
miCopyFullPath: TMenuItem;
MenuItem16: TMenuItem;
miCopyProjectPath: TMenuItem;
miOpenInNewWindow: TMenuItem;
miSearchInDirectory: TMenuItem;
MenuItem2: TMenuItem;
MenuItem21: TMenuItem;
MenuItem3: TMenuItem;
miProjNewFolder: TMenuItem;
MenuItem5: TMenuItem;
miCopy: TMenuItem;
MenuItem7: TMenuItem;
MenuItem8: TMenuItem;
miDuplicate: TMenuItem;
MessagesMemo: TMemo;
MessagesPopupMenu: TPopupMenu;
MessagesTabSheet: TTabSheet;
miAbout: TMenuItem;
miAssemble: TMenuItem;
miCloseAllOther: TMenuItem;
miClosePage: TMenuItem;
miCompile: TMenuItem;
miDeleteFile: TMenuItem;
miEdit: TMenuItem;
miFile: TMenuItem;
miFileSep1: TMenuItem;
miFileSep2: TMenuItem;
miHelp: TMenuItem;
miMessagesMemoClearAll: TMenuItem;
miMessagesMemoCopy: TMenuItem;
miMessagesMemoSelectAll: TMenuItem;
miMoveLeft: TMenuItem;
miMoveRight: TMenuItem;
miMoveRightMost: TMenuItem;
miNew: TMenuItem;
miNewFile: TMenuItem;
miNewFolder: TMenuItem;
miOpenProjectFolder: TMenuItem;
miProject: TMenuItem;
miQuit: TMenuItem;
miSave: TMenuItem;
miSaveAll: TMenuItem;
miSaveAs: TMenuItem;
miSaveAsTab: TMenuItem;
miSaveTab: TMenuItem;
miSettings: TMenuItem;
miShowInExplorer: TMenuItem;
miTools: TMenuItem;
moMoveLeftMost: TMenuItem;
ProjectPopupMenu: TPopupMenu;
ProjectTreeView: TTreeView;
SaveDialog: TSaveDialog;
SelectDirectoryDialog: TSelectDirectoryDialog;
Splitter1: TSplitter;
Splitter2: TSplitter;
TabsPopupMenu: TPopupMenu;
Timer: TTimer;
procedure actCopyExecute(Sender: TObject);
procedure actCopyFullPathExecute(Sender: TObject);
procedure actCopyProjectPathExecute(Sender: TObject);
procedure actCutExecute(Sender: TObject);
procedure actDeleteExecute(Sender: TObject);
procedure actDuplicateExecute(Sender: TObject);
procedure actNewFileExecute(Sender: TObject);
procedure actNewFolderExecute(Sender: TObject);
procedure actOpenInNewWindowExecute(Sender: TObject);
procedure actPasteExecute(Sender: TObject);
procedure actRenameExecute(Sender: TObject);
procedure actSearchInDirectoryExecute(Sender: TObject);
procedure actShowInExplorerExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure miAboutClick(Sender: TObject);
procedure miAssembleClick(Sender: TObject);
procedure miCloseAllOtherClick(Sender: TObject);
procedure miClosePageClick(Sender: TObject);
procedure miCompileClick(Sender: TObject);
procedure miMessagesMemoClearAllClick(Sender: TObject);
procedure miMessagesMemoCopyClick(Sender: TObject);
procedure miMessagesMemoSelectAllClick(Sender: TObject);
procedure miMoveLeftClick(Sender: TObject);
procedure miMoveRightClick(Sender: TObject);
procedure miMoveRightMostClick(Sender: TObject);
procedure miOpenProjectFolderClick(Sender: TObject);
procedure miQuitClick(Sender: TObject);
procedure miSaveAllClick(Sender: TObject);
procedure miSaveAsClick(Sender: TObject);
procedure miSaveClick(Sender: TObject);
procedure miSettingsClick(Sender: TObject);
procedure moMoveLeftMostClick(Sender: TObject);
private
FProjectFolder: string;
FProjectFiles: TFPList;
{ private declarations }
procedure OnEditorChange(Sender: TObject);
procedure SaveEditorFile(const idx: integer);
procedure SetProjectFolder(Folder: string);
//projectfile related functions
function AddProjectFile(const path: string; var node: TTreeNode): pProjectFile;
function ProjectFileTabIndex(const FileName: string): integer;
public
{ public declarations }
procedure EnvironmentChanged;
procedure CloseProjectFile(index: integer);
end;
var
MainForm: TMainForm;
implementation
{$R *.lfm}
uses
icons, AppSettings, ASMZ80, MessageIntf, Graphics, Process, Clipbrd;
procedure UIVerboseMsg(Level: VERBOSITY_LEVELS; aMessage: STRING);
begin
IF Level IN Configuration.Verbose THEN
Messages.Log(aMessage);
end;
{ TMainForm }
procedure TMainForm.FormCreate(Sender: TObject);
begin
Messages.RegisterView(MessagesMemo);
VerboseMsg := @UIVerboseMsg;
LoadFromResource(ImageList16);
FProjectFiles := TFPList.Create;
//new menu is disabled until a project is opened
miNew.Enabled := False;
if Settings.ReOpenAtStart then
SetProjectFolder(Settings.LastProjectFolder);
//show about in editor
miAboutClick(nil);
end;
procedure TMainForm.actNewFileExecute(Sender: TObject);
var
sl: TStrings;
begin
if SaveDialog.Execute then
begin
sl := TStringList.Create;
sl.SaveToFile(SaveDialog.FileName);
SetProjectFolder(FProjectFolder);
sl.Free;
end;
end;
procedure TMainForm.actDeleteExecute(Sender: TObject);
var
tn: TTreeNode;
pf: pProjectFile;
begin
tn := ProjectTreeView.Selected;
if tn = nil then
exit;
if MessageDlg(rsDeleteFile, rsAreYouSureToPermanen, mtConfirmation, mbYesNo, 0) = mrYes then
begin
if not DeleteFile(IncludeTrailingPathDelimiter(FProjectFolder) + tn.Text) then
Messages.LogFmt(rsCouldNotDeleteFileS, [SysErrorMessage(GetLastOSError)])
else
begin
//close file in editor
pf := pProjectFile(tn.Data);
pf^.TabSheet.Free;
//rebuild project tree view
SetProjectFolder(FProjectFolder);
end;
end;
end;
procedure TMainForm.actDuplicateExecute(Sender: TObject);
var
tn: TTreeNode;
src, dest: string;
begin
tn := ProjectTreeView.Selected;
if tn <> nil then
begin
if tn.Parent <> nil then
begin
src := IncludeTrailingPathDelimiter(FProjectFolder) + tn.Text;
dest := tn.Text;
InputQuery(rsDestinationFilename, rsPleaseEnterTheDestin, dest);
dest := IncludeTrailingPathDelimiter(FProjectFolder) + dest;
if src = dest then
exit;
if not CopyFile(src, dest, True, False) then
begin
Messages.LogFmt(rsErrorCouldNotDulicat, [SysErrorMessage(GetLastOSError)]);
end
else
SetProjectFolder(FProjectFolder);
end;
end;
end;
procedure TMainForm.actCopyExecute(Sender: TObject);
begin
end;
procedure TMainForm.actCopyFullPathExecute(Sender: TObject);
var
tn: TTreeNode;
begin
tn := ProjectTreeView.Selected;
if tn <> nil then
begin
if tn.Parent <> nil then
Clipboard.AsText := IncludeTrailingPathDelimiter(FProjectFolder) + tn.Text;
end;
end;
procedure TMainForm.actCopyProjectPathExecute(Sender: TObject);
var
tn: TTreeNode;
begin
tn := ProjectTreeView.Selected;
if tn <> nil then
begin
if tn.Parent <> nil then
Clipboard.AsText := IncludeTrailingPathDelimiter(FProjectFolder);
end;
end;
procedure TMainForm.actCutExecute(Sender: TObject);
begin
end;
procedure TMainForm.actNewFolderExecute(Sender: TObject);
var
path: string;
begin
InputQuery(rsCreateNewFolder, rsEnterThePathForTheNe, path);
if path <> '' then
begin
path := IncludeTrailingPathDelimiter(FProjectFolder) + path;
if not ForceDirectories(path) then
Messages.LogFmt(rsErrorCouldNotCreateD, [SysErrorMessage(GetLastOSError)])
else
SetProjectFolder(FProjectFolder);
end;
end;
procedure TMainForm.actOpenInNewWindowExecute(Sender: TObject);
var
tn: TTreeNode;
ext: string;
pf: pProjectFile;
idx: integer;
procedure CreateSynEditHighlighter;
begin
TSynEdit(pf^.Editor) := TSynEdit.Create(pf^.TabSheet);
TSynEdit(pf^.Editor).Parent := pf^.TabSheet;
TSynEdit(pf^.Editor).Align := alClient;
TSynEdit(pf^.Editor).Lines.LoadFromFile(pf^.FullFileName);
TSynEdit(pf^.Editor).OnChange := @OnEditorChange;
end;
begin
tn := ProjectTreeView.Selected;
if tn = nil then
exit;
if tn.Parent = nil then
exit;
//check if projectfile already is opened in the editor
idx := ProjectFileTabIndex(tn.Text);
if idx <> -1 then
begin
EditorsPageControl.PageIndex := idx;
exit;
end;
ext := LowerCase(ExtractFileExt(tn.Text));
pf := AddProjectFile(FProjectFolder, tn);
case ext of
'.asm':
begin
pf^.TabSheet.ImageIndex := ICON_ASM_SOURCE;
//create the editor
CreateSynEditHighlighter;
//highlighter
pf^.hlt := TSynFacilSyn.Create(self);
TSynEdit(pf^.Editor).Highlighter := pf^.hlt;
pf^.hlt.LoadFromResourceName(HInstance, 'HL_Z80ASM');
UpdateSynEdit(TSynEdit(pf^.Editor));
end;
'.obj':
begin
pf^.TabSheet.ImageIndex := ICON_OBJ_SOURCE;
//create the editor
pf^.Editor := TKHexEditor.Create(pf^.TabSheet);
TKHexEditor(pf^.Editor).Parent := pf^.TabSheet;
TKHexEditor(pf^.Editor).Align := alClient;
TKHexEditor(pf^.Editor).Font.Style := [];
TKHexEditor(pf^.Editor).LoadFromFile(pf^.FullFileName);
TKHexEditor(pf^.Editor).OnChange := @OnEditorChange;
UpdateHexEditor(TKHexEditor(pf^.Editor));
end;
'.pas', '.pp', '.p', '.inc':
begin
pf^.TabSheet.ImageIndex := ICON_PAS_SOURCE;
//create the editor
CreateSynEditHighlighter;
//highlighter
pf^.hlt := TSynFacilSyn.Create(self);
TSynEdit(pf^.Editor).Highlighter := pf^.hlt;
pf^.hlt.LoadFromResourceName(HInstance, 'HL_PASCAL');
UpdateSynEdit(TSynEdit(pf^.Editor));
end;
else
begin
//for all other files open the SynEdit editor without highlighter
pf^.TabSheet.ImageIndex := ICON_FILE;
//create the editor
CreateSynEditHighlighter;
UpdateSynEdit(TSynEdit(pf^.Editor));
end;
end;
end;
procedure TMainForm.actPasteExecute(Sender: TObject);
begin
end;
procedure TMainForm.actRenameExecute(Sender: TObject);
var
tn: TTreeNode;
src, dest: string;
begin
tn := ProjectTreeView.Selected;
if tn <> nil then
begin
if tn.Parent <> nil then
begin
src := IncludeTrailingPathDelimiter(FProjectFolder) + tn.Text;
dest := tn.Text;
InputQuery(rsNewFilename, rsPleaseEnterTheNewFil, dest);
dest := IncludeTrailingPathDelimiter(FProjectFolder) + dest;
if src = dest then
exit;
if not RenameFile(src, dest) then
begin
Messages.LogFmt(rsErrorCouldNotRenameF, [SysErrorMessage(GetLastOSError)]);
end
else
SetProjectFolder(FProjectFolder);
end;
end;
end;
procedure TMainForm.actSearchInDirectoryExecute(Sender: TObject);
begin
end;
procedure TMainForm.actShowInExplorerExecute(Sender: TObject);
var
tn: TTreeNode;
s: string;
exec: string;
arg: string;
begin
tn := ProjectTreeView.Selected;
if tn <> nil then
begin
{$IFDEF MSWINDOWS}
exec := 'explorer';
if tn.Parent = nil then
arg := FProjectFolder
else
arg := Format('/select,%s%s', [IncludeTrailingPathDelimiter(FProjectFolder), tn.Text]);
{$ENDIF}
{$IFDEF LINUX}
exec := 'gnome-open';
if tn.Parent = nil then
arg := FProjectFolder
else
arg := Format('%s%s', [IncludeTrailingPathDelimiter(FProjectFolder), tn.Text]);
{$ENDIF}
{$IFDEF DARWIN}
exec := 'open';
if tn.Parent = nil then
arg := FProjectFolder
else
arg := Format('%s%s', [IncludeTrailingPathDelimiter(FProjectFolder), tn.Text]);
{$ENDIF}
RunCommand(exec, [arg], s);
end;
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
while FProjectFiles.Count > 0 do
CloseProjectFile(0);
FProjectFiles.Free;
end;
procedure TMainForm.FormShow(Sender: TObject);
begin
Caption := Format(rsEasy80IDEVS, [{$i version.inc}]);
end;
procedure TMainForm.miMessagesMemoClearAllClick(Sender: TObject);
begin
MessagesMemo.Lines.Clear;
end;
procedure TMainForm.miMessagesMemoCopyClick(Sender: TObject);
begin
MessagesMemo.CopyToClipboard;
end;
procedure TMainForm.miMessagesMemoSelectAllClick(Sender: TObject);
begin
MessagesMemo.SelectAll;
end;
procedure TMainForm.miCompileClick(Sender: TObject);
var
PascalCompiler: TCompiler;
ts: TTabSheet;
pf: pProjectFile;
time: double;
begin
ts := EditorsPageControl.ActivePage;
//exit if no tabsheet is selected
if ts = nil then
exit;
pf := pProjectFile(ts.Tag);
//exit if file is not pascal sourcefile
if LowerCase(ExtractFileExt(pf^.FileName)) <> '.pas' then
exit;
//save all editor files
miSaveAllClick(nil);
try
time := Now;
Messages.Log('Z80 Pascal compiler (WIP version)');
Messages.Log('(c) 2009, 2010 by Guillermo Martínez');
Messages.Log('');
Configuration.InputFileName := pf^.FullFileName;
Configuration.OutputFileName := ChangeFileExt(pf^.FullFileName, '.asm');;
Configuration.ListsComments := FALSE;
Configuration.Verbose := [vblErrors, vblWarnings];
PascalCompiler := TCompiler.Create;
PascalCompiler.FileName := Configuration.InputFileName;
PascalCompiler.Compile;
Messages.Log('Compilation finished.');
PascalCompiler.SaveToFile (Configuration.OutputFileName);
Messages.LogFmt('File saved at ''%s''.', [Configuration.OutputFileName]);
if vblWarnings in Configuration.Verbose then
begin
Messages.Log('');
Messages.LogFmt('%d lines compiled, %.1f sec, %d bytes code', [TSynEdit(pf^.Editor).Lines.Count, (Now - time) * 24 * 3600, Length(TSynEdit(pf^.Editor).Lines.Text)]);
//Messages.LogFmt('%d warning(s) issued', [warnCount]);
//Messages.LogFmt('%d note(s) issued', [noteCount]);
//Messages.LogFmt('%d error(s) issued', [errCount]);
Messages.Log('');
end;
except
on Error: Exception do
Messages.Log(Error.Message);
end;
Configuration.Unload;
//update projectfolder
SetProjectFolder(FProjectFolder);
end;
procedure TMainForm.miAssembleClick(Sender: TObject);
var
ts: TTabSheet;
pf: pProjectFile;
lis: string;
obj: RawByteString;
begin
ts := EditorsPageControl.ActivePage;
//exit if no tabsheet is selected
if ts = nil then
exit;
pf := pProjectFile(ts.Tag);
//exit if file is not ASM
if LowerCase(ExtractFileExt(pf^.FileName)) <> '.asm' then
exit;
miSaveAllClick(nil);
lis := ChangeFileExt(pf^.FullFileName, '.lis');
obj := ChangeFileExt(pf^.FullFileName, '.obj');
ASMZ80_execute(pf^.FullFileName, lis, obj, Settings.AsmVerbose);
//update projectfolder
SetProjectFolder(FProjectFolder);
end;
procedure TMainForm.miMoveRightMostClick(Sender: TObject);
begin
EditorsPageControl.ActivePage.PageIndex := EditorsPageControl.PageCount - 1;
end;
procedure TMainForm.miClosePageClick(Sender: TObject);
begin
CloseProjectFile(EditorsPageControl.PageIndex);
end;
procedure TMainForm.miCloseAllOtherClick(Sender: TObject);
var
i: integer;
begin
for i := EditorsPageControl.PageCount -1 downto 0 do
begin
if i <> EditorsPageControl.PageIndex then
CloseProjectFile(i);
end;
end;
procedure TMainForm.miMoveLeftClick(Sender: TObject);
var
idx: integer;
begin
idx := EditorsPageControl.PageIndex;
if idx <> 0 then
EditorsPageControl.ActivePage.PageIndex := idx - 1;
end;
procedure TMainForm.miMoveRightClick(Sender: TObject);
var
idx: integer;
begin
idx := EditorsPageControl.PageIndex;
if idx <> EditorsPageControl.PageCount then
EditorsPageControl.ActivePage.PageIndex := idx + 1;
end;
procedure TMainForm.moMoveLeftMostClick(Sender: TObject);
begin
EditorsPageControl.ActivePage.PageIndex := 0;
end;
procedure TMainForm.miSaveAllClick(Sender: TObject);
var
i: Integer;
begin
for i := 0 to FProjectFiles.Count - 1 do
SaveEditorFile(i);
end;
procedure TMainForm.SaveEditorFile(const idx: integer);
var
pf: pProjectFile;
begin
pf := FProjectFiles[idx];
if pf^.Dirty then
begin
if pf^.Editor.ClassType = TSynEdit then
TSynEdit(pf^.Editor).Lines.SaveToFile(pf^.FullFileName);
if pf^.Editor.ClassType = TKHexEditor then
TKHexEditor(pf^.Editor).SaveToFile(pf^.FullFileName);
pf^.TabSheet.Caption := pf^.FileName;
end;
end;
procedure TMainForm.OnEditorChange(Sender: TObject);
var
pf: pProjectFile;
idx: integer;
begin
idx := EditorsPageControl.TabIndex;
pf := FProjectFiles[idx];
pf^.TabSheet.Caption := '*' + pf^.FileName;
pf^.Dirty := True;
end;
procedure TMainForm.miOpenProjectFolderClick(Sender: TObject);
begin
if SelectDirectoryDialog.Execute then
SetProjectFolder(SelectDirectoryDialog.FileName);
end;
procedure TMainForm.miQuitClick(Sender: TObject);
begin
//quit the main app
Close;
end;
procedure TMainForm.miAboutClick(Sender: TObject);
var
pf: pProjectFile;
idx: integer;
node: TTreeNode = nil;
begin
//check if settings already is opened in the editor
idx := ProjectFileTabIndex(rsAbout);
if idx <> -1 then
begin
EditorsPageControl.PageIndex := idx;
exit;
end;
pf := AddProjectFile(FProjectFolder, node);
pf^.TabSheet.ImageIndex := ICON_EASY80;
pf^.TabSheet.Caption := rsAbout;
pf^.Editor := TSplash.Create(pf^.TabSheet);
TSplash(pf^.Editor).Parent := pf^.TabSheet;
TSplash(pf^.Editor).Align := alClient;
end;
procedure TMainForm.miSettingsClick(Sender: TObject);
var
pf: pProjectFile;
idx: integer;
node: TTreeNode = nil;
begin
//check if settings already is opened in the editor
idx := ProjectFileTabIndex(rsSettings);
if idx <> -1 then
begin
EditorsPageControl.PageIndex := idx;
exit;
end;
pf := AddProjectFile(FProjectFolder, node);
pf^.TabSheet.ImageIndex := ICON_SETTINGS;
pf^.TabSheet.Caption := rsSettings;
pf^.Editor := TSettingsFrame.Create(pf^.TabSheet);
TSettingsFrame(pf^.Editor).Parent := pf^.TabSheet;
TSettingsFrame(pf^.Editor).Align := alClient;
end;
procedure TMainForm.miSaveClick(Sender: TObject);
var
idx: integer;
begin
idx := EditorsPageControl.TabIndex;
SaveEditorFile(idx);
end;
procedure TMainForm.miSaveAsClick(Sender: TObject);
var
pf: pProjectFile;
idx: integer;
Msg, OldFileName: string;
begin
idx := EditorsPageControl.TabIndex;
pf := FProjectFiles[idx];
if SaveDialog.Execute then
begin
OldFileName := pf^.FullFileName;
pf^.Dirty := True;
pf^.FullFileName := SaveDialog.FileName;
pf^.FileName := ExtractFileName(SaveDialog.FileName);
pf^.TreeNode.Text := pf^.FileName;
SaveEditorFile(EditorsPageControl.TabIndex);
Msg := Format(rsDeleteOldFileS, [ExtractFileName(OldFileName)]);
if MessageDlg(rsDeleteOldFile, Msg, mtConfirmation , mbYesNo, '') = mrYes then
begin
if not DeleteFile(UTF8ToAnsi(OldFileName)) then
Messages.LogFmt(rsCannotDeleteFileS, [SysErrorMessage(GetLastOSError)]);
end;
end;
end;
procedure TMainForm.SetProjectFolder(Folder: string);
var
AllFiles: TStringList;
mainnode: TTreeNode;
node: TTreeNode;
i: integer;
ext: string;
begin
//if folder does not exist then exit
if not DirectoryExists(Folder) then
exit;
//if new folder selected
if Folder <> FProjectFolder then
begin
//save the last opened projectfolder to the settings file
Settings.LastProjectFolder := Folder;
Settings.Save;
//clear the open projectfile list
while FProjectFiles.Count > 0 do
CloseProjectFile(0);
end;
FProjectFolder := Folder;
//enable new menu, when a project is opened
miNew.Enabled := True;
//now search all files in the project folder
ProjectTreeView.Items.Clear;
mainnode := ProjectTreeView.Items.Add(nil, ExtractFileName(FProjectFolder));
mainnode.ImageIndex := ICON_EASY80;
mainnode.SelectedIndex := mainnode.ImageIndex;
AllFiles := FindAllFiles(FProjectFolder, '*', False);
try
for i := 0 to AllFiles.Count - 1 do
begin
node := ProjectTreeView.Items.AddChild(mainnode, ExtractFileName(AllFiles[i]));
ext := LowerCase(ExtractFileExt(AllFiles[i]));
case ext of
'.asm': node.ImageIndex := ICON_ASM_SOURCE;
'.obj': node.ImageIndex := ICON_OBJ_SOURCE;
'.pas', '.pp', '.p', '.inc': node.ImageIndex := ICON_PAS_SOURCE;
else
node.ImageIndex := ICON_FILE;
end;
node.SelectedIndex := node.ImageIndex;
end;
//expand all items in project
mainnode.Expand(True);
//sort the items
ProjectTreeView.SortType := stText;
ProjectTreeView.AlphaSort;
finally
AllFiles.Free;
end;
end;
function TMainForm.AddProjectFile(const path: string; var node: TTreeNode): pProjectFile;
var
pf: pProjectFile;
begin
New(pf);
FProjectFiles.Add(pf);
if node <> nil then
begin
pf^.FullFileName := IncludeTrailingPathDelimiter(path) + node.Text;
//link the projectfile to the treenode
node.Data := pf;
end
else
pf^.FullFileName := '';
pf^.FileName := ExtractFileName(pf^.FullFileName);
pf^.Dirty := False;
pf^.TreeNode := node;
pf^.TabSheet := EditorsPageControl.AddTabSheet;
pf^.TabSheet.Caption := pf^.FileName;
//link the tabsheet to the projectfile record
pf^.TabSheet.Tag := PtrInt(pf);
EditorsPageControl.ActivePage := pf^.TabSheet;
Result := pf;
end;
function TMainForm.ProjectFileTabIndex(const FileName: string): integer;
var
fname: string;
i: integer;
edt : string;
begin
fname := ExtractFileName(FileName);
for i := 0 to EditorsPageControl.PageCount - 1 do
begin
//ignore the 'dirty' file indicator
edt := StringReplace(EditorsPageControl.Pages[i].Caption, '*', '', [rfReplaceAll]);
if edt = fname then
begin
Result := i;
exit;
end;
end;
Result := -1;
end;
procedure TMainForm.EnvironmentChanged;
var
i: integer;
pf: pProjectFile;
begin
//update all editor settings
for i := 0 to FProjectFiles.Count - 1 do
begin
pf := FProjectFiles[i];
if pf^.Editor.ClassType = TSynEdit then
UpdateSynEdit(TSynEdit(pf^.Editor));
if pf^.Editor.ClassType = TKHexEditor then
UpdateHexEditor(TKHexEditor(pf^.Editor));
end;
end;
procedure TMainForm.CloseProjectFile(index: integer);
var
pf: pProjectFile;
begin
//get the projectfile object from the list
pf := FProjectFiles[index];
//free and delete the projectfile object
Dispose(pf);
FProjectFiles.Delete(index);
//close the tab
EditorsPageControl.Pages[index].Free;
end;
end.
|
{-------------------------------------------------------------------------------
// EasyComponents For Delphi 7
// 一轩软研第三方开发包
// @Copyright 2010 hehf
// ------------------------------------
//
// 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何
// 人不得外泄,否则后果自负.
//
// 使用权限以及相关解释请联系何海锋
//
//
// 网站地址:http://www.YiXuan-SoftWare.com
// 电子邮件:hehaifeng1984@126.com
// YiXuan-SoftWare@hotmail.com
// QQ :383530895
// MSN :YiXuan-SoftWare@hotmail.com
//------------------------------------------------------------------------------}
unit untEasyIODFM;
interface
uses
Windows, Classes, Forms;
//从流读取控件
procedure EasyReadCmpFromStream(Stream: TStream; Root: TComponent;
OnError: TReaderError = nil; OnCreateCmp: TCreateComponentEvent = nil);
procedure EasyReadCmpFromFile(const FileName: string; Root: TComponent;
OnError: TReaderError = nil; OnCreateCmp: TCreateComponentEvent = nil);
//写控件信息到流
procedure EasyWriteCmpToStream(Stream: TStream; Root: TComponent; AsText: Boolean = True);
procedure EasyWriteCmpToFile(const FileName: string; Root: TComponent; AsText: Boolean = True);
//复制控件
procedure EasyCopyCmpResource(Dest, Source: TComponent);
function EasyComponentToString(Component: TComponent): string;
function EasyStringToComponent(Value: string; Instance: TComponent): TComponent;
//按ON标识符删除事件相关文本
procedure EasyDeleteDFMEnventLines(list: TStrings);
function EasyGetObjectString(list: TStrings; BegLine: Integer = 0; TypeString: string=''): string;
procedure EasyReadForm(aFrom: TComponent; aFileName: string = '');
function EasyLoadTextForm(FileName: String): TForm;
function EasyLoadTextForm2(FileName: String): TForm;
implementation
uses
SysUtils;
type
{ Special Reader to support overloading. }
TMyReader = class(TReader)
public
FFinded: TComponent;
procedure ReadPrefix(var Flags: TFilerFlags; var AChildPos: Integer); override;
function FindAncestorComponent(const Name: string;
ComponentClass: TPersistentClass): TComponent; override;
end;
function Local(Input: string; Default: String = ''): String;
begin
Result := Input;
end;
procedure EasyReadCmpFromFile(const FileName: string; Root: TComponent; OnError: TReaderError; OnCreateCmp: TCreateComponentEvent);
var
Stream: TStream;
begin
Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
EasyReadCmpFromStream(Stream, Root, OnError, OnCreateCmp);
finally
Stream.Free;
end;
end;
procedure EasyReadCmpFromStream(Stream: TStream; Root: TComponent; OnError: TReaderError; OnCreateCmp: TCreateComponentEvent);
var
MemSt: TStream;
Reader: TReader;
begin
MemSt := nil;
case TestStreamFormat(Stream) of
sofUnknown: raise Exception.Create(Local('SUnsuppResFormat'));
sofText:
begin
MemSt := TMemoryStream.Create;
try
ObjectTextToBinary(Stream, MemSt);
finally
MemSt.Position := 0;
end;
end;
sofBinary: Stream.ReadResHeader;
end;
if MemSt <> nil then
Reader := TMyReader.Create(MemSt, 4096)
else
Reader := TMyReader.Create(Stream, 4096);
try
Reader.OnCreateComponent := OnCreateCmp;
Reader.OnError := OnError;
Reader.ReadRootComponent(Root);
finally
Reader.Free;
if MemSt <> nil then MemSt.Free;
end;
end;
{ TMyReader }
function TMyReader.FindAncestorComponent(const Name: string;
ComponentClass: TPersistentClass): TComponent;
begin
if FFinded <> nil then
Result := FFinded
else
Result := inherited FindAncestorComponent(Name, ComponentClass);
end;
procedure TMyReader.ReadPrefix(var Flags: TFilerFlags;
var AChildPos: Integer);
var
cName, cClass: string;
sPos: integer;
begin
inherited;
if Root = nil then Exit;
sPos := Position;
cClass := ReadStr;
cName := ReadStr;
FFinded := Root.FindComponent(cName);
if (FFinded <> nil) and SameText(FFinded.ClassName, cClass) then
Include(Flags, ffInherited)
else
FFinded := nil;
Position := sPos;
end;
procedure EasyWriteCmpToStream(Stream: TStream; Root: TComponent; AsText: Boolean = True);
var
MemSt: TStream;
begin
if AsText then
begin
MemSt := TMemoryStream.Create;
try
MemSt.WriteComponent(Root);
MemSt.Position := 0;
ObjectBinaryToText(MemSt, Stream);
finally
MemSt.Free;
end
end
else
begin
Stream.WriteComponentRes(Root.ClassName, Root);
end;
end;
procedure EasyWriteCmpToFile(const FileName: string; Root: TComponent; AsText: Boolean);
var
Stream: TStream;
begin
Stream := TFileStream.Create(FileName, fmCreate);
try
EasyWriteCmpToStream(Stream, Root, AsText);
finally
Stream.Free;
end;
end;
//复制控件
procedure EasyCopyCmpResource(Dest, Source: TComponent);
var
MemSt: TStream;
Reader: TMyReader;
begin
MemSt := TMemoryStream.Create;
try
MemSt.WriteComponent(Source);
MemSt.Position := 0;
Reader := TMyReader.Create(MemSt, 4096);
try
Reader.ReadRootComponent(Dest);
finally
Reader.Free;
end;
finally
MemSt.Free;
end;
end;
function EasyComponentToString(Component: TComponent): string;
var
BinStream: TMemoryStream;
StrStream: TStringStream;
s: string;
begin
BinStream := TMemoryStream.Create;
try
StrStream := TStringStream.Create(s);
try
BinStream.WriteComponent(Component);
BinStream.Seek(0, soFromBeginning);
ObjectBinaryToText(BinStream, StrStream);
StrStream.Seek(0, soFromBeginning);
Result := StrStream.DataString;
finally
StrStream.Free;
end;
finally
BinStream.Free
end;
end; { ComponentToString }
function EasyStringToComponent(Value: string; Instance: TComponent): TComponent;
var
StrStream: TStringStream;
BinStream: TMemoryStream;
begin
StrStream := TStringStream.Create(Value);
try
BinStream := TMemoryStream.Create;
try
ObjectTextToBinary(StrStream, BinStream);
BinStream.Seek(0, soFromBeginning);
Result := BinStream.ReadComponent(Instance);
finally
BinStream.Free;
end;
finally
StrStream.Free;
end;
end; { StringToComponent }
procedure EasyDeleteDFMEnventLines(list: TStrings);
var
i : Integer;
line: String;
begin
if list.Count=0 then
Exit;
i := 0;
while i<list.Count do
begin
line := Trim(list[i]);
if Copy(line,1,2)='On' then
list.Delete(i)
else
Inc(i);
end;
end;
function EasyGetObjectString(list: TStrings; BegLine: Integer = 0; TypeString: string=''): string;
var
i,iBegCount,iEndCount : Integer;
ObjString,Line,ClassStr: String;
begin
iBegCount:=0;
iEndCount:=0;
ClassStr := Trim(UpperCase(TypeString));
for i := BegLine to list.Count - 1 do
begin
line := UpperCase(list[i]);
if Pos('OBJECT',line)>0 then
begin
if (TypeString='') or (Pos(': '+ClassStr,line)>0) then
Inc(iBegCount);
end
else
if (iBegCount>iEndCount) and (trim(line)='END') then
Inc(iEndCount);
if iBegCount>0 then
Result := Result + list[i] + #13#10;
if (iBegCount>0) and (iBegCount=iEndCount) then
Exit;
end;
end;
procedure EasyReadForm(aFrom: TComponent; aFileName: string = '');
var
FrmStrings : TStrings;
begin
if not FileExists(aFileName) then Exit;
RegisterClass(TPersistentClass(aFrom.ClassType));
FrmStrings := TStringlist.Create;
try
FrmStrings.LoadFromFile(aFileName);
//删除事件
EasyDeleteDFMEnventLines(FrmStrings);
while aFrom.ComponentCount > 0 do
aFrom.Components[0].Destroy;
aFrom := EasyStringToComponent(FrmStrings.Text, aFrom);
finally
FrmStrings.Free;
end;
UnRegisterClass(TPersistentClass(aFrom.ClassType));
end;
function EasyLoadTextForm(FileName: String): TForm;
var
list : TStrings;
FirstLine: String;
iPos : Integer;
Form : TForm;
begin
Result := nil;
if not FileExists(FileName) then Exit;
Form := TForm.Create(Application);
list := TStringList.Create;
try
list.LoadFromFile(FileName);
if list.Count = 0 then Exit;
FirstLine := list[0];
iPos := Pos(': ',FirstLine);
if iPos = 0 then //找不到': ',格式不对
Exit;
list[0] := Copy(FirstLine,1,iPos)+' TForm';
EasyDeleteDFMEnventLines(list);
EasyStringToComponent(list.Text, Form);
Result := Form;
except
Form.Free;
Result := nil;
end;
list.Free;
end;
function EasyLoadTextForm2(FileName: String): TForm;
var
list : TStrings;
FirstLine: String;
iPos : Integer;
Form : TForm;
begin
Result := nil;
if not FileExists(FileName) then Exit;
Form := TForm.Create(Application);
list := TStringList.Create;
try
list.LoadFromFile(FileName);
if list.Count=0 then Exit;
FirstLine := list[0];
iPos := Pos(': ',FirstLine);
if iPos = 0 then //找不到': ',格式不对
Exit;
list[0] := Copy(FirstLine, 1, iPos)+' TForm';
EasyDeleteDFMEnventLines(list);
EasyStringToComponent(list.Text, Form);
Result := Form;
except on e:exception do
begin
Form.Free;
Result := nil;
end;
end;
list.Free;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ }
{ Copyright(c) 2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit FMX.Ani;
{$I FMX.Defines.inc}
interface
uses
System.Classes, System.Types, System.UITypes, FMX.Types;
type
{ TColorAnimation }
TColorAnimation = class(TAnimation)
private
FStartColor: TAlphaColor;
FStopColor: TAlphaColor;
FPath, FPropertyName: AnsiString;
FInstance: TObject;
FStartFromCurrent: Boolean;
protected
procedure ProcessAnimation; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Start; override;
published
property StartValue: TAlphaColor read FStartColor write FStartColor;
property StartFromCurrent: Boolean read FStartFromCurrent write FStartFromCurrent default False;
property StopValue: TAlphaColor read FStopColor write FStopColor;
property PropertyName: AnsiString read FPropertyName write FPropertyName;
end;
{ TGradientAnimation }
TGradientAnimation = class(TAnimation)
private
FStartGradient: TGradient;
FStopGradient: TGradient;
FPath, FPropertyName: AnsiString;
FInstance: TObject;
FStartFromCurrent: Boolean;
procedure SetStartGradient(const Value: TGradient);
procedure SetStopGradient(const Value: TGradient);
protected
procedure ProcessAnimation; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Start; override;
published
property StartValue: TGradient read FStartGradient write SetStartGradient;
property StartFromCurrent: Boolean read FStartFromCurrent write FStartFromCurrent default False;
property StopValue: TGradient read FStopGradient write SetStopGradient;
property PropertyName: AnsiString read FPropertyName write FPropertyName;
end;
{ TFloatAnimation }
TFloatAnimation = class(TAnimation)
private
FStartFloat: Single;
FStopFloat: Single;
FPath, FPropertyName: AnsiString;
FInstance: TObject;
FStartFromCurrent: Boolean;
protected
procedure ProcessAnimation; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Start; override;
procedure Stop; override;
published
property StartValue: Single read FStartFloat write FStartFloat stored True;
property StartFromCurrent: Boolean read FStartFromCurrent write FStartFromCurrent default False;
property StopValue: Single read FStopFloat write FStopFloat stored True;
property PropertyName: AnsiString read FPropertyName write FPropertyName;
end;
{ TRectAnimation }
TRectAnimation = class(TAnimation)
private
FStartRect: TBounds;
FCurrent: TBounds;
FStopRect: TBounds;
FPath, FPropertyName: AnsiString;
FInstance: TObject;
FStartFromCurrent: Boolean;
protected
procedure ProcessAnimation; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Start; override;
published
property StartValue: TBounds read FStartRect write FStartRect;
property StartFromCurrent: Boolean read FStartFromCurrent write FStartFromCurrent default False;
property StopValue: TBounds read FStopRect write FStopRect;
property PropertyName: AnsiString read FPropertyName write FPropertyName;
end;
{ TBitmapAnimation }
TBitmapAnimation = class(TAnimation)
private
FPropertyName: AnsiString;
FInstance: TObject;
FStartBitmap: TBitmap;
FStopBitmap: TBitmap;
FCurrent: TBitmap;
procedure SetStartBitmap(Value: TBitmap);
procedure SetStopBitmap(Value: TBitmap);
protected
procedure ProcessAnimation; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property StartValue: TBitmap read FStartBitmap write SetStartBitmap;
property StopValue: TBitmap read FStopBitmap write SetStopBitmap;
property PropertyName: AnsiString read FPropertyName write FPropertyName;
end;
{ TBitmapListAnimation }
TBitmapListAnimation = class(TAnimation)
private
FPropertyName: AnsiString;
FInstance: TObject;
FCurrent: TBitmap;
FAnimationCount: Integer;
FAnimationBitmap: TBitmap;
FLastAnimationStep: Integer;
procedure SetAnimationBitmap(Value: TBitmap);
protected
procedure ProcessAnimation; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property PropertyName: AnsiString read FPropertyName write FPropertyName;
property AnimationBitmap: TBitmap read FAnimationBitmap write SetAnimationBitmap;
property AnimationCount: Integer read FAnimationCount write FAnimationCount;
end;
{ Key Animations }
{ TKey }
TKey = class(TCollectionItem)
private
FKey: Single;
procedure SetKey(const Value: Single);
published
property Key: Single read FKey write SetKey;
end;
{ TKeys }
TKeys = class(TCollection)
public
function FindKeys(const Time: Single; var Key1, Key2: TKey): Boolean;
end;
{ TColorKey }
TColorKey = class(TKey)
private
FValue: TAlphaColor;
published
property Value: TAlphaColor read FValue write FValue;
end;
{ TColorKeyAnimation }
TColorKeyAnimation = class(TAnimation)
private
FPropertyName: AnsiString;
FInstance: TObject;
FKeys: TKeys;
FPath: AnsiString;
FStartFromCurrent: Boolean;
protected
procedure ProcessAnimation; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Start; override;
published
property PropertyName: AnsiString read FPropertyName write FPropertyName;
property Keys: TKeys read FKeys write FKeys;
property StartFromCurrent: Boolean read FStartFromCurrent write FStartFromCurrent;
end;
{ TFloatKey }
TFloatKey = class(TKey)
private
FValue: Single;
published
property Value: Single read FValue write FValue;
end;
{ TFloatKeyAnimation }
TFloatKeyAnimation = class(TAnimation)
private
FPropertyName: AnsiString;
FInstance: TObject;
FKeys: TKeys;
FPath: AnsiString;
FStartFromCurrent: Boolean;
protected
procedure ProcessAnimation; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Start; override;
published
property PropertyName: AnsiString read FPropertyName write FPropertyName;
property Keys: TKeys read FKeys write FKeys;
property StartFromCurrent: Boolean read FStartFromCurrent write FStartFromCurrent;
end;
{ Path Animation }
{ TPathAnimation }
TPathAnimation = class(TAnimation)
private
FPath: TPathData;
FPolygon: TPolygon;
FObj: TControl;
FStart: TPointF;
FRotate: Boolean;
FSpline: TSpline;
procedure SetPath(const Value: TPathData);
protected
procedure ProcessAnimation; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Start; override;
published
property Path: TPathData read FPath write SetPath;
property Rotate: Boolean read FRotate write FRotate default False;
end;
implementation
uses
System.UIConsts, System.Math, System.TypInfo, System.SysUtils;
{ TAnimation }
constructor TColorAnimation.Create(AOwner: TComponent);
begin
inherited;
Duration := 0.2;
FStartColor := $FFFFFFFF;
FStartColor := $FFFFFFFF;
end;
destructor TColorAnimation.Destroy;
begin
inherited;
end;
procedure TColorAnimation.Start;
var
Persistent: string;
I: Integer;
Comp: TFmxObject;
begin
if (Parent <> nil) and (FPropertyName <> '') then
begin
if FInstance = nil then
begin
FInstance := Parent;
FPath := FPropertyName;
while Pos('.', FPath) > 0 do
begin
Persistent := GetToken(FPath, '.');
if GetPropInfo(FInstance.ClassInfo, Persistent, [tkClass]) <> nil then
FInstance := GetObjectProp(FInstance, Persistent)
else
if Parent <> nil then
begin
for I := 0 to Parent.ChildrenCount - 1 do
if CompareText(Parent.Children[I].Name, Persistent) = 0 then
begin
Comp := Parent.Children[I];
if GetPropInfo(Comp.ClassInfo, FPath) <> nil then
begin
FInstance := Comp;
Break;
end;
end;
end;
end;
end;
end;
if (FInstance <> nil) and StartFromCurrent then
begin
{ is string prop }
if GetPropInfo(FInstance.ClassInfo, FPath,
[tkString, tkLString, tkWString{$IFDEF FPC},
tkAString{$ENDIF}{$IFDEF KS_COMPILER11_UP}, tkUString{$ENDIF}]) <> nil
then
StartValue := StringToAlphaColor(GetStrProp(FInstance, FPath));
{ is int prop }
if GetPropInfo(FInstance.ClassInfo, FPath, [tkInteger]) <> nil then
StartValue := GetOrdProp(FInstance, FPath);
end;
inherited;
end;
procedure TColorAnimation.ProcessAnimation;
begin
if FInstance <> nil then
begin
{ is string prop }
if GetPropInfo(FInstance.ClassInfo, FPath,
[tkString, tkLString, tkWString{$IFDEF FPC},
tkAString{$ENDIF}{$IFDEF KS_COMPILER11_UP}, tkUString{$ENDIF}]) <> nil
then
SetStrProp(FInstance, FPath, AlphaColorToString(InterpolateColor(FStartColor,
FStopColor, NormalizedTime)));
{ is int prop }
if GetPropInfo(FInstance.ClassInfo, FPath, [tkInteger]) <> nil then
SetOrdProp(FInstance, FPath, InterpolateColor(FStartColor, FStopColor,
NormalizedTime));
end;
end;
{ TAnimation }
constructor TGradientAnimation.Create(AOwner: TComponent);
begin
inherited;
Duration := 0.2;
FStartGradient := TGradient.Create;
FStopGradient := TGradient.Create;
end;
destructor TGradientAnimation.Destroy;
begin
FStartGradient.Free;
FStopGradient.Free;
inherited;
end;
procedure TGradientAnimation.Start;
var
Persistent: string;
I: Integer;
Comp: TFmxObject;
begin
if (Parent <> nil) and (FPropertyName <> '') then
begin
if FInstance = nil then
begin
FInstance := Parent;
FPath := FPropertyName;
while Pos('.', FPath) > 0 do
begin
Persistent := GetToken(FPath, '.');
if GetPropInfo(FInstance.ClassInfo, Persistent, [tkClass]) <> nil then
FInstance := GetObjectProp(FInstance, Persistent)
else
if Parent <> nil then
begin
for I := 0 to Parent.ChildrenCount - 1 do
if CompareText(Parent.Children[I].Name, Persistent) = 0 then
begin
Comp := Parent.Children[I];
if GetPropInfo(Comp.ClassInfo, FPath) <> nil then
begin
FInstance := Comp;
Break;
end;
end;
end;
end;
end;
end;
if (FInstance <> nil) and StartFromCurrent then
begin
if GetPropInfo(FInstance.ClassInfo, FPath, [tkClass]) <> nil then
begin
StartValue := TGradient(GetObjectProp(FInstance, FPath, TGradient));
end;
end;
inherited;
end;
procedure TGradientAnimation.ProcessAnimation;
var
i: Integer;
G: TGradient;
begin
if FInstance <> nil then
begin
if GetPropInfo(FInstance.ClassInfo, FPath, [tkClass]) <> nil then
begin
with TGradient(GetObjectProp(FInstance, FPath, TGradient)) do
begin
for i := 0 to Points.Count - 1 do
begin
if (i < FStopGradient.Points.Count) and (i < FStartGradient.Points.Count) then
Points[i].Color := FMX.Types.InterpolateColor
(FStartGradient.Points[i].Color, FStopGradient.Points[i].Color,
NormalizedTime);
end;
Change;
end;
end;
end;
end;
procedure TGradientAnimation.SetStartGradient(const Value: TGradient);
begin
FStartGradient.Assign(Value);
end;
procedure TGradientAnimation.SetStopGradient(const Value: TGradient);
begin
FStopGradient.Assign(Value);
end;
{ TFloatAnimation }
constructor TFloatAnimation.Create(AOwner: TComponent);
begin
inherited;
Duration := 0.2;
FStartFloat := 0;
FStopFloat := 0;
end;
destructor TFloatAnimation.Destroy;
begin
inherited;
end;
procedure TFloatAnimation.Start;
var
Persistent: string;
I: Integer;
Comp: TFmxObject;
begin
if (Parent <> nil) and (FPropertyName <> '') then
begin
if FInstance = nil then
begin
FInstance := Parent;
FPath := FPropertyName;
while Pos('.', FPath) > 0 do
begin
Persistent := GetToken(FPath, '.');
if GetPropInfo(FInstance.ClassInfo, Persistent, [tkClass]) <> nil then
FInstance := GetObjectProp(FInstance, Persistent)
else
if Parent <> nil then
begin
for I := 0 to Parent.ChildrenCount - 1 do
if CompareText(Parent.Children[I].Name, Persistent) = 0 then
begin
Comp := Parent.Children[I];
if GetPropInfo(Comp.ClassInfo, FPath) <> nil then
begin
FInstance := Comp;
Break;
end;
end;
end;
end;
end;
end;
if (FInstance <> nil) and StartFromCurrent then
begin
{ is float prop }
if GetPropInfo(FInstance.ClassInfo, FPath, [tkFloat]) <> nil then
begin
StartValue := GetFloatProp(FInstance, FPath);
end;
end;
inherited;
end;
procedure TFloatAnimation.Stop;
begin
inherited;
FInstance := nil;
end;
procedure TFloatAnimation.ProcessAnimation;
begin
if FInstance <> nil then
begin
{ is float prop }
if GetPropInfo(FInstance.ClassInfo, FPath, [tkFloat]) <> nil then
begin
SetFloatProp(FInstance, FPath, InterpolateSingle(FStartFloat, FStopFloat,
NormalizedTime));
end;
end;
end;
{ TRectAnimation }
constructor TRectAnimation.Create(AOwner: TComponent);
begin
inherited;
Duration := 0.2;
FStartRect := TBounds.Create(RectF(0, 0, 0, 0));
FStopRect := TBounds.Create(RectF(0, 0, 0, 0));
FCurrent := TBounds.Create(RectF(0, 0, 0, 0));
end;
destructor TRectAnimation.Destroy;
begin
FCurrent.Free;
FStartRect.Free;
FStopRect.Free;
inherited;
end;
procedure TRectAnimation.Start;
var
Persistent: string;
I: Integer;
Comp: TFmxObject;
Value: TObject;
begin
if (Parent <> nil) and (FPropertyName <> '') then
begin
if FInstance = nil then
begin
FInstance := Parent;
FPath := FPropertyName;
while Pos('.', FPath) > 0 do
begin
Persistent := GetToken(FPath, '.');
if GetPropInfo(FInstance.ClassInfo, Persistent, [tkClass]) <> nil then
FInstance := GetObjectProp(FInstance, Persistent)
else
if Parent <> nil then
begin
for I := 0 to Parent.ChildrenCount - 1 do
if CompareText(Parent.Children[I].Name, Persistent) = 0 then
begin
Comp := Parent.Children[I];
if GetPropInfo(Comp.ClassInfo, FPath) <> nil then
begin
FInstance := Comp;
Break;
end;
end;
end;
end;
end;
end;
if (FInstance <> nil) and StartFromCurrent then
begin
{ is Rect prop }
if GetPropInfo(FInstance.ClassInfo, FPropertyName, [tkClass]) <> nil then
begin
Value := GetObjectProp(FInstance, FPropertyName);
if (Value <> nil) and (Value is TPersistent) then
FStartRect.Assign(TPersistent(Value));
end;
end;
inherited;
end;
procedure TRectAnimation.ProcessAnimation;
var
Value: TObject;
begin
if FInstance <> nil then
begin
{ calc value }
FCurrent.Left := InterpolateSingle(FStartRect.Left, FStopRect.Left,
NormalizedTime);
FCurrent.Top := InterpolateSingle(FStartRect.Top, FStopRect.Top,
NormalizedTime);
FCurrent.Right := InterpolateSingle(FStartRect.Right, FStopRect.Right,
NormalizedTime);
FCurrent.Bottom := InterpolateSingle(FStartRect.Bottom, FStopRect.Bottom,
NormalizedTime);
{ is Rect prop }
if GetPropInfo(FInstance.ClassInfo, FPath, [tkClass]) <> nil then
begin
Value := GetObjectProp(FInstance, FPath);
if (Value <> nil) and (Value is TPersistent) then
TPersistent(Value).Assign(FCurrent);
end;
end;
end;
{ TBitmapAnimation }
constructor TBitmapAnimation.Create(AOwner: TComponent);
begin
inherited;
Duration := 0.2;
FStartBitmap := TBitmap.Create(1, 1);
FStopBitmap := TBitmap.Create(1, 1);
FCurrent := TBitmap.Create(1, 1);
end;
destructor TBitmapAnimation.Destroy;
begin
FCurrent.Free;
FStartBitmap.Free;
FStopBitmap.Free;
inherited;
end;
procedure TBitmapAnimation.ProcessAnimation;
var
Persistent, Path: string;
Value: TObject;
begin
if (Parent <> nil) and (FPropertyName <> '') then
begin
if FInstance = nil then
begin
FInstance := Parent;
Path := FPropertyName;
while Pos('.', FPropertyName) > 0 do
begin
Persistent := GetToken(FPropertyName, '.');
if GetPropInfo(FInstance.ClassInfo, Persistent, [tkClass]) <> nil then
FInstance := GetObjectProp(FInstance, Persistent);
end;
end;
if FInstance <> nil then
begin
{ is Bitmap prop }
if GetPropInfo(FInstance.ClassInfo, FPropertyName, [tkClass]) <> nil then
begin
{ calc new value }
Value := GetObjectProp(FInstance, FPropertyName);
if (Value <> nil) and (Value is TPersistent) then
begin
if Inverse then
begin
{ assign to start }
FCurrent.SetSize(FStopBitmap.Width, FStopBitmap.Height);
{ draw final with alpha }
if FCurrent.Canvas.BeginScene then
try
FCurrent.Canvas.Clear(0);
FCurrent.Canvas.DrawBitmap(FStopBitmap,
RectF(0, 0, FCurrent.Width, FCurrent.Height),
RectF(0, 0, FStopBitmap.Width, FStopBitmap.Height),
1);
FCurrent.Canvas.DrawBitmap(FStartBitmap,
RectF(0, 0, FCurrent.Width, FCurrent.Height),
RectF(0, 0, FStartBitmap.Width, FStartBitmap.Height),
1 - NormalizedTime);
finally
FCurrent.Canvas.EndScene;
end;
end
else
begin
{ assign to start }
FCurrent.SetSize(FStartBitmap.Width, FStartBitmap.Height);
{ draw final with alpha }
if FCurrent.Canvas.BeginScene then
try
FCurrent.Canvas.Clear(0);
FCurrent.Canvas.DrawBitmap(FStartBitmap,
RectF(0, 0, FCurrent.Width, FCurrent.Height),
RectF(0, 0, FStartBitmap.Width, FStartBitmap.Height),
1);
FCurrent.Canvas.DrawBitmap(FStopBitmap,
RectF(0, 0, FCurrent.Width, FCurrent.Height),
RectF(0, 0, FStopBitmap.Width, FStopBitmap.Height),
NormalizedTime);
finally
FCurrent.Canvas.EndScene;
end;
end;
{ assign }
TPersistent(Value).Assign(FCurrent);
end;
end;
end;
end;
end;
procedure TBitmapAnimation.SetStartBitmap(Value: TBitmap);
begin
FStartBitmap.Assign(Value);
end;
procedure TBitmapAnimation.SetStopBitmap(Value: TBitmap);
begin
FStopBitmap.Assign(Value);
end;
{ TBitmapListAnimation }
constructor TBitmapListAnimation.Create(AOwner: TComponent);
begin
inherited;
Duration := 0.2;
FCurrent := TBitmap.Create(0, 0);
FAnimationBitmap := TBitmap.Create(0, 0);
FAnimationCount := 1;
FLastAnimationStep := 0;
end;
destructor TBitmapListAnimation.Destroy;
begin
FCurrent.Free;
FAnimationBitmap.Free;
inherited;
end;
procedure TBitmapListAnimation.ProcessAnimation;
var
Persistent, Path: string;
Value: TObject;
LeftPos, CurrentIndex: Integer;
NowValue: Single;
begin
if (Parent <> nil) and (FPropertyName <> '') then
begin
if FInstance = nil then
begin
FInstance := Parent;
Path := FPropertyName;
while Pos('.', FPropertyName) > 0 do
begin
Persistent := GetToken(FPropertyName, '.');
if GetPropInfo(FInstance.ClassInfo, Persistent, [tkClass]) <> nil then
FInstance := GetObjectProp(FInstance, Persistent);
end;
end;
if FInstance <> nil then
begin
{ is Bitmap prop }
if GetPropInfo(FInstance.ClassInfo, FPropertyName, [tkClass]) <> nil then
begin
{ calc new value }
Value := GetObjectProp(FInstance, FPropertyName);
if (Value <> nil) and (Value is TBitmap) and not (FAnimationBitmap.IsEmpty) then
begin
NowValue := InterpolateSingle(0, FAnimationCount, NormalizedTime);
FCurrent.SetSize(FAnimationBitmap.Width div FAnimationCount, FAnimationBitmap.Height);
CurrentIndex := Trunc(NowValue);
if CurrentIndex > FAnimationCount - 1 then
CurrentIndex := FAnimationCount - 1;
LeftPos := CurrentIndex * (FAnimationBitmap.Width div FAnimationCount);
if FCurrent.Canvas.BeginScene then
try
FCurrent.Canvas.Clear(0);
FCurrent.Canvas.DrawBitmap(FAnimationBitmap,
RectF(LeftPos, 0, LeftPos + FCurrent.Width, FCurrent.Height),
RectF(0, 0, FAnimationBitmap.Width div FAnimationCount,
FAnimationBitmap.Height), 1);
finally
FCurrent.Canvas.EndScene;
end;
TPersistent(Value).Assign(FCurrent);
end;
end;
end;
end;
end;
procedure TBitmapListAnimation.SetAnimationBitmap(Value: TBitmap);
begin
FAnimationBitmap.Assign(Value);
end;
{ Key Animation }
{ TKey }
procedure TKey.SetKey(const Value: Single);
begin
FKey := Value;
if FKey < 0 then
FKey := 0;
if FKey > 1 then
FKey := 1;
end;
{ TKeys }
function TKeys.FindKeys(const Time: Single; var Key1, Key2: TKey): Boolean;
var
i: Integer;
begin
Result := False;
if Count < 2 then
Exit;
for i := 0 to Count - 2 do
if ((Time >= TKey(Items[i]).Key) and (Time <= TKey(Items[i + 1]).Key)) then
begin
Result := True;
Key1 := TKey(Items[i]);
Key2 := TKey(Items[i + 1]);
Exit;
end;
end;
{ TColorKeyAnimation }
constructor TColorKeyAnimation.Create(AOwner: TComponent);
begin
inherited;
FKeys := TKeys.Create(TColorKey);
end;
destructor TColorKeyAnimation.Destroy;
begin
FKeys.Free;
inherited;
end;
procedure TColorKeyAnimation.Start;
var
Persistent: string;
I: Integer;
Comp: TFmxObject;
begin
if (Parent <> nil) and (FPropertyName <> '') then
begin
if FInstance = nil then
begin
FInstance := Parent;
FPath := FPropertyName;
while Pos('.', FPath) > 0 do
begin
Persistent := GetToken(FPath, '.');
if GetPropInfo(FInstance.ClassInfo, Persistent, [tkClass]) <> nil then
FInstance := GetObjectProp(FInstance, Persistent)
else
if Parent <> nil then
begin
for I := 0 to Parent.ChildrenCount - 1 do
if CompareText(Parent.Children[I].Name, Persistent) = 0 then
begin
Comp := Parent.Children[I];
if GetPropInfo(Comp.ClassInfo, FPath) <> nil then
begin
FInstance := Comp;
Break;
end;
end;
end;
end;
end;
end;
if (FInstance <> nil) and StartFromCurrent then
begin
if Keys.Count > 0 then
begin
{ is string prop }
if GetPropInfo(FInstance.ClassInfo, FPath,
[tkString, tkLString, tkWString{$IFDEF FPC},
tkAString{$ENDIF}{$IFDEF KS_COMPILER11_UP}, tkUString{$ENDIF}]) <> nil
then
TColorKey(Keys.Items[0]).Value := StringToAlphaColor(GetStrProp(FInstance, FPath));
{ is int prop }
if GetPropInfo(FInstance.ClassInfo, FPath, [tkInteger]) <> nil then
TColorKey(Keys.Items[0]).Value :=
GetOrdProp(FInstance, FPath);
end;
end;
inherited;
end;
procedure TColorKeyAnimation.ProcessAnimation;
var
Key1, Key2: TKey;
begin
if FInstance <> nil then
begin
if FKeys.FindKeys(NormalizedTime, Key1, Key2) then
begin
if (TFloatKey(Key2).Key - TFloatKey(Key1).Key) = 0 then
Exit;
{ is string prop }
if GetPropInfo(FInstance.ClassInfo, FPath,
[tkString, tkLString, tkWString{$IFDEF FPC},
tkAString{$ENDIF}{$IFDEF KS_COMPILER11_UP}, tkUString{$ENDIF}]) <> nil
then
SetStrProp(FInstance, FPath,
AlphaColorToString(InterpolateColor(TColorKey(Key1).Value,
TColorKey(Key2).Value,
(NormalizedTime - TFloatKey(Key1).Key) / (TFloatKey(Key2).Key -
TFloatKey(Key1).Key))));
{ is int prop }
if GetPropInfo(FInstance.ClassInfo, FPath, [tkInteger]) <> nil then
SetOrdProp(FInstance, FPath,
InterpolateColor(TColorKey(Key1).Value,
TColorKey(Key2).Value,
(NormalizedTime - TFloatKey(Key1).Key) / (TFloatKey(Key2).Key -
TFloatKey(Key1).Key)));
end;
end;
end;
{ TFloatKeyAnimation }
constructor TFloatKeyAnimation.Create(AOwner: TComponent);
begin
inherited;
FKeys := TKeys.Create(TFloatKey);
end;
destructor TFloatKeyAnimation.Destroy;
begin
FKeys.Free;
inherited;
end;
procedure TFloatKeyAnimation.Start;
var
Persistent: string;
I: Integer;
Comp: TFmxObject;
begin
if (Parent <> nil) and (FPropertyName <> '') then
begin
if FInstance = nil then
begin
FInstance := Parent;
FPath := FPropertyName;
while Pos('.', FPath) > 0 do
begin
Persistent := GetToken(FPath, '.');
if GetPropInfo(FInstance.ClassInfo, Persistent, [tkClass]) <> nil then
FInstance := GetObjectProp(FInstance, Persistent)
else
if Parent <> nil then
begin
for I := 0 to Parent.ChildrenCount - 1 do
if CompareText(Parent.Children[I].Name, Persistent) = 0 then
begin
Comp := Parent.Children[I];
if GetPropInfo(Comp.ClassInfo, FPath) <> nil then
begin
FInstance := Comp;
Break;
end;
end;
end;
end;
end;
end;
if (FInstance <> nil) and StartFromCurrent then
begin
if Keys.Count > 0 then
begin
{ is string prop }
if GetPropInfo(FInstance.ClassInfo, FPath, [tkFloat]) <> nil then
TFloatKey(Keys.Items[0]).Value := GetFloatProp(FInstance, FPath);
end;
end;
inherited;
end;
procedure TFloatKeyAnimation.ProcessAnimation;
var
Key1, Key2: TKey;
begin
if FInstance <> nil then
begin
if FKeys.FindKeys(NormalizedTime, Key1, Key2) then
begin
if (TFloatKey(Key2).Key - TFloatKey(Key1).Key) = 0 then
Exit;
if GetPropInfo(FInstance.ClassInfo, FPath, [tkFloat]) <> nil then
SetFloatProp(FInstance, FPath, InterpolateSingle(TFloatKey(Key1).Value,
TFloatKey(Key2).Value, (NormalizedTime - TFloatKey(Key1).Key) /
(TFloatKey(Key2).Key - TFloatKey(Key1).Key)));
end;
end;
end;
{ TPathAnimation }
constructor TPathAnimation.Create(AOwner: TComponent);
begin
inherited;
FPath := TPathData.Create;
end;
destructor TPathAnimation.Destroy;
begin
if FSpline <> nil then
FreeAndNil(FSpline);
FPath.Free;
inherited;
end;
procedure TPathAnimation.ProcessAnimation;
var
OldP, P1: TPointF;
begin
if (Length(FPolygon) > 0) and (FObj <> nil) then
begin
OldP := FObj.Position.Point;
FSpline.SplineXY(NormalizedTime * High(FPolygon), P1.X, P1.Y);
FObj.Position.X := FStart.X + P1.X;
FObj.Position.Y := FStart.Y + P1.Y;
if FRotate and (NormalizedTime <> 0) and (NormalizedTime <> 1) and
((OldP.X <> FObj.Position.X) and (OldP.Y <> FObj.Position.Y)) then
begin
if Inverse then
begin
if VectorCrossProductZ(Vector(FObj.Position.X - OldP.X,
FObj.Position.Y - OldP.Y), Vector(0, 1)) < 0 then
FObj.RotationAngle := 180 +
RadToDeg(ArcCos(VectorAngleCosine(Vector(FObj.Position.X - OldP.X,
FObj.Position.Y - OldP.Y), Vector(0, 1))))
else
FObj.RotationAngle := 180 -
RadToDeg(ArcCos(VectorAngleCosine(Vector(FObj.Position.X - OldP.X,
FObj.Position.Y - OldP.Y), Vector(0, 1))))
end
else
begin
if VectorCrossProductZ(Vector(FObj.Position.X - OldP.X,
FObj.Position.Y - OldP.Y), Vector(0, 1)) < 0 then
FObj.RotationAngle :=
RadToDeg(ArcCos(VectorAngleCosine(Vector(FObj.Position.X - OldP.X,
FObj.Position.Y - OldP.Y), Vector(0, 1))))
else
FObj.RotationAngle :=
-RadToDeg(ArcCos(VectorAngleCosine(Vector(FObj.Position.X - OldP.X,
FObj.Position.Y - OldP.Y), Vector(0, 1))))
end;
end;
end;
end;
procedure TPathAnimation.SetPath(const Value: TPathData);
begin
FPath.Assign(Value);
end;
procedure TPathAnimation.Start;
var
i: Integer;
begin
inherited;
if FSpline <> nil then
FreeAndNil(FSpline);
SetLength(FPolygon, 0);
FPath.FlattenToPolygon(FPolygon);
if Length(FPolygon) > 1 then
for i := 1 to High(FPolygon) do
if (FPolygon[i].X = ClosePolygon.X) and (FPolygon[i].Y = ClosePolygon.Y)
then
FPolygon[i] := FPolygon[i - 1];
FSpline := TSpline.Create(FPolygon);
if (Parent <> nil) and (Parent is TControl) then
FObj := TControl(Parent)
else
FObj := nil;
if FObj <> nil then
FStart := FObj.Position.Point;
end;
initialization
RegisterFmxClasses([TColorAnimation, TGradientAnimation, TFloatAnimation,
TRectAnimation, TBitmapAnimation, TBitmapListAnimation, TColorKeyAnimation,
TFloatKeyAnimation, TPathAnimation]);
end.
|
{ ---------------------------------------------------------------------------- }
{ BulbTracer for MB3D }
{ Copyright (C) 2016-2017 Andreas Maschke }
{ ---------------------------------------------------------------------------- }
unit MeshSimplifier;
interface
uses
SysUtils, Classes, Contnrs, VectorMath, SyncObjs, Generics.Collections,
VertexList;
type
TVector3 = packed record
X, Y, Z: Single
end;
TPVector3 = ^TVector3;
TSymmetricMatrix = packed record
M: Array[0..9] of Single;
end;
TPSymmetricMatrix = ^TSymmetricMatrix;
TTriangle = packed record
V: Array [0..2] of Integer;
Err: Array [0..3] of Single;
Deleted, Dirty: Boolean;
N: TVector3;
end;
TPTriangle = ^TTriangle;
TVertex = packed record
P: TVector3;
TStart, TCount: Integer;
Q: TSymmetricMatrix;
Border: Boolean;
end;
TPVertex = ^TVertex;
TRef = packed record
TId, TVertex: Integer;
end;
TPRef = ^TRef;
TMeshSimplifier = class
private
FFaces: TFacesList;
FTriangles: TList;
FVertices: TList;
FRefs: TList;
procedure Clear;
procedure ClearRefs;
procedure MatrixInit( M: TPSymmetricMatrix; const C: Single ); overload;
procedure MatrixInit( M: TPSymmetricMatrix; const A, B, C, D: Single ); overload;
procedure MatrixAdd( Dest: TPSymmetricMatrix; const A, B: TPSymmetricMatrix );
function MatrixDet( const M: TPSymmetricMatrix; const A11, A12, A13, A21, A22, A23, A31, A32, A33: Integer): Single;
procedure VecCross( Dest: TPVector3; const A, B: TPVector3 );
procedure VecNormalize( Dest: TPVector3 );
procedure VecSub( Dest: TPVector3; const A, B: TPVector3 );
function VecDot( const A, B: TPVector3 ): Single;
function VertexError(const Q: TPSymmetricMatrix; const X, Y, Z: Single): Single;
function CalculateError( const Id_V1, Id_V2: Integer; const PResult: TPVector3 ): Single;
function Flipped( const P: TPVector3; const I0, I1: Integer; const V0, V1: TPVertex; var Deleted: Array of Boolean ): Boolean;
procedure MeshToTriangles;
procedure TrianglesToMesh;
procedure UpdateTriangles( const I0: Integer; const V:TPVertex; var Deleted: Array of Boolean; var DeletedTriangles: Integer);
procedure UpdateMesh(const Iteration: Integer);
procedure CompactMesh;
public
constructor Create( const Faces: TFacesList );
destructor Destroy; override;
procedure SimplifyMeshLossless(const Threshold: Double = 1.0E-4);
procedure SimplifyMesh(const TargetCount: Integer; const Agressiveness: Double = 7.0 );
end;
implementation
uses
Math, Windows;
// Mesh simplification roughly based on: Mesh Simplification Tutorial
//
// (C) by Sven Forstmann in 2014
//
// License : MIT
// http://opensource.org/licenses/MIT
//
//https://github.com/sp4cerat/Fast-Quadric-Mesh-Simplification
function TMeshSimplifier.VecDot( const A, B: TPVector3 ): Single;
begin
Result := A^.X * B^.X + A^.Y * B^.Y + A^.Z * B^.Z;
end;
procedure TMeshSimplifier.VecCross( Dest: TPVector3; const A, B: TPVector3 );
begin
Dest^.X := A^.Y * B^.Z - A^.Z * B^.Y;
Dest^.Y := A^.Z * B^.X - A^.X * B^.Z;
Dest^.Z := A^.X * B^.Y - A^.Y * B^.X;
end;
procedure TMeshSimplifier.VecSub( Dest: TPVector3; const A, B: TPVector3 );
begin
Dest^.X := A^.X - B^.X;
Dest^.Y := A^.Y - B^.Y;
Dest^.Z := A^.Z - B^.Z;
end;
procedure TMeshSimplifier.VecNormalize( Dest: TPVector3 );
var
Square: Single;
begin
Square := Sqrt( Dest^.X * Dest^.X + Dest^.Y * Dest^.Y + Dest^.Z * Dest^.Z );
if Square <> 0 then begin
Dest^.X := Dest^.X / Square;
Dest^.Y := Dest^.Y / Square;
Dest^.Z := Dest^.Z / Square;
end;
end;
// Error between vertex and Quadric
function TMeshSimplifier.VertexError(const Q: TPSymmetricMatrix; const X, Y, Z: Single): Single;
begin
Result := Q^.M[ 0 ] * X * X + 2 * Q^.M[ 1 ] * X * Y + 2 * Q^.M[ 2 ] * X * Z +
2 * Q^.M[ 3 ] * X + Q^.M[ 4 ] * Y * Y + 2 * Q^.M[ 5 ] * Y * Z +
2 * Q^.M[ 6 ] * Y + Q^.M[ 7 ] * Z * Z + 2 * Q^.M[ 8 ] * Z + Q^.M[ 9 ];
end;
// Error for one edge
function TMeshSimplifier.CalculateError( const Id_V1, Id_V2: Integer; const PResult: TPVector3 ): Single;
var
Border: Boolean;
Q: TSymmetricMatrix;
Error, Det: Single;
P1, P2: TPVector3;
Error1, Error2, Error3: Single;
begin
// compute interpolated vertex
MatrixAdd( @Q, @(TPVertex( FVertices[ Id_V1 ] )^.Q), @( TPVertex( FVertices[ Id_V2 ] )^.Q ) );
Border := TPVertex( FVertices[ Id_V1 ] )^.Border and TPVertex( FVertices[ Id_V2 ] )^.Border;
Error := 0.0;
Det := MatrixDet( @Q, 0, 1, 2, 1, 4, 5, 2, 5, 7 );
if ( Det <> 0 ) and ( not Border ) then begin
// q_delta is invertible
PResult^.X := -1.0 / Det *( MatrixDet( @Q, 1, 2, 3, 4, 5, 6, 5, 7 , 8) ); // vx = A41/det(q_delta)
PResult^.Y := 1.0 / Det *( MatrixDet( @Q, 0, 2, 3, 1, 5, 6, 2, 7 , 8) ); // vy = A42/det(q_delta)
PResult^.Z := -1.0 / Det *( MatrixDet( @Q, 0, 1, 3, 1, 4, 6, 2, 5, 8) ); // vz = A43/det(q_delta)
Error := VertexError( @Q, PResult^.X, PResult^.Y, PResult^.Z );
end
else begin
// det = 0 -> try to find best result
P1 := @( TPVertex( FVertices[ Id_V1 ] )^.P );
P2 := @( TPVertex( FVertices[ Id_V2 ] )^.P );
Error1 := VertexError( @Q, P1^.X, P1^.Y, P1^.Z );
Error2 := VertexError( @Q, P2^.X, P2^.Y, P2^.Z );
Error3 := VertexError( @Q, ( P1^.X + P2.X ) / 2.0, ( P1^.Y + P2.Y ) / 2.0, ( P1^.Z + P2.Z ) / 2.0 ); // P3
Error := Min( Error1, Min( Error2, Error3 ) );
if Error1 = Error then begin
PResult^.X := P1^.X;
PResult^.Y := P1^.Y;
PResult^.Z := P1^.Z;
end;
if Error2 = Error then begin
PResult^.X := P2^.X;
PResult^.Y := P2^.Y;
PResult^.Z := P2^.Z;
end;
if Error3 = Error then begin
PResult^.X := ( P1^.X + P2^.X ) / 2.0;
PResult^.Y := ( P1^.Y + P2^.Y ) / 2.0;
PResult^.Z := ( P1^.Z + P2^.Z ) / 2.0;
end;
end;
Result := Error;
end;
constructor TMeshSimplifier.Create( const Faces: TFacesList );
begin
inherited Create;
FFaces := Faces;
FVertices := TList.Create;
FTriangles := TList.Create;
FRefs := TList.Create;
end;
destructor TMeshSimplifier.Destroy;
begin
Clear;
if FTriangles <> nil then
FTriangles.Free;
if FVertices <> nil then
FVertices.Free;
if FRefs <> nil then
FRefs.Free;
inherited Destroy;
end;
procedure TMeshSimplifier.ClearRefs;
var
I: Integer;
begin
if FRefs <> nil then begin
for I := 0 to FRefs.Count - 1 do begin
if FRefs[ I ] <> nil then
FreeMem( FRefs[ I ] );
end;
FRefs.Clear;
end;
end;
procedure TMeshSimplifier.Clear;
var
I: Integer;
begin
if FTriangles <> nil then begin
for I := 0 to FTriangles.Count - 1 do begin
if FTriangles[ I ] <> nil then
FreeMem( FTriangles[ I ] );
end;
FTriangles.Clear;
end;
if FVertices <> nil then begin
for I := 0 to FVertices.Count - 1 do begin
if FVertices[ I ] <> nil then
FreeMem( FVertices[ I ] );
end;
FVertices.Clear;
end;
ClearRefs;
end;
procedure TMeshSimplifier.TrianglesToMesh;
var
I: Integer;
V: TPVertex;
T: TPTriangle;
begin
FFaces.Clear;
for I := 0 to FVertices.Count - 1 do begin
V := FVertices[ I ];
FFaces.AddUnvalidatedVertex( V^.P.X, V^.P.Y, V^.P.Z );
end;
for I := 0 to FTriangles.Count - 1 do begin
T := FTriangles[ I ];
FFaces.AddFace( T^.V[ 0 ], T^.V[ 1 ], T^.V[ 2 ] );
end;
end;
procedure TMeshSimplifier.MeshToTriangles;
var
I, J: Integer;
PVertex: TPVertex;
PTriangle: TPTriangle;
SVertex: TPS3Vector;
SFace: TPFace;
begin
Clear;
for I := 0 to FFaces.VertexCount - 1 do begin
SVertex := FFaces.GetVertex( I );
GetMem(PVertex, SizeOf(TVertex));
FVertices.Add(PVertex);
PVertex^.P.X := SVertex.X;
PVertex^.P.Y := SVertex.Y;
PVertex^.P.Z := SVertex.Z;
PVertex^.TStart := 0;
PVertex^.TCount := 0;
for J := Low( PVertex^.Q.M ) to High( PVertex^.Q.M ) do
PVertex^.Q.M[J] := 0.0;
end;
for I := 0 to FFaces.Count - 1 do begin
SFace := FFaces.GetFace( I );
GetMem( PTriangle, SizeOf( TTriangle ) );
FTriangles.Add( PTriangle );
PTriangle^.V[ 0 ] := SFace.Vertex1;
PTriangle^.V[ 1 ] := SFace.Vertex2;
PTriangle^.V[ 2 ] := SFace.Vertex3;
PTriangle^.Err[ 0 ] := 0.0;
PTriangle^.Err[ 1 ] := 0.0;
PTriangle^.Err[ 2 ] := 0.0;
PTriangle^.Err[ 3 ] := 0.0;
PTriangle^.Deleted := False;
PTriangle^.Dirty := False;
PTriangle^.N.X := 0.0;
PTriangle^.N.Y := 0.0;
PTriangle^.N.Z := 0.0;
end;
OutputDebugString(PChar('Simplification Input: TCount = '+IntToStr(FVertices.Count)+', FCount = ' + IntToStr(FTriangles.Count)));
end;
// Main simplification function
//
// target_count : target nr. of triangles
// agressiveness : sharpness to increase the threashold.
// 5..8 are good numbers
// more iterations yield higher quality
procedure TMeshSimplifier.SimplifyMesh(const TargetCount: Integer; const Agressiveness: Double = 7.0);
var
I, J, K, Iteration, DeletedTriangles, TriangleCount: Integer;
I0, I1, TStart, TCount: Integer;
V0, V1: TPVertex;
Deleted0, Deleted1: Array of Boolean;
Threshold: Double;
SRef, DRef: TPRef;
T: TPTriangle;
P: TVector3;
begin
// init
MeshToTriangles;
// init
for I := 0 to FTriangles.Count - 1 do
TPTriangle( FTriangles[ I ] )^.Deleted := False;
// main iteration loop
DeletedTriangles := 0;
TriangleCount := FTriangles.Count;
//int iteration = 0;
//loop(iteration,0,100)
for Iteration := 0 to 99 do begin
if TriangleCount - DeletedTriangles <= TargetCount then
break;
// update mesh once in a while
if iteration mod 5 = 0 then
UpdateMesh( Iteration );
// clear dirty flag
// clear dirty flag
for I := 0 to FTriangles.Count - 1 do
TPTriangle( FTriangles[ I ] )^.Dirty := False;
//
// All triangles with edges below the threshold will be removed
//
// The following numbers works well for most models.
// If it does not, try to adjust the 3 parameters
//
Threshold := 0.000000001 * Power( Iteration + 3.0, Agressiveness);
// remove vertices & mark deleted triangles
for I := 0 to FTriangles.Count - 1 do begin
T := FTriangles[ I ];
if T.Err[3] > Threshold then
Continue;
if T.Deleted then
Continue;
if T.Dirty then
Continue;
for J := 0 to 2 do begin
if T^.Err[ J ] < Threshold then begin
I0 := T.V[ J ];
V0 := FVertices[ I0 ];
I1 := T.V[ ( J + 1) mod 3 ];
V1 := FVertices[ I1 ];
// Border check
if V0.border <> V1.border then
Continue;
// Compute vertex to collapse to
CalculateError( I0, I1, @P );
SetLength( Deleted0, V0.TCount ); // normals temporarily
SetLength( Deleted1, V1.TCount ); // normals temporarily
// dont remove if flipped
if( Flipped( @P, I0, I1, V0, V1, Deleted0 ) ) then
Continue;
if( Flipped( @P, I1, I0, V1, V0, Deleted1 ) ) then
Continue;
// not flipped, so remove edge
V0.P := P;
MatrixAdd( @( V0.Q ), @( V1.Q ), @( V0.Q ));
TStart := FRefs.Count;
UpdateTriangles( I0, V0, Deleted0, DeletedTriangles );
UpdateTriangles( I0, V1, Deleted1, DeletedTriangles );
TCount := FRefs.Count - TStart;
if TCount <= V0.TCount then begin
// save ram
for K := 0 to TCount - 1 do begin
DRef := FRefs[ V0.TStart + K ];
SRef := FRefs[ TStart + K ];
DRef^.TId := SRef^.TId;
DRef^.TVertex := SRef^.TVertex;
end;
end
else begin
// append
V0.TStart := TStart;
end;
V0.TCount := TCount;
break;
end;
end;
// done?
if TriangleCount - DeletedTriangles <= TargetCount then
break;
end;
end;
// clean up mesh
CompactMesh;
TrianglesToMesh;
OutputDebugString(PChar('Simplification Output: TCount = '+IntToStr(FVertices.Count)+', FCount = ' + IntToStr(FTriangles.Count)));
end;
procedure TMeshSimplifier.SimplifyMeshLossless(const Threshold: Double = 1.0E-4);
//
// All triangles with edges below the threshold will be removed
//
// The following numbers works well for most models.
// Threshold: Double = 1.0E-3
// If it does not, try to adjust the 3 parameters
//
var
I, J, K, Iteration, DeletedTriangles, TriangleCount: Integer;
Deleted0, Deleted1: Array of Boolean;
I0, I1, TStart, TCount: Integer;
T: TPTriangle;
V0, V1: TPVertex;
SRef, DRef: TPRef;
P: TVector3;
begin
// init
MeshToTriangles;
// main iteration loop
DeletedTriangles := 0;
TriangleCount := FTriangles.Count;
for Iteration := 0 to 9999 do begin
// update mesh constantly
UpdateMesh( Iteration );
// clear dirty flag
for I := 0 to FTriangles.Count - 1 do
TPTriangle( FTriangles[ I ] )^.Dirty := False;
// remove vertices & mark deleted triangles
for I := 0 to FTriangles.Count - 1 do begin
T := FTriangles[ I ];
if T.Err[3] > Threshold then
Continue;
if T.Deleted then
Continue;
if T.Dirty then
Continue;
for J := 0 to 2 do begin
if T.err[j] < Threshold then begin
I0 := T.V[ J ];
V0 := FVertices[ I0 ];
I1 := T.V[ ( J + 1) mod 3 ];
V1 := FVertices[ I1 ];
// Border check
if V0.border <> V1.border then
Continue;
// Compute vertex to collapse to
CalculateError( I0, I1, @P );
SetLength( Deleted0, V0.TCount ); // normals temporarily
SetLength( Deleted1, V1.TCount ); // normals temporarily
// dont remove if flipped
if( Flipped( @P, I0, I1, V0, V1, Deleted0 ) ) then
Continue;
if( Flipped( @P, I1, I0, V1, V0, Deleted1 ) ) then
Continue;
// not flipped, so remove edge
V0.P := P;
MatrixAdd( @( V0.Q ), @( V1.Q ), @( V0.Q ));
TStart := FRefs.Count;
UpdateTriangles( I0, V0, Deleted0, DeletedTriangles );
UpdateTriangles( I0, V1, Deleted1, DeletedTriangles );
TCount := FRefs.Count - TStart;
if TCount <= V0.TCount then begin
// save ram
for K := 0 to TCount - 1 do begin
DRef := FRefs[ V0.TStart + K ];
SRef := FRefs[ TStart + K ];
DRef^.TId := SRef^.TId;
DRef^.TVertex := SRef^.TVertex;
end;
end
else begin
// append
V0.TStart := TStart;
end;
V0.TCount := TCount;
break;
end;
end;
end;
if DeletedTriangles <= 0 then
break;
DeletedTriangles := 0;
end;
// clean up mesh
CompactMesh;
TrianglesToMesh;
OutputDebugString(PChar('Simplification Output: TCount = '+IntToStr(FVertices.Count)+', FCount = ' + IntToStr(FTriangles.Count)));
end;
// Update triangle connections and edge error after a edge is collapsed
procedure TMeshSimplifier.UpdateTriangles( const I0: Integer; const V:TPVertex; var Deleted: Array of Boolean; var DeletedTriangles: Integer);
var
K: Integer;
P: TVector3;
SRef, R: TPRef;
T: TPTriangle;
begin
for K := 0 to V.TCount - 1 do begin
SRef := FRefs[ V.TStart + K ];
GetMem( R, SizeOf( TREf ));
R^.TId := SRef^.TId;
R^.TVertex := SRef^.TVertex;
T := FTriangles[ R.TId ];
if T^.Deleted then
Continue;
if Deleted[ K ] then begin
T^.Deleted := True;
Inc( DeletedTriangles );
Continue;
end;
T^.V[ R^.TVertex ] := I0;
T^.Dirty := True;
T^.Err[0] := CalculateError( T.V[ 0 ], T.V[ 1 ], @P );
T^.Err[1] := CalculateError( T.V[ 1 ], T.V[ 2 ], @P );
T^.Err[2] := CalculateError( T.V[ 2 ], T.V[ 0 ], @P );
T^.Err[3] := Min( T^.Err[ 0 ], Min( T.Err[ 1 ], T.err[ 2 ] ) );
FRefs.Add( R );
end;
end;
// Finally compact mesh before exiting
procedure TMeshSimplifier.CompactMesh;
var
I, J, Dst: Integer;
T: TPTriangle;
NewTriangles: TList;
begin
for I := 0 to FVertices.Count - 1 do begin
TPVertex( FVertices[i] ).TCount := 0;
end;
NewTriangles := TList.Create;
for I := 0 to FTriangles.Count - 1 do begin
T := FTriangles[ I ];
if not T^.Deleted then begin
NewTriangles.Add( T );
for J := 0 to 2 do
TPVertex( FVertices[T^.V[ J ] ] )^.TCount := 1;
end
else
FreeMem( T );
end;
FTriangles.Free;
FTriangles := NewTriangles;
Dst := 0;
for I := 0 to FVertices.Count - 1 do begin
if TPVertex( FVertices[ I ] )^.TCount > 0 then begin
TPVertex( FVertices[ I ] )^.TStart := Dst;
TPVertex( FVertices[ Dst ] )^.P := TPVertex( FVertices[ I ] )^.P;
Inc( Dst );
end;
end;
for I := 0 to FTriangles.Count - 1 do begin
T := TPTriangle( FTriangles[ I ] );
for J := 0 to 2 do
T^.V[ J ] := TPVertex( FVertices[ T.V[ J ] ] )^.TStart;
end;
for I := Dst to FVertices.Count - 1 do begin
FreeMem( FVertices[ FVertices.Count - 1 ] );
FVertices.Delete( FVertices.Count - 1 );
end;
end;
// compact triangles, compute edge error and build reference list
procedure TMeshSimplifier.UpdateMesh(const Iteration: Integer);
var
I, J, K, TStart, Ofs, Id: Integer;
NewTriangles: TList;
T: TPTriangle;
V: TPVertex;
A, B, N: TVector3;
P: Array [0..2] of TVector3;
M: TSymmetricMatrix;
Ref: TPRef;
VCount, VIds: TList<Integer>;
begin
if Iteration > 0 then begin // compact triangles
NewTriangles := TList.Create;
for I := 0 to FTriangles.Count - 1 do begin
T := FTriangles[ I ];
if not T^.Deleted then
NewTriangles.Add( T )
else
FreeMem( T );
end;
FTriangles.Free;
FTriangles := NewTriangles;
end;
//
// Init Quadrics by Plane & Edge Errors
//
// required at the beginning ( iteration == 0 )
// recomputing during the simplification is not required,
// but mostly improves the result for closed meshes
//
if Iteration = 0 then begin
for I := 0 to FVertices.Count - 1 do begin
V := FVertices[ I ];
MatrixInit( @(V^.Q), 0.0 );
end;
for I := 0 to FTriangles.Count - 1 do begin
T := FTriangles[ I ];
for J := 0 to 2 do
P[ J ] := TPVertex( FVertices[ T.V[ J ] ] )^.P;
VecSub( @A, @(P[ 1 ]), @(P[ 0 ]) );
VecSub( @B, @(P[ 2 ]), @(P[ 0 ]) );
VecCross( @N, @A, @B );
VecNormalize( @N );
T^.N := N;
for J := 0 to 2 do begin
MatrixInit( @M, N.X, N.Y, N.Z, -VecDot( @N, @P[0] ) );
MatrixAdd( @( TPVertex( FVertices[ T^.V[ J ] ])^.Q ), @( TPVertex( FVertices[ T^.V[ J ] ] )^.Q ), @M );
end;
end;
for I := 0 to FTriangles.Count - 1 do begin
// Calc Edge Error
T := FTriangles[ I ];
for J := 0 to 2 do
T^.Err[ J ] := CalculateError( T^.V[ J ], T^.V[ (J + 1) mod 3 ], @A );
T^.Err[ 3 ] := Min( T^.Err[ 0 ], Min( T^.Err[ 1 ], T^.Err[ 2 ] ) );
end;
end;
// Init Reference ID list
for I := 0 to FVertices.Count - 1 do begin
TPVertex( FVertices[ I ] )^.TStart := 0;
TPVertex( FVertices[ I ] )^.TCount := 0;
end;
for I := 0 to FTriangles.Count - 1 do begin
T := FTriangles[ I ];
for J := 0 to 2 do
Inc( TPVertex( FVertices[ T^.V[ J ] ] )^.TCount );
end;
TStart := 0;
for I := 0 to FVertices.Count - 1 do begin
V := FVertices[ I ];
V^.TStart := TStart;
Inc( TStart, V^.TCount );
V^.TCount := 0;
end;
// Write References
ClearRefs;
for I := 0 to 3 * FTriangles.Count - 1 do begin
GetMem( Ref, SizeOf( TRef ) );
Ref^.TId := 0;
Ref^.TVertex := 0;
FRefs.Add( Ref );
end;
for I := 0 to FTriangles.Count - 1 do begin
T := FTriangles[ I ];
for J := 0 to 2 do begin
V := FVertices[ T^.V[ J ] ];
TPRef( FRefs[ V^.TStart + V^.TCount ] )^.TId := I;
TPRef( FRefs[ V^.TStart + V^.TCount ] )^.TVertex := J;
Inc( V^.TCount );
end;
end;
// Identify boundary : vertices[].border=0,1
if Iteration = 0 then begin
VCount := TList<Integer>.Create;
try
VIds := TList<Integer>.Create;
try
for I := 0 to FVertices.Count - 1 do
TPVertex( FVertices[ I ] )^.Border := False;
for I := 0 to FVertices.Count - 1 do begin
V := FVertices[ I ];
VCount.Clear;
VIds.Clear;
for J := 0 to V^.TCount - 1 do begin
K := TPRef( FRefs[ V^.TStart + J ] )^.TId;
T := FTriangles[ K ];
for K := 0 to 2 do begin
Ofs := 0;
Id := T^.V[ K ];
while Ofs < VCount.Count do begin
if VIds[Ofs]=Id then
break;
Inc( Ofs );
end;
if Ofs =VCount.Count then begin
VCount.Add( 1 );
VIds.Add( Id );
end
else
VCount[ Ofs ] := VCount[ Ofs ] + 1;
end;
end;
for J := 0 to VCount.Count - 1 do begin
if VCount[ J ] =1 then
TPVertex( FVertices[ VIds[ J ] ] )^.Border := True;
end;
end;
finally
VIds.Free;
end;
finally
VCount.Free;
end;
end;
end;
procedure TMeshSimplifier.MatrixInit( M: TPSymmetricMatrix; const C: Single );
var
I: Integer;
begin
for I := Low( M^.M ) to High( M^.M ) do
M^.M[ I ] := C;
end;
// Make plane
procedure TMeshSimplifier.MatrixInit( M: TPSymmetricMatrix; const A, B, C, D: Single );
begin
M^.M[ 0 ] := A * A; M^.M[ 1 ] := A * B; M^.M[ 2 ] := A * C; M^.M[ 3 ] := A * D;
M^.M[ 4 ] := B * B; M^.M[ 5 ] := B * C; M^.M[ 6 ] := B * D;
M^.M[ 7 ] := C * C; M^.M[ 8 ] := C * D;
M^.M[ 9 ] := D * D;
end;
procedure TMeshSimplifier.MatrixAdd( Dest: TPSymmetricMatrix; const A, B: TPSymmetricMatrix );
var
I: Integer;
begin
for I := Low( Dest^.M ) to High( Dest^.M ) do
Dest^.M[ I ] := A^.M[ I ] + B^.M[ I ];
end;
// Determinant
function TMeshSimplifier.MatrixDet( const M: TPSymmetricMatrix; const A11, A12, A13, A21, A22, A23, A31, A32, A33: Integer): Single;
begin
Result := M^.M[ A11 ] * M^.M[ A22 ] * M^.M[ A33 ] + M^.M[ A13 ] * M^.M[ A21 ] * M^.M[ A32 ] +
M^.M[ A12 ] * M^.M[ A23 ] * M^.M[ A31 ] - M^.M[ A13 ] * M^.M[ A22 ] * M^.M[ A31 ] -
M^.M[ A11 ] * M^.M[ A23 ] * M^.M[ A32 ] - M^.M[ A12 ] * M^.M[ A21 ] * M^.M[ A33 ];
end;
// Check if a triangle flips when this edge is removed
function TMeshSimplifier.Flipped( const P: TPVector3; const I0, I1: Integer; const V0, V1: TPVertex; var Deleted: Array of Boolean ): Boolean;
var
K, S, Id1, Id2: Integer;
T: TPTriangle;
D1, D2, N: TVector3;
begin
for K := 0 to V0^.TCount - 1 do begin
T := FTriangles[ TPRef ( FRefs[ V0^.TStart + K ] )^.TId];
if T.Deleted then
Continue;
S := TPRef( FRefs[ V0^.TStart + K ] )^.TVertex;
Id1 := T^.V[ ( S + 1) mod 3 ];
Id2 := T^.V[ ( S + 2) mod 3 ];
if ( Id1 = I1 ) or ( Id2 = I1) then begin // delete ?
Deleted[ K ] := True;
continue;
end;
VecSub( @D1, @( TPVertex( FVertices[ Id1 ] )^.P ), P);
VecNormalize( @D1 );
VecSub( @D2, @( TPVertex( FVertices[ Id2 ] )^.P ), P);
VecNormalize( @D2 );
if( Abs( VecDot( @D1, @D2) ) > 0.999 ) then begin
Result := True;
Exit;
end;
VecCross( @N, @D1, @D2 );
VecNormalize( @N );
Deleted[ K ] := False;
if VecDot( @N, @( T^.N ) ) < 0.2 then begin
Result := True;
Exit;
end;
end;
Result := False;
end;
end.
|
// Ported CrystalDiskInfo (The MIT License, http://crystalmark.info)
unit SMARTSupport.Fallback.SSD;
interface
uses
BufferInterpreter, Device.SMART.List, SMARTSupport,
Support;
type
TSSDFallbackSMARTSupport = class(TSMARTSupport)
public
function IsThisStorageMine(
const IdentifyDevice: TIdentifyDeviceResult;
const SMARTList: TSMARTValueList): Boolean; override;
function GetTypeName: String; override;
function IsSSD: Boolean; override;
function IsInsufficientSMART: Boolean; override;
function GetSMARTInterpreted(
const SMARTList: TSMARTValueList): TSMARTInterpreted; override;
function IsWriteValueSupported(const SMARTList: TSMARTValueList): Boolean;
override;
end;
implementation
{ TSSDFallbackSMARTSupport }
function TSSDFallbackSMARTSupport.GetTypeName: String;
begin
result := 'SmartSsd';
end;
function TSSDFallbackSMARTSupport.IsInsufficientSMART: Boolean;
begin
result := true;
end;
function TSSDFallbackSMARTSupport.IsSSD: Boolean;
begin
result := true;
end;
function TSSDFallbackSMARTSupport.IsThisStorageMine(
const IdentifyDevice: TIdentifyDeviceResult;
const SMARTList: TSMARTValueList): Boolean;
begin
result := CheckIsSSDInCommonWay(IdentifyDevice);
end;
function TSSDFallbackSMARTSupport.IsWriteValueSupported(
const SMARTList: TSMARTValueList): Boolean;
begin
result := false;
end;
function TSSDFallbackSMARTSupport.GetSMARTInterpreted(
const SMARTList: TSMARTValueList): TSMARTInterpreted;
begin
FillChar(result, SizeOf(result), 0);
end;
end.
|
{
ctypesmapping.pas
Copyright (C) 2011 Andrew Haines andrewd207@aol.com
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
}
unit girCTypesMapping;
{$mode objfpc}{$H+}
interface
const
CTypesMax = 34;
var
TypesPascalCTypes: array [0..CTypesMax-1] of string =
(
'void',
'pointer',
'cint',
'cint',
'cuint',
'cuint8',
'cuint16',
'cuint32',
'cuint64',
'cint8',
'cint16',
'cint32',
'cint64',
'csize_t',
'clong',
'culong',
'cushort',
'cshort',
'char',
'byte',
'Boolean32',
'PtrInt',
'csize_t',
'gpointer',
'cfloat',
'cdouble',
'cdouble',
'char',
'Int64',
'Extended',
'guint32',
'guint32',
'file',
'qword'
);
TypesGTypes: array [0..CTypesMax-1] of string =
(
'void',
'gpointer',
'int',
'gint',
'guint',
'guint8',
'guint16',
'guint32',
'guint64',
'gint8',
'gint16',
'gint32',
'gint64',
'gsize',
'glong',
'gulong',
'gushort',
'gshort',
'gchar',
'guchar',
'gboolean',
'gssize',
'size_t' ,
'gconstpointer',
'gfloat',
'gdouble',
'double',
'char',
'goffset',
'long double',
'gunichar',
'gunichar2',
'file',
'unsigned long long'
);
function LookupGTypeToCType(AName: String): String;
implementation
function LookupGTypeToCType(AName: String): String;
var
i: Integer;
begin
//WriteLn('Looking up: ', AName);
for i := 0 to CTypesMax-1 do
if AName = TypesGTypes[i] then
Exit(TypesPascalCTypes[i]);
Result := '';
end;
end.
|
unit TestForIn;
interface
implementation
type
TStringArray = array of String;
procedure Demo1(const List: TStringArray);
var
S: String;
begin
for S in List do
writeln(S);
end;
end.
|
{----------------------------------------------------------------------------}
{ Written by Nguyen Le Quang Duy }
{ Nguyen Quang Dieu High School, An Giang }
{----------------------------------------------------------------------------}
Program FIRS;
Type
Note =Record id,va :LongInt end;
Var
n,res :LongInt;
A :Array[0..100001] of Note;
Free :Array[0..100001] of Boolean;
procedure Enter;
var
i :LongInt;
begin
ReadLn(n);
for i:=1 to n do
begin
A[i].id:=i; Read(A[i].va);
end;
end;
procedure QSort(l,r :LongInt);
var
i,j :LongInt;
Key,Tmp :Note;
begin
if (l>=r) then Exit;
i:=l; j:=r; Key:=A[(l+r) div 2];
repeat
while (A[i].va<Key.va) do Inc(i);
while (A[j].va>Key.va) do Dec(j);
if (i<=j) then
begin
if (A[i].va<>A[j].va) then
begin
Tmp:=A[i]; A[i]:=A[j]; A[j]:=Tmp;
end;
Inc(i); Dec(j);
end;
until (i>j);
QSort(l,j); QSort(i,r);
end;
procedure Greedy;
var
i :LongInt;
begin
FillChar(Free,SizeOf(Free),true);
Free[0]:=false; Free[n+1]:=false;
res:=0;
for i:=1 to n do
if (Free[A[i].id]) then
begin
Inc(res);
Free[A[i].id]:=false;
if (Free[A[i].id-1]) then Free[A[i].id-1]:=false;
if (Free[A[i].id+1]) then Free[A[i].id+1]:=false;
end;
end;
Begin
Assign(Input,''); Reset(Input);
Assign(Output,''); Rewrite(Output);
Enter;
QSort(1,n);
Greedy;
Write(res);
Close(Input); Close(Output);
End. |
UNIT PARSE;
(* parse a string *)
interface
CONST
(* Most args that will be parsed *)
MaxArg = 50;
PROCEDURE ParseString( VAR strc : WORD;
instr : STRING;
delim : CHAR);
(* the number of args in instr is returned in strc *)
(* delim is the argument delimiter, normally ' ' *)
FUNCTION argstr(argindex : WORD) : STRING;
(* extract string argindex from parsestring. Returns null *)
(* string if none to retrieve *)
(****************************************************************)
implementation
TYPE
args = ARRAY[1..MaxArg] OF ^STRING;
VAR
OrigExit : POINTER;
arg : ^args;
argcount : WORD;
{+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}
PROCEDURE AddArg(VAR pstr : STRING);
BEGIN
IF NOT (argcount + 1 > MaxArg) THEN
BEGIN
inc(argcount); { increment internal counter }
new(arg^[argcount]); { make new string pointer }
arg^[argcount]^ := pstr;
pstr := '';
END;
END;
{+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}
PROCEDURE ParseString( VAR strc : WORD;
instr : STRING;
delim : CHAR);
(* argc is the number of args, argv is a pointer to an array of string *)
(* pointers argv^[1]^ is a string *)
VAR
len,
i : WORD;
pstr : STRING;
BEGIN
IF (arg <> NIL) AND (argcount > 0) THEN
BEGIN
FOR i := 1 to argcount DO Dispose(arg^[i]);
argcount := 0;
END;
pstr := '';
len := length(instr);
i := 1;
REPEAT
IF (instr[i] = delim) AND (length(pstr) > 0) THEN
AddArg(pstr);
WHILE instr[i] = delim DO inc(i);
IF (i < len + 1) THEN pstr := pstr + instr[i];
inc(i);
UNTIL i > len;
(* add final string, if any *)
IF (length(pstr) > 0) THEN
AddArg(pstr);
argc := argcount;
END;
{+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}
FUNCTION argstr(argindex : WORD) : STRING;
BEGIN
IF argindex > argcount THEN
argstr := ''
ELSE
argstr := arg^[argindex]^
END;
{+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}
{$F+} PROCEDURE ClearParse; {$F-}
VAR
i : WORD;
BEGIN
IF (argcount > 0) THEN
BEGIN
FOR i := 1 to argcount DO Dispose(arg^[i]);
argcount := 0;
END;
Dispose(arg);
ExitProc := OrigExit;
END;
{+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}
BEGIN
OrigExit := ExitProc;
ExitProc := @ClearParse;
argcount := 0;
new(arg); { make new array of pointers }
END.
|
{
@html(<b>)
HTTP Server Connection
@html(</b>)
- Copyright (c) Danijel Tkalcec
@html(<br><br>)
Introducing the @html(<b>) @Link(TRtcHttpServer) @html(</b>) component:
@html(<br>)
Server connection component for TCP/IP communication using HTTP requests.
Received data will be processed to gather Request information and
make it easily accessible through the @Link(TRtcDataServer.Request) property.
The same way, your response will be packed into a HTTP result header
and sent out as a valid HTTP result, readable by any Web Browser.
@Link(TRtcHttpServer) also makes sure that you receive requests one by one,
even if the client side sends all requests at once (as one big request list).
}
unit rtcHttpSrv;
{$INCLUDE rtcDefs.inc}
interface
uses
Classes,
rtcInfo,
rtcConn,
rtcFastStrings,
rtcPlugins,
rtcDataSrv;
type
{ @Abstract(Server Connection component for direct TCP/IP communication using the HTTP protocol)
Received data will be processed by TRtcHttpServer to gather Request
information and make it easily accessible through the
@Link(TRtcDataServer.Request) property.
The same way, your response will be packed into a HTTP result header
and sent out as a valid HTTP result, readable by any Web Browser.
@html(<br>)
@Link(TRtcHttpServer) also makes sure that you receive requests one by one
and get the chance to answer them one-by-one, even if the client side
sends all the requests at once (as one big request list), so
you can relax and process all incomming requests, without worrying
about overlapping your responses for different requests.
@html(<br><br>)
Properties to check first:
@html(<br>)
@Link(TRtcConnection.ServerAddr) - Local Address to bind the server to (leave empty for ALL)
@html(<br>)
@Link(TRtcConnection.ServerPort) - Port to listen on and wait for connections
@html(<br><br>)
Methods to check first:
@html(<br>)
@Link(TRtcServer.Listen) - Start server
@html(<br>)
@Link(TRtcDataServer.Request), @Link(TRtcConnection.Read) - Read client request
@html(<br>)
@Link(TRtcDataServer.Response), @Link(TRtcHttpServer.WriteHeader), @Link(TRtcHttpServer.Write) - Write result to client
@html(<br>)
@Link(TRtcConnection.Disconnect) - Disconnect client
@html(<br>)
@Link(TRtcServer.StopListen) - Stop server
@html(<br><br>)
Events to check first:
@html(<br>)
@Link(TRtcServer.OnListenStart) - Server started
@html(<br>)
@Link(TRtcConnection.OnConnect) - new Client connected
@html(<br>)
@Link(TRtcConnection.OnDisconnect) - one Client disconnected
@html(<br>)
@Link(TRtcServer.OnListenStop) - Server stopped
@html(<br><br>)
Check @Link(TRtcDataServer), @Link(TRtcServer) and @Link(TRtcConnection) for more info.
}
TRtcHttpServer = class(TRtcDataServer)
private
FCryptPlugin:TRtcCryptPlugin;
// User Parameters
FMaxRequestSize:cardinal;
FMaxHeaderSize:cardinal;
FOnInvalidRequest:TRtcNotifyEvent;
FWritten:boolean;
FWriteBuffer:TRtcHugeString;
protected
// @exclude
procedure CopyFrom(Dup: TRtcServer); override;
// @exclude
procedure SetTriggers; override;
// @exclude
procedure ClearTriggers; override;
// @exclude
procedure SetParams; override;
// @exclude
function CreateProvider:TObject; override;
// @exclude
procedure TriggerDataSent; override;
// @exclude
procedure TriggerDataReceived; override;
// @exclude
procedure TriggerDataOut; override;
// @exclude
procedure TriggerInvalidRequest; virtual;
// @exclude
procedure CallInvalidRequest; virtual;
// @exclude
procedure SetRequest(const Value: TRtcServerRequest); override;
// @exclude
procedure SetResponse(const Value: TRtcServerResponse); override;
public
// @exclude
constructor Create(AOwner: TComponent); override;
// @exclude
destructor Destroy; override;
// Constructor
class function New:TRtcHttpServer;
{ Flush all buffered data.
@html(<br>)
When using 'Write' without calling 'WriteHeader' before, all data
prepared by calling 'Write' will be buffered until your event
returns to its caller (automatically upon your event completion) or
when you first call 'Flush'. Flush will check if Response.ContentLength is set
and if not, will set the content length to the number of bytes buffered.
@html(<br>)
Flush does nothing if WriteHeader was called for this response.
@exclude}
procedure Flush; override;
// You can call WriteHeader to send the Response header out.
procedure WriteHeader(SendNow:boolean=True); overload; override;
{ You can call WriteHeader with empty 'HeaderText' parameter to
tell the component that you do not want any HTTP header to be sent. }
procedure WriteHeader(const HeaderText: string; SendNow:boolean=True); overload; override;
// Use Write to send the Content (document body) out.
procedure Write(const s:string=''); override;
published
{ Maximum allowed size of the request, without header (0 = no limit).
This is the first line in a HTTP request and includes Request.Method and Request.URI }
property MaxRequestSize:cardinal read FMaxRequestSize write FMaxRequestSize default 0;
{ Maximum allowed size of each request's header size (0 = no limit).
This are all the remaining header lines in a HTTP request,
which come after the first line and end with an empty line,
after which usually comes the content (document body). }
property MaxHeaderSize:cardinal read FMaxHeaderSize write FMaxHeaderSize default 0;
{ This event will be called if the received request exceeds your defined
maximum request or header size. If both values are 0, this event will never be called. }
property OnInvalidRequest:TRtcNotifyEvent read FOnInvalidRequest write FOnInvalidRequest;
{ To use SSL/SSH encryption, assign the encryption plug-in here,
before you first start the Server Listener. }
property CryptPlugin:TRtcCryptPlugin read FCryptPlugin write FCryptPlugin;
end;
implementation
uses
SysUtils,
rtcConnProv,
rtcWSockHttpSrvProv; // WSocket HTTP Server Provider
type
TMyProvider = TRtcWSockHttpServerProvider;
class function TRtcHttpServer.New: TRtcHttpServer;
begin
Result:=Create(nil);
end;
{ TRtcHttpServer }
function TRtcHttpServer.CreateProvider:TObject;
begin
if not assigned(Con) then
begin
Con:=TMyProvider.Create;
SetTriggers;
end;
Result:=Con;
end;
procedure TRtcHttpServer.CopyFrom(Dup: TRtcServer);
begin
inherited CopyFrom(Dup);
MaxRequestSize:=TRtcHttpServer(Dup).MaxRequestSize;
MaxHeaderSize:=TRtcHttpServer(Dup).MaxHeaderSize;
OnInvalidRequest:=TRtcHttpServer(Dup).OnInvalidRequest;
CryptPlugin:=TRtcHttpServer(Dup).CryptPlugin;
end;
procedure TRtcHttpServer.SetParams;
begin
inherited;
if assigned(Con) then
begin
TMyProvider(Con).Request:=Request;
TMyProvider(Con).Response:=Response;
TMyProvider(Con).MaxRequestSize:=MaxRequestSize;
TMyProvider(Con).MaxHeaderSize:=MaxHeaderSize;
end;
end;
procedure TRtcHttpServer.SetTriggers;
begin
inherited;
if assigned(Con) then
begin
TMyProvider(Con).CryptPlugin:=CryptPlugin;
{$IFDEF FPC}
TMyProvider(Con).SetTriggerInvalidRequest(@TriggerInvalidRequest);
{$ELSE}
TMyProvider(Con).SetTriggerInvalidRequest(TriggerInvalidRequest);
{$ENDIF}
end;
end;
procedure TRtcHttpServer.ClearTriggers;
begin
inherited;
if assigned(Con) then
begin
TMyProvider(Con).CryptPlugin:=nil;
TMyProvider(Con).SetTriggerInvalidRequest(nil);
end;
end;
procedure TRtcHttpServer.WriteHeader(SendNow:boolean=True);
begin
if assigned(Con) and (State<>conInactive) then
begin
if Response.Sending then
raise Exception.Create('Error! Sending multiple headers for one request.');
Timeout.DataSending;
TMyProvider(Con).WriteHeader(SendNow);
end;
end;
procedure TRtcHttpServer.WriteHeader(const HeaderText: string; SendNow:boolean=True);
begin
if assigned(Con) and (State<>conInactive) then
begin
if Response.Sending then
raise Exception.Create('Error! Sending multiple headers for one request.');
Timeout.DataSending;
TMyProvider(Con).WriteHeader(HeaderText, SendNow);
end;
end;
procedure TRtcHttpServer.Write(const s: string='');
begin
if assigned(Con) and (State<>conInactive) then
begin
if Response.Sent then
raise Exception.Create('Error! Answer allready sent for this request.');
if Response.Sending then
begin
{ Header is out }
if Response['Content-Length']<>'' then
if Response.ContentLength - Response.ContentOut < length(s) then
raise Exception.Create('Error! Sending more data out than specified in header.');
{ Data size is known or unimportant.
We can just write the string out, without buffering }
Con.Write(s);
end
else
begin
if (Response['CONTENT-LENGTH']<>'') and not FWritten then // Direct writing if header was sent out.
begin
{ Content length defined and no data buffered,
send out header prior to sending first content bytes }
WriteHeader(length(s)=0);
if Response.ContentLength - Response.ContentOut < length(s) then
raise Exception.Create('Error! Sending more data out than specified in header.');
Con.Write(s);
end
else
begin
{ Header is not out.
Buffer all Write() operations,
so we can determine content size and write it all out in a flush. }
FWritten:=True;
FWriteBuffer.Add(s);
end;
end;
end;
end;
procedure TRtcHttpServer.Flush;
var
Temp:string;
begin
if not FWritten then
Exit
else
FWritten:=False; // so we don't re-enter this method.
if assigned(Con) and (State<>conInactive) then
begin
Timeout.DataSending;
if Response.Sent then
raise Exception.Create('Error! Answer allready sent for this request.');
if not Response.Sending then
begin
if Response['CONTENT-LENGTH']='' then // length not specified
Response.ContentLength:=FWriteBuffer.Size;
TMyProvider(Con).WriteHeader(False);
end;
if FWriteBuffer.Size>0 then
begin
Temp:=FWriteBuffer.Get;
FWriteBuffer.Clear;
Con.Write(Temp);
Temp:='';
end;
end;
end;
procedure TRtcHttpServer.CallInvalidRequest;
begin
if assigned(OnInvalidRequest) then
OnInvalidRequest(self);
end;
procedure TRtcHttpServer.TriggerDataReceived;
begin
inherited;
Flush;
end;
procedure TRtcHttpServer.TriggerDataSent;
begin
if FWriteCount>0 then
Timeout.DataSent;
EnterEvent;
try
if FWriteCount>0 then
begin
CallDataSent;
Flush;
if Response.Done then
if Request.Close then
Disconnect; // make sure we close the connection, as requested by the client.
end;
if not isClosing then
begin
CallReadyToSend;
Flush;
if (FWriteCount>0) and Response.Done then
if Request.Close then
Disconnect; // make sure we close the connection, as requested by the client.
end;
finally
LeaveEvent;
end;
end;
procedure TRtcHttpServer.TriggerDataOut;
begin
inherited;
Flush;
end;
procedure TRtcHttpServer.TriggerInvalidRequest;
begin
EnterEvent;
try
CallInvalidRequest;
Flush;
Disconnect;
finally
LeaveEvent;
end;
end;
constructor TRtcHttpServer.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FWriteBuffer:=TRtcHugeString.Create;
FWritten:=False;
end;
destructor TRtcHttpServer.Destroy;
begin
FWriteBuffer.Free;
inherited;
end;
procedure TRtcHttpServer.SetRequest(const Value: TRtcServerRequest);
begin
inherited SetRequest(Value);
if assigned(Con) then
TMyProvider(Con).Request:=Request;
end;
procedure TRtcHttpServer.SetResponse(const Value: TRtcServerResponse);
begin
inherited SetResponse(Value);
if assigned(Con) then
TMyProvider(Con).Response:=Response;
end;
end.
|
unit IdStackConsts;
interface
uses
{$IFDEF LINUX}
Libc;
{$ELSE}
IdWinsock;
{$ENDIF}
type
TIdStackSocketHandle = TSocket;
var
Id_SO_True: Integer = 1;
Id_SO_False: Integer = 0;
const
{$IFDEF LINUX}
TCP_NODELAY = 1;
{$ENDIF}
// Protocol Family
Id_PF_INET = PF_INET;
// Socket Type
Id_SOCK_STREAM = Integer(SOCK_STREAM);
Id_SOCK_DGRAM = Integer(SOCK_DGRAM);
Id_SOCK_RAW = Integer(SOCK_RAW);
// IP Protocol type
Id_IPPROTO_IP = IPPROTO_IP;
Id_IPPROTO_ICMP = IPPROTO_ICMP;
Id_IPPROTO_IGMP = IPPROTO_IGMP;
Id_IPPROTO_TCP = IPPROTO_TCP;
Id_IPPROTO_UDP = IPPROTO_UDP;
Id_IPPROTO_RAW = IPPROTO_RAW;
Id_IPPROTO_MAX = IPPROTO_MAX;
// Socket Option level
Id_SOL_SOCKET = SOL_SOCKET;
// Socket options
Id_SO_BROADCAST = SO_BROADCAST;
Id_SO_DEBUG = SO_DEBUG;
Id_SO_DONTROUTE = SO_DONTROUTE;
Id_SO_KEEPALIVE = SO_KEEPALIVE;
Id_SO_LINGER = SO_LINGER;
Id_SO_OOBINLINE = SO_OOBINLINE;
Id_SO_RCVBUF = SO_RCVBUF;
Id_SO_REUSEADDR = SO_REUSEADDR;
Id_SO_SNDBUF = SO_SNDBUF;
// Additional socket options
Id_SO_RCVTIMEO = SO_RCVTIMEO;
Id_SO_SNDTIMEO = SO_SNDTIMEO;
Id_IP_TTL = IP_TTL;
//
Id_INADDR_ANY = INADDR_ANY;
Id_INADDR_NONE = INADDR_NONE;
// TCP Options
Id_TCP_NODELAY = TCP_NODELAY;
Id_INVALID_SOCKET = INVALID_SOCKET;
Id_SOCKET_ERROR = SOCKET_ERROR;
//
{$IFDEF LINUX}
// Shutdown Options
Id_SD_Recv = SHUT_RD;
Id_SD_Send = SHUT_WR;
Id_SD_Both = SHUT_RDWR;
//
Id_WSAEINTR = EINTR;
Id_WSAEBADF = EBADF;
Id_WSAEACCES = EACCES;
Id_WSAEFAULT = EFAULT;
Id_WSAEINVAL = EINVAL;
Id_WSAEMFILE = EMFILE;
Id_WSAEWOULDBLOCK = EWOULDBLOCK;
Id_WSAEINPROGRESS = EINPROGRESS;
Id_WSAEALREADY = EALREADY;
Id_WSAENOTSOCK = ENOTSOCK;
Id_WSAEDESTADDRREQ = EDESTADDRREQ;
Id_WSAEMSGSIZE = EMSGSIZE;
Id_WSAEPROTOTYPE = EPROTOTYPE;
Id_WSAENOPROTOOPT = ENOPROTOOPT;
Id_WSAEPROTONOSUPPORT = EPROTONOSUPPORT;
Id_WSAESOCKTNOSUPPORT = ESOCKTNOSUPPORT;
Id_WSAEOPNOTSUPP = EOPNOTSUPP;
Id_WSAEPFNOSUPPORT = EPFNOSUPPORT;
Id_WSAEAFNOSUPPORT = EAFNOSUPPORT;
Id_WSAEADDRINUSE = EADDRINUSE;
Id_WSAEADDRNOTAVAIL = EADDRNOTAVAIL;
Id_WSAENETDOWN = ENETDOWN;
Id_WSAENETUNREACH = ENETUNREACH;
Id_WSAENETRESET = ENETRESET;
Id_WSAECONNABORTED = ECONNABORTED;
Id_WSAECONNRESET = ECONNRESET;
Id_WSAENOBUFS = ENOBUFS;
Id_WSAEISCONN = EISCONN;
Id_WSAENOTCONN = ENOTCONN;
Id_WSAESHUTDOWN = ESHUTDOWN;
Id_WSAETOOMANYREFS = ETOOMANYREFS;
Id_WSAETIMEDOUT = ETIMEDOUT;
Id_WSAECONNREFUSED = ECONNREFUSED;
Id_WSAELOOP = ELOOP;
Id_WSAENAMETOOLONG = ENAMETOOLONG;
Id_WSAEHOSTDOWN = EHOSTDOWN;
Id_WSAEHOSTUNREACH = EHOSTUNREACH;
Id_WSAENOTEMPTY = ENOTEMPTY;
{$ELSE}
// Shutdown Options
Id_SD_Recv = 0;
Id_SD_Send = 1;
Id_SD_Both = 2;
//
Id_WSAEINTR = WSAEINTR;
Id_WSAEBADF = WSAEBADF;
Id_WSAEACCES = WSAEACCES;
Id_WSAEFAULT = WSAEFAULT;
Id_WSAEINVAL = WSAEINVAL;
Id_WSAEMFILE = WSAEMFILE;
Id_WSAEWOULDBLOCK = WSAEWOULDBLOCK;
Id_WSAEINPROGRESS = WSAEINPROGRESS;
Id_WSAEALREADY = WSAEALREADY;
Id_WSAENOTSOCK = WSAENOTSOCK;
Id_WSAEDESTADDRREQ = WSAEDESTADDRREQ;
Id_WSAEMSGSIZE = WSAEMSGSIZE;
Id_WSAEPROTOTYPE = WSAEPROTOTYPE;
Id_WSAENOPROTOOPT = WSAENOPROTOOPT;
Id_WSAEPROTONOSUPPORT = WSAEPROTONOSUPPORT;
Id_WSAESOCKTNOSUPPORT = WSAESOCKTNOSUPPORT;
Id_WSAEOPNOTSUPP = WSAEOPNOTSUPP;
Id_WSAEPFNOSUPPORT = WSAEPFNOSUPPORT;
Id_WSAEAFNOSUPPORT = WSAEAFNOSUPPORT;
Id_WSAEADDRINUSE = WSAEADDRINUSE;
Id_WSAEADDRNOTAVAIL = WSAEADDRNOTAVAIL;
Id_WSAENETDOWN = WSAENETDOWN;
Id_WSAENETUNREACH = WSAENETUNREACH;
Id_WSAENETRESET = WSAENETRESET;
Id_WSAECONNABORTED = WSAECONNABORTED;
Id_WSAECONNRESET = WSAECONNRESET;
Id_WSAENOBUFS = WSAENOBUFS;
Id_WSAEISCONN = WSAEISCONN;
Id_WSAENOTCONN = WSAENOTCONN;
Id_WSAESHUTDOWN = WSAESHUTDOWN;
Id_WSAETOOMANYREFS = WSAETOOMANYREFS;
Id_WSAETIMEDOUT = WSAETIMEDOUT;
Id_WSAECONNREFUSED = WSAECONNREFUSED;
Id_WSAELOOP = WSAELOOP;
Id_WSAENAMETOOLONG = WSAENAMETOOLONG;
Id_WSAEHOSTDOWN = WSAEHOSTDOWN;
Id_WSAEHOSTUNREACH = WSAEHOSTUNREACH;
Id_WSAENOTEMPTY = WSAENOTEMPTY;
{$ENDIF}
implementation
end.
|
unit U_ComComm;
{
*功能:串口异步通讯,协议解释
}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls,
Dialogs, StdCtrls, ExtCtrls,DateUtils,U_MyFunction;
const WM_COMM_RECEIVE_DATA = WM_USER + 11111;
//线程状态
type TThreadStatus=(
ThreadStatus_Freeed,//0-已释放;
ThreadStatus_Running,//1-正在运行;
ThreadStatus_TerminateNotFree,//2-已终止但未释放;
ThreadStatus_NotExist//3-未建立或不存在
);
type
//线程声明
TO_ComComm=Class(TThread)
private
m_hcom:Thandle;//串口句柄
m_Overlapped:TOverlapped;
m_bComOpened:bool;//是否打开串口
m_bSendData:bool;//是否正在发送数据,从开始发送~~收到数据前或超时前为true
m_bSendInterval:bool;//是否要通知发送间隔时间到了,true为要通知,false为不要通知
m_DTWrite:TDateTime;//发送数据时刻
m_lwHandle:LongWord;//帧标识
m_ReadBuffer:array[0..4095] of byte;//读取数据缓冲区
m_nPos:integer;//指向m_ReadBuffer下一个要写入的位置,即当前m_ReadBuffer的长度
function CheckThreadStatus(aThread:TThread):TThreadStatus;
Published
protected
procedure Execute;override;
public
m_WriteBuffer:array[0..1023] of byte;//发送数据缓冲区
m_nTimeOut:Int64;//读取超时
m_SendInterval:integer;//发送间隔 ms
//m_protocol:TProtocol;//协议类型
m_frame_interval : Integer;
function SetHandle(lwHandle:LongWord):Boolean;
function IniCom(nPort,nBaudRate:integer;nParity:integer=NOPARITY;nDataBits:integer=8;nStopBits:integer=ONESTOPBIT):Boolean;
function SetComParam(nBaudRate:integer;nParity:integer=NOPARITY;nDataBits:integer=8;nStopBits:integer=ONESTOPBIT):Boolean;
function WriteCom(nHandle:integer;sendBuffer:PByte;nNumberOfBytesToWrite:DWORD):DWORD;
function UniniCom():Boolean;
function IsComOpen():Boolean;
function SetFrameInterval(interval:integer):Boolean;
constructor Create();
end;
var O_ComComm:TO_ComComm;
implementation
function TO_ComComm.SetHandle(lwHandle:LongWord):Boolean;
begin
m_lwHandle := lwHandle;
end;
function TO_ComComm.SetFrameInterval(interval:integer):Boolean;
begin
m_frame_interval := interval;
end;
function TO_ComComm.IsComOpen():Boolean;
begin
if m_hcom = INVALID_HANDLE_VALUE then
begin
Result:=False;
end
else
begin
Result:=True;
end;
end;
constructor TO_ComComm.Create();
begin
m_nTimeOut:=10*1000;
m_DTWrite:=Now();
m_hcom := INVALID_HANDLE_VALUE;
m_bComOpened:=False;
m_bSendData:=False;
m_nPos:=0;
m_SendInterval:=500;
m_bSendInterval:=false;
fillchar(m_ReadBuffer,sizeof(m_ReadBuffer),0);
inherited create(True);
//Priority:=tpidle;
Priority:=tpTimeCritical;
//m_frame_interval := 15;
//m_frame_interval := 100;
m_frame_interval := 40;//适合300波特率,分帧
end;
function TO_ComComm.IniCom(nPort,nBaudRate:integer;nParity:integer=NOPARITY;nDataBits:integer=8;nStopBits:integer=ONESTOPBIT):Boolean;
var lpdcb:Tdcb;
pcCom:pchar;
begin
Result := False;
m_bComOpened := False;
if m_hcom <> INVALID_HANDLE_VALUE then
begin
outputdebugstring(pchar('if m_hcom <> INVALID_HANDLE_VALUE then')) ;
UniniCom();
Sleep(100);
end;
pcCom:=pchar('com'+inttostr(nPort));
m_hcom:=createfile(pcCom,
generic_read or generic_write,
0,
nil,
open_existing,
file_attribute_normal or file_flag_overlapped,
0);//打开串行口
if m_hcom = INVALID_HANDLE_VALUE then Exit;
//指定串行口事件为接收到字符; EV_RXCHAR or EV_CTS or EV_DSR or EV_RING
//EV_BREAK or EV_CTS or EV_DSR or EV_ERR or EV_RING or EV_RLSD or EV_RXCHAR or EV_RXFLAG or EV_TXEMPTY
if not setcommMask(m_hcom,EV_RXCHAR or EV_CTS or EV_DSR or EV_RING) then
begin
UniniCom();
Exit;
end;
if not setupcomm(m_hcom,4096,4096) then //设置输入、输出缓冲区皆为4096字节
begin
UniniCom();
Exit;
end;
if not getcommstate(m_hcom,lpdcb) then //获取串行口当前默认设置
begin
UniniCom();
Exit;
end;
lpdcb.baudrate:=nBaudRate;
lpdcb.StopBits:=nStopBits;
lpdcb.Parity:=nParity;
lpdcb.ByteSize:=nDataBits;
if not Setcommstate(m_hcom,lpdcb) then
begin
UniniCom();
Exit;
end;
m_bComOpened := True;
Result:=m_bComOpened;
if Suspended then
Resume();
end;
function TO_ComComm.SetComParam(nBaudRate:integer;nParity:integer=NOPARITY;nDataBits:integer=8;nStopBits:integer=ONESTOPBIT):Boolean;
var lpdcb:Tdcb;
begin
Result := False;
if m_hcom = INVALID_HANDLE_VALUE then Exit;
if not getcommstate(m_hcom,lpdcb) then Exit;
lpdcb.baudrate:=nBaudRate;
lpdcb.StopBits:=nStopBits;
lpdcb.Parity:=nParity;
lpdcb.ByteSize:=nDataBits;
if not Setcommstate(m_hcom,lpdcb) then Exit;
Result := True;
end;
function TO_ComComm.UniniCom():Boolean;
begin
//Comm.Terminate;Comm.WaitFor;
setcommMask(m_hcom,DWORD(Nil));
if m_hcom <> INVALID_HANDLE_VALUE then
begin
if CloseHandle(m_hcom)=true then
begin
m_hcom := INVALID_HANDLE_VALUE;
result:=true;
end
else
begin
result:=false;
setcommMask(m_hcom,EV_RXCHAR or EV_CTS or EV_DSR or EV_RING);
exit;
end;
end;
result:=true;
m_bComOpened:=False;
end;
//返回值:0-已释放;1-正在运行;2-已终止但未释放;3-未建立或不存在
function TO_ComComm.CheckThreadStatus(aThread: TThread): TThreadStatus;
var
i: DWord;
IsQuit: Boolean;
begin
if Assigned(aThread) then
begin
IsQuit := GetExitCodeThread(aThread.Handle, i);
if IsQuit then //If the function succeeds, the return value is nonzero.//If the function fails, the return value is zero.
begin
if i = STILL_ACTIVE then //If the specified thread has not terminated,//the termination status returned is STILL_ACTIVE.
Result := ThreadStatus_Running
else
Result := ThreadStatus_TerminateNotFree; //aThread未Free,因为Tthread.Destroy中有执行语句
end
else
Result := ThreadStatus_Freeed; //可以用GetLastError取得错误代码
end
else
Result := ThreadStatus_NotExist;
end;
function TO_ComComm.WriteCom(nHandle:integer;sendBuffer:PByte;nNumberOfBytesToWrite:DWORD):DWORD;
var dwBytesWrite:DWORD;
bWriteStat:BOOL;
begin
outputdebugstring(pchar('发送数据:'+chr($0d)));
result:=0;
if not m_bComOpened then
begin
//if Assigned(m_FReceiveEvent) then m_FReceiveEvent(m_lwHandle,UMType_Com_Not_Opened,sendBuffer,0);
Exit;
end;
//PurgeComm(m_hcom,PURGE_TXCLEAR or PURGE_RXCLEAR);//异步清空读缓冲有问题
//if Suspended then Resume();
dwBytesWrite:=0;
m_lwHandle:=nHandle;
//fillchar(m_ReadBuffer,sizeof(m_ReadBuffer),0);
//m_nPos:=0;
bWriteStat:=WriteFile(m_hcom,sendBuffer^,nNumberOfBytesToWrite,dwBytesWrite,@m_Overlapped);
if not bWriteStat then
begin
if GetLastError()=ERROR_IO_PENDING then
begin
//WaitForSingleObject(m_Overlapped.hEvent,INFINITE);
WaitForSingleObject(m_Overlapped.hEvent,5000);
{
if WaitForSingleObject(m_Overlapped.hEvent,5000)<> WAIT_OBJECT_0 then
begin
Exit;
end;
}
end
else
begin
Exit;
end;
end;
//Exit;
m_DTWrite:=Now();
m_bSendData:=true;
m_bSendInterval:=true;
//GetOverlappedResult(m_hcom,m_Overlapped,dwBytesWrite,true);//这句很多时候会死等
result:=nNumberOfBytesToWrite;//result:=dwBytesWrite;
if Suspended then Resume();
end;
Procedure TO_ComComm.Execute; //线程执行过程
var dwEvtMask,lpErrors,lpNumberOfBytesRead:Dword;
Wait,Clear:Boolean;
nNumberOfBytesToRead:Integer;
Coms:Tcomstat;
ErrCode:Integer;
Begin
fillchar(m_Overlapped,sizeof(TOverlapped),0);
While true do
Begin
//Sleep(100);Continue;
lpNumberOfBytesRead:=0;
if Terminated then
break;
if not m_bComOpened then
begin
Suspend();
//Sleep(1);Continue;
end;
dwEvtMask:=0;
Wait := WaitCommEvent(m_hcom,dwevtmask,@m_Overlapped); //等待串行口事件;
Sleep(5);//等待关闭串口
Clear:=Clearcommerror(m_hcom,lpErrors,@Coms);
//ClearCommBreak(m_hcom);
if ( Clear and ( ((dwevtmask and EV_RXCHAR) = EV_RXCHAR) or (Coms.cbInQue>0) ) ) then
begin
if ( (Coms.cbInQue>0) ) then
begin
nNumberOfBytesToRead:=Coms.cbInQue;
while True do
begin
Sleep(m_frame_interval);
Clear := Clearcommerror(m_hcom,lpErrors,@Coms);
//ClearCommBreak(m_hcom);
if (Coms.cbInQue > nNumberOfBytesToRead) then
begin
nNumberOfBytesToRead := Coms.cbInQue;
end
else Break;
end;
if m_nPos+nNumberOfBytesToRead > high(m_ReadBuffer)+1 then
begin
FillChar(m_ReadBuffer, sizeof(m_ReadBuffer),0);
m_nPos:=0;
end;
if nNumberOfBytesToRead>high(m_ReadBuffer)+1 then
nNumberOfBytesToRead := high(m_ReadBuffer)+1;
lpNumberOfBytesRead:=0;
if not ReadFile(m_hcom,m_ReadBuffer[m_nPos],nNumberOfBytesToRead,lpNumberOfBytesRead,@m_Overlapped) then//处理接收数据
begin
if GetLastError()=ERROR_IO_PENDING then
begin
WaitForSingleObject(m_Overlapped.hEvent,INFINITE);
lpNumberOfBytesRead := nNumberOfBytesToRead;
end;
end;
if lpNumberOfBytesRead>0 then
begin
m_nPos := m_nPos + lpNumberOfBytesRead;
SendMessage( m_lwHandle,WM_COMM_RECEIVE_DATA,m_nPos,Integer(@m_ReadBuffer[0]));
//FillChar(m_ReadBuffer,sizeof(m_ReadBuffer),0);
m_nPos := 0;
end;
end;
end;//if (dwevtmask and EV_RXCHAR) = EV_RXCHAR then
end;//while
end;
end.
|
unit ExtraChargeTypeQuery;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, Vcl.StdCtrls, NotifyEvents, DSWrap, BaseEventsQuery;
type
TExtraChargeType = class(TDSWrap)
private
FName: TFieldWrap;
FID: TFieldWrap;
public
constructor Create(AOwner: TComponent); override;
procedure LocateOrAppend(const AName: String);
function Lookup(const AExtraChargeTypeName: String): Variant;
property Name: TFieldWrap read FName;
property ID: TFieldWrap read FID;
end;
TQueryExtraChargeType = class(TQueryBaseEvents)
private
FW: TExtraChargeType;
{ Private declarations }
protected
function CreateDSWrap: TDSWrap; override;
public
constructor Create(AOwner: TComponent); override;
property W: TExtraChargeType read FW;
{ Public declarations }
end;
implementation
{$R *.dfm}
constructor TQueryExtraChargeType.Create(AOwner: TComponent);
begin
inherited;
FW := FDSWrap as TExtraChargeType;
AutoTransaction := False;
end;
function TQueryExtraChargeType.CreateDSWrap: TDSWrap;
begin
Result := TExtraChargeType.Create(FDQuery);
end;
constructor TExtraChargeType.Create(AOwner: TComponent);
begin
inherited;
FID := TFieldWrap.Create(Self, 'ID', '', True);
FName := TFieldWrap.Create(Self, 'Name', 'Наименование');
end;
procedure TExtraChargeType.LocateOrAppend(const AName: String);
begin
if not FDDataSet.LocateEx(Name.FieldName, AName, [lxoCaseInsensitive]) then
begin
TryAppend;
Name.F.AsString := AName;
TryPost;
end;
end;
function TExtraChargeType.Lookup(const AExtraChargeTypeName: String): Variant;
begin
Result := FDDataSet.LookupEx(Name.FieldName, AExtraChargeTypeName,
PKFieldName, [lxoCaseInsensitive]);
end;
end.
|
unit unit1;
interface
implementation
Function DEL_ALL_SPACE(S: String): String;
Var
CNT, N : Integer;
STR, S1 : String;
begin
Result := '';
CNT := 1;
STR := Trim(S);
N := Length(STR);
While CNT <= N do
begin
S1 := Copy(STR, CNT ,1);
if IsKanjiUp(S1) then
begin
If( CNT = N ) Then
Begin
Break;
End
Else
if (S1 = Chr($81))
and (Copy(STR,CNT + 1, 1) = Chr($40)) then
begin
Cnt := Cnt + 1;
End Else Begin
Result := Result + Copy(Str,Cnt, 2);
Cnt := Cnt + 1;
End;
end
else
begin
If( S1 <> Chr($20) ) Then
Begin
Result := Result + S1;
End;
end;
CNT := CNT + 1;
end;
end;
|
unit typeid_2;
interface
implementation
function GetType<T>(const Value: T): string;
begin
case typeid(Value) of
dtInt8: Result := 'i8';
dtInt16: Result := 'i16';
dtInt32: Result := 'i32';
dtInt64: Result := 'i64';
dtUInt8: Result := 'u8';
dtUInt16: Result := 'u16';
dtUInt32: Result := 'u32';
dtUInt64: Result := 'u64';
dtFloat32: Result := 'f32';
dtFloat64: Result := 'f64';
dtstring: Result := 'str';
dtAnsiString: Result := 'astr';
else
Result := 'another';
end;
end;
var
S: string;
procedure Test;
begin
S := GetType(1);
Assert(S = 'u8');
S := GetType(-1);
Assert(S = 'i8');
S := GetType(14.56);
Assert(S = 'f32');
S := GetType('aaa');
Assert(S = 'str');
end;
initialization
Test();
finalization
end. |
unit WiseFocus;
interface
uses
ExtCtrls, SysUtils, DateUtils,
WiseHardware, WiseDaq, WisePort, WiseEncoder, WisePin, WiseLogger,
cbw;
type TWiseFocusState = (FocusIdle, FocusMovingUp, FocusMovingDown );
type TWiseFocus = class(TWiseObject)
private
UpPin, DownPin: TWisePin;
Encoder: TWiseEncoder;
Logger: TWiseLogger;
Timer: TTimer;
lastValue: integer;
fChanging: boolean;
fState: TWiseFocusState;
sameValues: integer;
fSpeed: integer; // ticks/second
stopTime: TDateTime;
stopVal: integer;
public
constructor Create;
destructor Destroy; override;
function GetValue: integer;
procedure SetValue(val: integer);
function GetStateStr: string;
function GetStatus: string;
procedure log(s: string);
procedure StartUp;
procedure StopUp;
procedure StartDown;
procedure StopDown;
procedure FullUp;
procedure FullDown;
procedure Stop;
procedure onTimer(Sender: TObject);
property Value: integer read GetValue write SetValue;
property Changing: boolean read fChanging;
property StateStr: string read GetStateStr;
property Speed: integer read fSpeed;
property Status: string read GetStatus;
end;
implementation
constructor TWiseFocus.Create;
var
specs: TWiseMultiPortSpecs;
begin
if production then begin
Self.DownPin := TWisePin.Create('FocusDownPin', daqId(focusboard, FIRSTPORTCH, DIGITALOUT), 0);
Self.UpPin := TWisePin.Create('FocusUpPin', daqId(focusboard, FIRSTPORTCH, DIGITALOUT), 1)
end else begin
Self.DownPin := TWisePin.Create('FocusDownPin', daqId(domeboard, FIRSTPORTA, DIGITALOUT), 0);
Self.UpPin := TWisePin.Create('FocusUpPin', daqId(domeboard, FIRSTPORTA, DIGITALOUT), 1)
end;
SetLength(specs, 2);
if production then begin
specs[0].daqid := daqId(focusboard, FIRSTPORTA, DIGITALIN); // bit[0..2] - FIRSTPORTA[0..2]
specs[0].mask := $3;
specs[0].shiftL := 0;
specs[0].shiftR := 0;
specs[1].daqid := daqId(focusboard, FIRSTPORTB, DIGITALIN); // bit[3..9] - FIRSTPORTB[0..6]
specs[1].mask := $7f;
specs[1].shiftL := 0;
specs[0].shiftR := 3;
end else begin
specs[0].daqid := daqId(domeboard, FIRSTPORTB, DIGITALIN);
specs[0].mask := $3;
specs[0].shiftL := 0;
specs[0].shiftR := 0;
specs[1].daqid := daqId(domeboard, FIRSTPORTCL, DIGITALIN);
specs[1].mask := $7f;
specs[1].shiftL := 0;
specs[1].shiftR := 3;
end;
Self.Encoder := TWiseFocusEncoder.Create('FocusEncoder', specs);
Self.Timer := TTimer.Create(nil);
Self.Timer.Enabled := false;
Self.Timer.Interval := 1000;
Self.Timer.OnTimer := onTimer;
Self.lastValue := -1;
Self.Logger := TWiseLogger.Create('focus-proto');
Self.log('Started.');
end;
function TWiseFocus.GetValue: integer;
begin
result := Self.Encoder.Value;
end;
procedure TWiseFocus.SetValue(val: integer);
begin
// tbd
end;
procedure TWiseFocus.StartUp;
begin
Self.UpPin.SetOn;
Self.fState := FocusMovingUp;
end;
procedure TWiseFocus.StopUp;
begin
Self.Stop;
end;
procedure TWiseFocus.StartDown;
begin
Self.DownPin.SetOn;
Self.fState := FocusMovingDown;
end;
procedure TWiseFocus.StopDown;
begin
Self.Stop;
end;
procedure TWiseFocus.onTimer(Sender: TObject);
var
currValue: integer;
begin
if not ((Self.fState = FocusMovingUp) or (Self.fState = FocusMovingDown)) then
exit;
currValue := Self.Encoder.Value;
Self.log(Format('currValue: %d, lastValue: %d, delta: %d', [currValue, Self.lastValue, currValue - Self.lastValue]));
if Self.lastValue = -1 then begin
Self.lastValue := currValue;
exit;
end;
if currValue = Self.lastValue then begin
Inc(Self.sameValues);
if Self.sameValues = 3 then begin
Self.Stop;
Self.Timer.Enabled := false;
end;
end;
Self.lastValue := currValue;
Self.fSpeed := Abs(currValue - Self.lastValue);
if SecondsBetween(Now, Self.stopTime) >= 2 then
Self.log(Format('stop at %d, inertia: %d', [Self.stopVal, Abs(Self.Value - Self.stopVal)]));
end;
procedure TWiseFocus.FullUp;
begin
Self.StartUp;
Self.sameValues := 0;
Self.Timer.Enabled := true;
end;
procedure TWiseFocus.FullDown;
begin
Self.StartDown;
Self.sameValues := 0;
Self.Timer.Enabled := true;
end;
procedure TWiseFocus.Stop;
begin
Self.UpPin.SetOff;
Self.DownPin.SetOff;
Self.fState := FocusIdle;
Self.stopTime := Now;
Self.stopVal := Self.Value;
end;
procedure TWiseFocus.log(s: string);
begin
Self.Logger.log(s);
end;
destructor TWiseFocus.Destroy;
begin
Self.Stop;
inherited Destroy;
end;
function TWiseFocus.GetStateStr: string;
begin
case Self.fState of
FocusIdle: result := 'Idle';
FocusMovingUp: result := 'Up';
FocusMovingDown: result := 'Down';
end;
end;
function TWiseFocus.GetStatus: string;
begin
result := '';
end;
end.
|
PROGRAM CurvModl;
{$I FLOAT.INC}
{$DEFINE DEBUG}
uses MathLib0;
CONST
r_default = 0.10;
v_default = 0.20;
Periods = 20; { periods }
VAR
r, { one period rate }
v, { volatility in percent per period }
F,
SpotRate,
PsubN : Float;
n : WORD;
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
PROCEDURE GetParams;
VAR
err : INTEGER;
BEGIN
val(paramstr(1),v,err);
IF err > 0 THEN v := v_default;
val(paramstr(2),r,err);
IF err > 0 THEN r := r_default;
END;
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
FUNCTION ExpectedPrice ( Steps : WORD; { periods }
rate, { one period rate }
Vol : Float ) : Float;
CONST
p = 0.5; {probability of an "up" day. Hey, it's a random walk. }
VAR
j : WORD;
FutureYield,
Prob,
Price,
u,d,
Sum, SumY : Float;
BEGIN
{ expected up and down moves }
(*
{ Additive process (Coin Toss) }
u := Rate * Vol;
d := - (Rate * Vol);
*)
{ My multiplicative process }
u := 1 + Vol;
d := 1 - Vol;
(*
{ Goldman's Multiplicative process }
u := 1 + Vol;
d := 1 / (1 + Vol);
*)
(*
{ First Boston Multiplicative process }
u := exp(Vol);
d := exp(-Vol);
*)
Sum := 0.0; { initialize }
SumY := 0.0;
FOR j := 0 to Steps DO
BEGIN
{ possible outcome value }
{ multiplicative }
FutureYield := (rate * power(u,j) * power(d,Steps-j));
(*)
{ additive }
FutureYield := rate + j*u + (Steps-j)*d;
*)
{ probability of an outcome }
Prob := Binomial(Steps,j, p);
{$IFDEF DEBUG }
IF j = Steps-j THEN BEGIN
Write(' MidPoint ',FutureYield:6:4);
Write(' prob ',Prob*100:8:6,'%');
Writeln;
END;
{$ENDIF}
Price := Prob * 1/(1+FutureYield);
{ Price := Prob * FutureYield; }
{ Sumation}
Sum := Sum + Price;
SumY := SumY + FutureYield * Prob;;
END;
ExpectedPrice := Sum;
{ Write(SumY*100:5:2); }
{ ExpectedPrice := 1/(1+Sum); }
END; { FuturePrice }
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
BEGIN
GetParams;
F := 1 ; { intialize factorial };
writeln('Initial Rate:',R_default*100:6:2,'%');
writeln('Volatility:',v_default*100:6:2,'%');
writeln(
'Period','Exp. 1 Pd. Price, Rate':25,'Disc. Factor':15,'Disc. Rate':15);
FOR n := 1 TO Periods DO BEGIN
PsubN := ExpectedPrice(n-1,r,v);
F := F * PSubN;
SpotRate := power(1/F,1/n)-1;
Write(n:2);
Write(PsubN:15:4);
Write((1/PSubN-1)*100:8:2);
Write(F:20:4);
Write(SpotRate * 100:15:2);
Writeln;
END;
END. |
unit TestBufferInterpreter.SCSI;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, BufferInterpreter.SCSI, SysUtils,
BufferInterpreter;
type
// Test methods for class TSCSIBufferInterpreter
TestTSCSIBufferInterpreter = class(TTestCase)
strict private
FSCSIBufferInterpreter: TSCSIBufferInterpreter;
private
procedure CompareWithOriginalIdentify(
const ReturnValue: TIdentifyDeviceResult);
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestBufferToIdentifyDeviceResult;
procedure TestBufferToSMARTValueList;
procedure TestLargeBufferToIdentifyDeviceResult;
procedure TestLargeBufferToSMARTValueList;
end;
const
SM951IdentifyDevice: TSmallBuffer =
(0, 0, 6, 2, 55, 0, 0, 2, 78, 86, 77, 101, 32, 32, 32, 32, 83, 65, 77, 83
, 85, 78, 71, 32, 77, 90, 86, 76, 86, 49, 50, 56, 48, 48, 48, 81, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 192, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
);
implementation
procedure TestTSCSIBufferInterpreter.SetUp;
begin
FSCSIBufferInterpreter := TSCSIBufferInterpreter.Create;
end;
procedure TestTSCSIBufferInterpreter.TearDown;
begin
FSCSIBufferInterpreter.Free;
FSCSIBufferInterpreter := nil;
end;
procedure TestTSCSIBufferInterpreter.TestBufferToIdentifyDeviceResult;
var
ReturnValue: TIdentifyDeviceResult;
Buffer: TSmallBuffer;
begin
Buffer := SM951IdentifyDevice;
ReturnValue := FSCSIBufferInterpreter.BufferToIdentifyDeviceResult(Buffer);
CompareWithOriginalIdentify(ReturnValue);
end;
procedure TestTSCSIBufferInterpreter.CompareWithOriginalIdentify(
const ReturnValue: TIdentifyDeviceResult);
begin
CheckEquals('NVMe SAMSUNG MZVLV128', ReturnValue.Model);
CheckEquals('000Q', ReturnValue.Firmware);
CheckEquals('', ReturnValue.Serial);
CheckTrue(TSATASpeed.NotSATA = ReturnValue.SATASpeed,
'TSATASpeed.NotSATA = ReturnValue.SATASpeed');
CheckEquals(512, ReturnValue.LBASize);
end;
procedure TestTSCSIBufferInterpreter.TestBufferToSMARTValueList;
var
Buffer: TSmallBuffer;
begin
StartExpectingException(ENotSupportedException);
FSCSIBufferInterpreter.BufferToSMARTValueList(Buffer);
StopExpectingException;
end;
procedure TestTSCSIBufferInterpreter.TestLargeBufferToIdentifyDeviceResult;
var
ReturnValue: TIdentifyDeviceResult;
Buffer: TLargeBuffer;
begin
Move(SM951IdentifyDevice, Buffer, SizeOf(Buffer));
ReturnValue :=
FSCSIBufferInterpreter.LargeBufferToIdentifyDeviceResult(Buffer);
CompareWithOriginalIdentify(ReturnValue);
end;
procedure TestTSCSIBufferInterpreter.TestLargeBufferToSMARTValueList;
var
Buffer: TLargeBuffer;
begin
StartExpectingException(ENotSupportedException);
FSCSIBufferInterpreter.LargeBufferToSMARTValueList(Buffer);
StopExpectingException;
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTSCSIBufferInterpreter.Suite);
end.
|
unit IdAntiFreezeBase;
interface
uses
Classes,
IdBaseComponent,
IdException;
const
ID_Default_TIdAntiFreezeBase_Active = True;
ID_Default_TIdAntiFreezeBase_ApplicationHasPriority = True;
ID_Default_TIdAntiFreezeBase_IdleTimeOut = 250;
ID_Default_TIdAntiFreezeBase_OnlyWhenIdle = True;
type
TIdAntiFreezeBase = class(TIdBaseComponent)
protected
FActive: boolean;
FApplicationHasPriority: boolean;
FIdleTimeOut: Integer;
FOnlyWhenIdle: Boolean;
public
constructor Create(AOwner: TComponent); override;
class procedure DoProcess(const AIdle: boolean = true; const AOverride:
boolean = false);
destructor Destroy; override;
procedure Process; virtual; abstract;
published
property Active: boolean read FActive write FActive
default ID_Default_TIdAntiFreezeBase_Active;
property ApplicationHasPriority: Boolean read FApplicationHasPriority
write FApplicationHasPriority
default ID_Default_TIdAntiFreezeBase_ApplicationHasPriority;
property IdleTimeOut: integer read FIdleTimeOut write FIdleTimeOut
default ID_Default_TIdAntiFreezeBase_IdleTimeOut;
property OnlyWhenIdle: Boolean read FOnlyWhenIdle write FOnlyWhenIdle
default ID_Default_TIdAntiFreezeBase_OnlyWhenIdle;
end;
EIdMoreThanOneTIdAntiFreeze = class(EIdException);
var
GAntiFreeze: TIdAntiFreezeBase = nil;
implementation
uses
IdGlobal,
IdResourceStrings,
SysUtils;
{ TIdAntiFreezeBase }
constructor TIdAntiFreezeBase.Create(AOwner: TComponent);
begin
inherited;
if csDesigning in ComponentState then
begin
if Assigned(GAntiFreeze) then
begin
raise EIdMoreThanOneTIdAntiFreeze.Create(RSOnlyOneAntiFreeze);
end;
end
else
begin
GAntiFreeze := Self;
end;
FActive := ID_Default_TIdAntiFreezeBase_Active;
FApplicationHasPriority :=
ID_Default_TIdAntiFreezeBase_ApplicationHasPriority;
IdleTimeOut := ID_Default_TIdAntiFreezeBase_IdleTimeOut;
FOnlyWhenIdle := ID_Default_TIdAntiFreezeBase_OnlyWhenIdle;
end;
destructor TIdAntiFreezeBase.Destroy;
begin
GAntiFreeze := nil;
inherited;
end;
class procedure TIdAntiFreezeBase.DoProcess(const AIdle: boolean = true;
const AOverride: boolean = false);
begin
if (GAntiFreeze <> nil) and InMainThread then
begin
if ((GAntiFreeze.OnlyWhenIdle = false) or AIdle or AOverride) and
GAntiFreeze.Active then
begin
GAntiFreeze.Process;
end;
end;
end;
end.
|
{**********************************************************}
{ }
{ Zip Compression Algorithm for TinyDB }
{ }
{**********************************************************}
unit Compress_Zip;
{$I TinyDB.INC}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls,
Forms, Dialogs, TinyDB, ZlibUnit;
type
TCompAlgo_Zip = class(TCompressAlgo)
private
FLevel: TCompressLevel;
FBlockSize: Integer;
function ConvertCompLevel(Value: TCompressLevel): TCompressionLevel;
procedure SetBlockSize(Value: Integer);
function CompressBlock( DestBlock: PChar; var DestSize: Integer; SrcBlock: PChar; SrcSize: Integer ): Boolean;
function UncompressBlock( DestBlock: PChar; var DestSize: Integer; SrcBlock: PChar; SrcSize: Integer): Boolean;
procedure InternalDoEncodeProgress(Size, Pos: Integer);
procedure InternalDoDecodeProgress(Size, Pos: Integer);
protected
procedure SetLevel(Value: TCompressLevel); override;
function GetLevel: TCompressLevel; override;
property BlockSize: Integer read FBlockSize write SetBlockSize;
public
constructor Create(AOwner: TObject); override;
destructor Destroy; override;
procedure EncodeStream(Source, Dest: TMemoryStream; DataSize: Integer); override;
procedure DecodeStream(Source, Dest: TMemoryStream; DataSize: Integer); override;
end;
implementation
function Min( a, b : Integer ) : Integer;
begin
if a < b then
Result := a
else
Result := b;
end;
function EncodeBlockSize( IsCompressed : Boolean; BlockSize : Integer ) : Integer;
begin
// Format:
// Bit 31 = 1 ? Compressed : Uncompressed
// Bits 30..0 = Block size
Result := BlockSize;
if not IsCompressed then
Result := - Result;
end;
procedure DecodeBlockSize( Size : Integer; var IsCompressed : Boolean; var BlockSize : Integer);
begin
// Format:
// Bit 31 = 1 ? Compressed : Uncompressed
// Bits 30..0 = Block size
IsCompressed := Size >= 0;
Size := Abs(Size);
BlockSize := Size;
end;
function ReadInteger( S : TStream ) : Integer;
begin
S.ReadBuffer( Result, Sizeof(Result) );
end;
procedure WriteInteger( S : TStream; Val : Integer );
begin
S.WriteBuffer( Val, Sizeof(Val) );
end;
constructor TCompAlgo_Zip.Create(AOwner: TObject);
begin
inherited;
FLevel := clNormal;
FBlockSize := 65536;
end;
destructor TCompAlgo_Zip.Destroy;
begin
inherited Destroy;
end;
function TCompAlgo_Zip.ConvertCompLevel(Value: TCompressLevel): TCompressionLevel;
begin
case Value of
clMaximum: Result := clMax;
clNormal: Result := clDefault;
clFast, clSuperFast: Result := clFastest;
else
Result := clNone;
end;
end;
procedure TCompAlgo_Zip.SetBlockSize(Value: Integer);
begin
if (Value < 100) then Value := 100;
FBlockSize := Value;
end;
function TCompAlgo_Zip.CompressBlock( DestBlock : PChar; var DestSize : Integer; SrcBlock : PChar; SrcSize : Integer ) : Boolean;
var
DestPtr: Pointer;
begin
Result := True;
try
CompressBuf(SrcBlock, SrcSize, DestPtr, DestSize, ConvertCompLevel(FLevel));
Move(DestPtr^, DestBlock^, DestSize);
FreeMem(DestPtr);
except
Result := False;
end;
end;
function TCompAlgo_Zip.UncompressBlock( DestBlock : PChar; var DestSize : Integer; SrcBlock : PChar; SrcSize : Integer) : Boolean;
var
DestPtr: Pointer;
begin
Result := True;
try
DecompressBuf(SrcBlock, SrcSize, 0, DestPtr, DestSize);
Move(DestPtr^, DestBlock^, DestSize);
FreeMem(DestPtr);
except
Result := False;
end;
end;
procedure TCompAlgo_Zip.InternalDoEncodeProgress(Size, Pos: Integer);
begin
if Size = 0 then
DoEncodeProgress(0)
else
DoEncodeProgress(Round(Pos / Size * 100));
end;
procedure TCompAlgo_Zip.InternalDoDecodeProgress(Size, Pos: Integer);
begin
if Size = 0 then
DoDecodeProgress(0)
else
DoDecodeProgress(Round(Pos / Size * 100));
end;
function TCompAlgo_Zip.GetLevel: TCompressLevel;
begin
Result := FLevel;
end;
procedure TCompAlgo_Zip.SetLevel(Value: TCompressLevel);
begin
FLevel := Value;
end;
procedure TCompAlgo_Zip.EncodeStream(Source, Dest: TMemoryStream; DataSize: Integer);
var
SrcBlock, DstBlock: PChar;
BytesProcessed, ToRead, CompressBlockSize: Integer;
IsCompressed : Boolean;
DestStream: TMemoryStream;
begin
Source.Position := 0;
Dest.Position := 0;
if Source = Dest then
DestStream := TMemoryStream.Create
else begin
Dest.Clear;
DestStream := Dest;
end;
GetMem(SrcBlock, FBlockSize);
GetMem(DstBlock, FBlockSize);
try
BytesProcessed := 0;
while BytesProcessed < DataSize do
begin
InternalDoEncodeProgress(DataSize, BytesProcessed);
ToRead := Min(FBlockSize, DataSize - BytesProcessed);
Source.Read(SrcBlock^, ToRead);
CompressBlockSize := FBlockSize;
if not CompressBlock(DstBlock, CompressBlockSize, SrcBlock, ToRead) then
raise Exception.Create( 'Cannot Compress.' );
if CompressBlockSize >= ToRead then
begin
// Compression was not interressant, so use uncompressed block
IsCompressed := False;
CompressBlockSize := ToRead;
Move(SrcBlock^, DstBlock^, CompressBlockSize);
end
else
IsCompressed := True;
WriteInteger(DestStream, EncodeBlockSize(IsCompressed, CompressBlockSize));
DestStream.Write(DstBlock^, CompressBlockSize);
Inc(BytesProcessed, ToRead);
end;
if Source = Dest then
begin
Dest.Clear;
Dest.CopyFrom(DestStream, 0);
end;
InternalDoEncodeProgress(DataSize, BytesProcessed);
finally
if Source = Dest then DestStream.Free;
FreeMem(DstBlock);
FreeMem(SrcBlock);
InternalDoEncodeProgress(0, 0);
end;
end;
procedure TCompAlgo_Zip.DecodeStream(Source, Dest: TMemoryStream; DataSize: Integer);
var
SrcBlock, DstBlock: PChar;
BytesProcessed, ToRead: Integer;
BlockSize, UncompressBlockSize: Integer;
IsCompressed: Boolean;
DestStream: TMemoryStream;
begin
Source.Position := 0;
Dest.Position := 0;
if Source = Dest then
DestStream := TMemoryStream.Create
else begin
Dest.Clear;
DestStream := Dest;
end;
GetMem(SrcBlock, FBlockSize);
GetMem(DstBlock, FBlockSize);
try
BytesProcessed := 0;
IsCompressed := True;
while BytesProcessed < DataSize do
begin
InternalDoDecodeProgress(DataSize, BytesProcessed);
ToRead := ReadInteger(Source);
DecodeBlockSize(ToRead, IsCompressed, BlockSize);
ToRead := BlockSize;
Source.Read(SrcBlock^, BlockSize);
if IsCompressed then
begin
UncompressBlockSize := FBlockSize;
if not UncompressBlock(DstBlock, UncompressBlockSize, SrcBlock, BlockSize) then
raise Exception.Create('Cannot Uncompress.');
end
else
begin // if it was not, then just copy it
UncompressBlockSize := BlockSize;
Move(SrcBlock^, DstBlock^, UncompressBlockSize);
end;
DestStream.Write(DstBlock^, UncompressBlockSize);
BytesProcessed := BytesProcessed + ToRead + Sizeof(Integer);
end;
if Source = Dest then
begin
Dest.Clear;
Dest.CopyFrom(DestStream, 0);
end;
InternalDoDecodeProgress(DataSize, BytesProcessed);
finally
if Source = Dest then DestStream.Free;
FreeMem(DstBlock);
FreeMem(SrcBlock);
InternalDoDecodeProgress(0, 0);
end;
end;
initialization
RegisterCompressClass(TCompAlgo_Zip, 'ZIP');
end.
|
PROGRAM Sieve (Input, Output);
(* Sieve of Eratosthenes for finding primes 2 <= N <= Max
P.D. Terry, Rhodes University, 2016 *)
CONST
Max = 32000 (* largest number allowed *);
TYPE
SIEVES = ARRAY [2 .. Max] OF BOOLEAN;
VAR
I, N, K, Primes, It, Iterations : INTEGER (* counters *);
Uncrossed : SIEVES (* the sieve *);
Display : BOOLEAN;
BEGIN
Write('How many iterations '); Read(Input, Iterations);
Display := Iterations = 1;
Write('Supply largest number to be tested '); Read(Input, N);
IF N > Max THEN BEGIN
WriteLn(Output, 'N too large, sorry'); HALT
END;
WriteLn(Output, 'Prime numbers between 2 and ', N);
WriteLn(Output, '------------------------------------');
FOR It := 1 To Iterations DO BEGIN
Primes := 0 (* no primes yet found *);
FOR I := 2 TO N DO (* clear sieve *)
Uncrossed[I] := TRUE;
FOR I := 2 TO N DO (* the passes over the sieve *)
IF Uncrossed[I] THEN BEGIN
IF Display AND (Primes MOD 8 = 0) THEN WriteLn; (* ensure line not too long *)
Primes := Primes + 1;
IF Display THEN Write(Output, I:6);
K := I; (* now cross out multiples of I *)
REPEAT
(* New Code *)
IF (K > (Max-I)) THEN
BREAK;
(* End *)
Uncrossed[K] := FALSE; K := K + I
UNTIL (K > N) (* with large numbers of N, K would overflow *)
END;
IF Display THEN WriteLn
END;
Write(Primes, ' primes')
END.
|
unit gfx_tga;
{***********************************************************************
Unit gfx_tga.PAS v1.2 0801
(c) by Andreas Moser, amoser@amoser.de,
Delphi version : Delphi 4
gfx_tga is part of the gfx_library collection
You may use this sourcecode for your freewareproducts.
You may modify this source-code for your own use.
You may recompile this source-code for your own use.
All functions, procedures and classes may NOT be used in commercial
products without the permission of the author. For parts of this library
not written by me, you have to ask for permission by their
respective authors.
Disclaimer of warranty: "This software is supplied as is. The author
disclaims all warranties, expressed or implied, including, without
limitation, the warranties of merchantability and of fitness for any
purpose. The author assumes no liability for damages, direct or
consequential, which may result from the use of this software."
All brand and product names are marks or registered marks of their
respective companies.
Please report bugs to:
Andreas Moser amoser@amoser.de
********************************************************************************}
interface
uses SysUtils,
classes,
Windows,
JPEG,
Graphics,
io_files,
gfx_basedef,
gfx_errors,
gfx_colors;
// -----------------------------------------------------------------------------
//
// TGA classes
//
// -----------------------------------------------------------------------------
Type
TTGAHeader=Packed Record
tgaIdentSize:Byte;
tgaColorMapType:Byte;
tgaImageType:Byte;
tgaColorMapStart:Word;
tgaColorMapLength:Word;
tgaColorMapBits:Byte;
tgaXStart:Word;
tgaYStart:Word;
tgaWidth:Word;
tgaHeight:Word;
tgaBits:Byte;
tgaDescriptor:Byte;
End;
type TTGATriple = record
b,g,r: byte;
end;
TTGASaveColorMode=(tga1Bit,tga8bit,tga24bit);
type
TTGABitmap = class(TBitmap)
public
procedure LoadFromStream(Stream: TStream); override;
end;
Type
TTGAFile = class(TObject)
FTGAHeader :TTGAHeader;
FBitmap :TBitmap;
FTGASaveColorMode :TTGASaveColorMode;
scan_line:Array [0..65535] of Byte;
private
Procedure ReadTGALine(Stream:TStream);
procedure FillTGAHeader;
procedure ReadTGAHeader(Stream:TStream);
procedure ReadTGABody(Stream:TStream);
procedure WriteTGAHeader(Stream:TStream);
procedure WriteTGABody(Stream:TStream);
public
constructor Create;
destructor Destroy;override;
procedure LoadFromFile(filename: String);
procedure LoadFromStream(Stream: TStream);
procedure SaveToFile(filename: String);
procedure SaveToStream(Stream: TStream);
procedure LoadBitmap(filename:String);
procedure AssignBitmap(ABitmap:TBitmap);
property Bitmap:TBitmap read FBitmap;
property SaveMode:TTGASaveColorMode read FTGASaveColorMode write FTGASaveColorMode;
end;
// -----------------------------------------------------------------------------
//
// const
//
// -----------------------------------------------------------------------------
const MyTGADescriptor:String[50]='TARGA-File written by MosLibrary for Delphi'+Chr($1A);
implementation
//***********************************************************
//
// TTGAFile
//
//***********************************************************
// -----------------------------------------------------------------------------
//
// Create
//
// -----------------------------------------------------------------------------
constructor TTGAFile.Create;
begin
FBitmap:=TBitmap.Create;
end;
// -----------------------------------------------------------------------------
//
// Destroy
//
// -----------------------------------------------------------------------------
destructor TTGAFile.Destroy;
begin
FBitmap.Free;
inherited;
end;
// -----------------------------------------------------------------------------
//
// LoadFromFile
//
// -----------------------------------------------------------------------------
procedure TTGAFile.LoadFromFile(FileName: String);
var
Stream: TMemoryStream;
begin
Stream := TMemoryStream.Create;
try
Stream.LoadFromFile(Filename);
LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
// -----------------------------------------------------------------------------
//
// LoadFromStream
//
// -----------------------------------------------------------------------------
procedure TTGAFile.LoadFromStream(Stream: TStream);
begin
Stream.Position := 0;
ReadTGAHeader(Stream);
ReadTGABody(Stream);
end;
// -----------------------------------------------------------------------------
//
// SaveToFile
//
// -----------------------------------------------------------------------------
procedure TTGAFile.SaveToFile(FileName: String);
var
Stream: TMemoryStream;
begin
Stream := TMemoryStream.Create;
SaveToStream(Stream);
Stream.SaveToFile(filename);
Stream.Free;
end;
// -----------------------------------------------------------------------------
//
// SaveToStream
//
// -----------------------------------------------------------------------------
procedure TTGAFile.SaveToStream(Stream: TStream);
begin
Stream.Position := 0;
WriteTGAHeader(Stream);
WriteTGABody(Stream);
end;
// -----------------------------------------------------------------------------
//
// ReadTGAHeader
//
// -----------------------------------------------------------------------------
procedure TTGAFile.ReadTGAHeader(Stream:TStream);
var i:Integer;
b:Byte;
w:Word;
FMaxLogPalette :TMaxLogPalette;
Buffer:Array[1..4096] Of Char;
begin
Stream.Position:=0;
Stream.Read(FTGAHeader,sizeof(FTGAHeader));
Stream.Read(Buffer,FTGAHeader.tgaIdentSize);
If not(FTGAHeader.tgaImageType In [1,2,4,9,10,11]) or
not(FTGAHeader.tgaBits In [1,4,8,16,24,32]) then
begin
if GFXRaiseErrors then raise EGraphicFormat.Create('Not supported or invalid TGA-File');
GFXFileErrorList.Add('Not supported or invalid TGA-File');
end else
begin
FBitmap.Width:=FTGAHeader.tgaWidth;
FBitmap.Height:=FTGAHeader.tgaHeight;
case FTGAHeader.tgaBits of
1:begin
FBitmap.PixelFormat:=pf1Bit;
FTGASaveColorMode:=tga1bit;
end;
8: begin
FBitmap.PixelFormat:=pf8Bit;
FTGASaveColorMode:=tga8bit;
end;
16,24,32:begin
FBitmap.PixelFormat:=pf24Bit;
FTGASaveColorMode:=tga24bit;
end;
end;
if FTGAHeader.tgaColorMapType<>0 then
begin
FMaxLogPalette.palVersion:=$300;
FMaxLogPalette.palNumEntries:=256;
for i:=FTGAHeader.tgaColorMapStart to FTGAHeader.tgaColorMapStart+FTGAHeader.tgaColorMapLength-1 Do
begin
case FTGAHeader.tgaColorMapBits of
24:begin
Stream.Read(b,1);
FMaxLogPalette.palPalEntry[i].peBlue:=b;
Stream.Read(b,1);
FMaxLogPalette.palPalEntry[i].peGreen:=b;
Stream.Read(b,1);
FMaxLogPalette.palPalEntry[i].peRed:=b;
FMaxLogPalette.palPalEntry[i].peFlags:=0;
end;
16:begin
Stream.Read(w,2);
FMaxLogPalette.palPalEntry[i].peRed:=(((w shr 10) and $1F) shl 1)*4;
FMaxLogPalette.palPalEntry[i].peGreen:=(((w shr 5) and $1F) shl 1)*4;
FMaxLogPalette.palPalEntry[i].peBlue:=((w and $1F) shl 1)*4;
FMaxLogPalette.palPalEntry[i].peFlags:=0;
end;
end;
end;
FBitmap.Palette:=CreatePalette(pLogPalette(@FMaxLogpalette)^);
FBitMap.IgnorePalette:=False;
end;
If ((FTGAHeader.tgaBits=8) and (FTGAHeader.tgaColorMapType=0)) then MakeGreyPalette(FMaxLogPalette)
else if FTGAHeader.tgaBits = 1 then
begin
FMaxLogPalette.palVersion:=$300;
FMaxLogPalette.palNumEntries:=2;
FMaxLogPalette.palPalEntry[0].peRed:=0;
FMaxLogPalette.palPalEntry[0].peGreen:=0;
FMaxLogPalette.palPalEntry[0].peBlue:=0;
FMaxLogPalette.palPalEntry[0].peFlags:=0;
FMaxLogPalette.palPalEntry[1].peRed:=63;
FMaxLogPalette.palPalEntry[1].peGreen:=63;
FMaxLogPalette.palPalEntry[1].peBlue:=63;
FMaxLogPalette.palPalEntry[1].peFlags:=0;
FBitmap.Palette:=CreatePalette(pLogPalette(@FMaxLogPalette)^);
FBitMap.IgnorePalette:=False;
end;
end;
end;
// -----------------------------------------------------------------------------
//
// ReadTGALine
//
// -----------------------------------------------------------------------------
Procedure TTGAFile.ReadTGALine(Stream:TStream);
var w:word;
i,n:Integer;
offset:Integer;
tgatriple:TTGATriple;
b:Byte;
repeater:Byte;
Begin
FillChar(scan_line,FTGAHeader.tgaWidth*3,0);
If FTGAHeader.tgaImageType In [1,2,3] Then
Begin //uncompressed
Case FTGAHeader.tgaBits Of
1:Stream.Read(scan_line, (FTGAHeader.tgaWidth+7) Div 8);
8:Stream.Read(scan_line, FTGAHeader.tgaWidth);
16:begin
offset:=0;
for i:=0 to FTGAHeader.tgaWidth-1 do
begin
Stream.Read(w,2);
scan_line[offset]:=(w and $1F) shl 3; //Blue
scan_line[offset+1]:=((w shr 5) and $1F) shl 3; //Green
scan_line[offset+2]:=((w shr 10) and $1F) shl 3;//Red
Inc(offset,3);
end;
end;
24:begin
Stream.Read(scan_line,(FTGAHeader.tgaWidth*3));
end;
32:begin
offset:=0;
for i:=0 to FTGAHeader.tgaWidth-1 do
begin
Stream.Read(b,1);
scan_line[offset]:=b;
Stream.Read(b,1);
scan_line[offset+1]:=b;
Stream.Read(b,1);
scan_line[offset+1]:=b;
Inc(offset,3);
Stream.Position:=Stream.Position+1;
end;
end;
end; //end case
end else //Compressed
if FTGAHeader.tgaImageType In [9,10,11] then
begin
n:=0;
offset:=0;
repeat
Stream.Read(b,1);
repeater:=(b And $7F)+1;
Inc(n,repeater);
if b and $80 <>0 then //compressed bytes
begin
case FTGAHeader.tgaBits of
1,8:begin
Stream.Read(b,1);
FillChar(scan_line[offset],repeater,b);
Inc(Offset,repeater);
end;
16,24,32:begin
if (FTGAHeader.tgaBits=32) or (FTGAHeader.tgaBits=24) then
begin
Stream.Read(tgatriple,3)
end
else if (FTGAHeader.tgaBits=16) then
begin
Stream.Read(w,2);
tgatriple.r:=((w shr 10) and $1F) shl 3;
tgatriple.g:=((w shr 5) and $1F) shl 3;
tgatriple.b:=((w shr 0) and $1F) shl 3;
end;
for i:=0 to repeater-1 do
begin
scan_line[offset]:=tgatriple.b;
scan_line[offset+1]:=tgatriple.g;
scan_line[offset+2]:=tgatriple.r;
Inc(Offset,3);
end;
if (FTGAHeader.tgaBits=32) then Stream.Read(b,1);
end;
end;
end else
begin //uncompressed byte
Case FTGAHeader.tgaBits Of
1,8:begin
Stream.Read(scan_line[offset], repeater);
Inc(Offset,repeater);
end;
16:begin
for i:=0 to repeater -1 do
begin
Stream.Read(w,2);
scan_line[offset]:=(w and $1F) shl 3; //Blue
scan_line[offset+1]:=((w shr 5) and $1F) shl 3; //Green
scan_line[offset+2]:=((w shr 10) and $1F) shl 3;//Red
Inc(Offset,3);
end;
end;
24:begin
Stream.Read(scan_line[offset],repeater*3);
Inc(Offset,repeater*3);
end;
32:begin
Stream.Read(scan_line[offset],repeater*3);
Inc(Offset,repeater*3);
Stream.Position:=Stream.Position+1;
end;
end;
end;
until n>=FTGAHeader.tgaWidth;
end; //end compressed
end;
// -----------------------------------------------------------------------------
//
// ReadTGABody
//
// -----------------------------------------------------------------------------
procedure TTGAFile.ReadTGABody(Stream:TStream);
var i,j,v,w,x:Integer;
y:pRGBArray;
y2:pByteArray;
aStream:TMemoryStream;
Position,Increment:Integer;
b1,b2,b3:Byte;
begin
y:=nil;
y2:=nil;
i:=Stream.Position;
aStream:=TMemoryStream.Create;
Stream.Position:=0;
aStream.LoadFromStream(Stream);
aStream.Position:=i;
if FTGAHeader.tgaImageType In [1,2,3,9,10,11] Then
begin
//check if picture is stored reverse (Horizontal)
if FTGAHeader.tgaDescriptor and $20 =0
then begin
Position:=FBitmap.Height-1;
Increment:=-1;
end else
begin
Position:=0;
Increment:=1;
end;
i:=0;
while i< FBitmap.Height do
begin
case FBitmap.Pixelformat of
pf24Bit:y:=FBitmap.ScanLine[Position];
pf8Bit: y2:=FBitmap.ScanLine[Position];
end;
Position:=Position+Increment;
ReadTGALine(aStream);
//check if picture is stored reverse (Vertical)
if FTGAHeader.tgaDescriptor and $10 <>0 then
begin
case FBitmap.PixelFormat of
pf8Bit:begin
x:= FTGAHeader.tgaWidth;
v:= 0;
for w:=0 to (FTGAHeader.tgaWidth div 2) -1 do
begin
b1:=scan_line[x];
scan_line[x]:=scan_line[v];
scan_line[v]:=b1;
Inc(v);
Dec(x);
end;
end;
pf24Bit:Begin
x:= (FTGAHeader.tgaWidth*3)-3;
v:= 0;
for w:=0 to (FTGAHeader.tgaWidth div 2) -1 do
begin
b1:=scan_line[x];
b2:=scan_line[x+1];
b3:=scan_line[x+2];
scan_line[x]:=scan_line[v];
scan_line[x+1]:=scan_line[v+1];
scan_line[x+2]:=scan_line[v+2];
scan_line[v]:=b1;
scan_line[v+1]:=b2;
scan_line[v+2]:=b3;
v:=v+3;
x:=x-3;
end;
end;
end;
end;
case FBitmap.PixelFormat of
pf8Bit: Move(scan_line,y2^,FBitmap.Width-1);
pf24Bit:begin
x:=0;
for j:=0 to FBitmap.Width-1 do
begin
y[j].rgbtRed:=scan_line[x+2];
y[j].rgbtGreen:=scan_line[x+1];
y[j].rgbtBlue:=scan_line[x];
x:=x+3;
end;
end;
end;
inc(i);
end;
end;
aStream.Free;
End;
// -----------------------------------------------------------------------------
//
// WriteTGAHeader
//
// -----------------------------------------------------------------------------
procedure TTGAFile.WriteTGAHeader(Stream:TStream);
var fPalEntries:TPaletteEntries;
i:Integer;
begin
FillTGAHeader;
case Fbitmap.PixelFormat of
pf8bit: begin
FTGAHeader.tgaImageType:=1;
FTGAHeader.tgaColorMapType:=1;
FTGAHeader.tgaColorMapStart:=0;
FTGAHeader.tgaColorMapLength:=256;
FTGAHeader.tgaColorMapBits:=24;
FTGAHeader.tgaBits:=8;
end;
pf24bit:begin
FTGAHeader.tgaImageType:=2;
FTGAHeader.tgaColorMapType:=0;
FTGAHeader.tgaColorMapStart:=0;
FTGAHeader.tgaColorMapLength:=0;
FTGAHeader.tgaColorMapBits:=24;
FTGAHeader.tgaBits:=24;
end;
end;
Stream.Position:=0;
Stream.Write(FTGAHeader,sizeof(FTGAHeader));
Stream.Write(MyTGADescriptor[1],Length(MyTGADescriptor));
if FBitmap.PixelFormat=pf8Bit then
begin
GetPaletteEntries(FBitmap.Palette,0,256,fpalEntries);
for i:=0 to 255 do
begin
Stream.Write(fPalEntries[i].peBlue,1);
Stream.Write(fPalEntries[i].peGreen,1);
Stream.Write(fPalEntries[i].peRed,1);
end;
end;
end;
// -----------------------------------------------------------------------------
//
// WriteTGABody
//
// -----------------------------------------------------------------------------
procedure TTGAFile.WriteTGABody(Stream:TStream);
var i,j:Integer;
y:pRGBArray;
y2:pByteArray;
begin
y2:=nil;
y:=nil;
for i:= 0 to FBitmap.Height -1 do
begin
if FBitmap.PixelFormat=pf24Bit then y:=FBitmap.ScanLine[i] else
y2:=FBitmap.ScanLine[i];
for j:=0 to FBitmap.Width -1 do
begin
case FBitmap.PixelFormat of
pf8bit: begin
Stream.Write(y2[j],1);
end;
pf24bit:begin
Stream.Write(y[j].rgbtBlue,1);
Stream.Write(y[j].rgbtGreen,1);
Stream.Write(y[j].rgbtRed,1);
end;
end;
end;
end;
end;
// -----------------------------------------------------------------------------
//
// LoadBitmap
//
// -----------------------------------------------------------------------------
procedure TTGAFile.LoadBitmap(filename:String);
begin
try
FBitmap.LoadFromFile(filename);
case FBitmap.PixelFormat of
pf1Bit:FTGASaveColorMode:=tga1Bit;
pf8Bit:FTGASaveColorMode:=tga8Bit;
pf24Bit:FTGASaveColorMode:=tga24Bit;
end;
except
if GFXRaiseErrors then raise EGraphicFormat.Create('Invalid bitmapfile (TGA)');
GFXFileErrorList.Add('Invalid bitmapfile (TGA)');
end;
end;
procedure TTGAFile.AssignBitmap(ABitmap:TBitmap);
begin
FBitmap.Assign(ABitmap);
case FBitmap.PixelFormat of
pf1Bit:FTGASaveColorMode:=tga1Bit;
pf8Bit:FTGASaveColorMode:=tga8Bit;
pf24Bit:FTGASaveColorMode:=tga24Bit;
end;
end;
// -----------------------------------------------------------------------------
//
// FillTGAHeader
//
// -----------------------------------------------------------------------------
procedure TTGAFile.FillTGAHeader;
begin
with FTGAHeader do
begin
tgaIdentSize:=Length(MyTGADescriptor);
tgaXStart:=0;
tgaYStart:=0;
tgaWidth:=FBitmap.Width;
tgaHeight:=Fbitmap.Height;
tgaDescriptor:=$20;
end;
end;
// -----------------------------------------------------------------------------
//
// LoadFromStream
//
// -----------------------------------------------------------------------------
procedure TTGABitmap.LoadFromStream(Stream: TStream);
var
aTGA: TTGAFile;
aStream: TMemoryStream;
begin
aTGA := TTGAFile.Create;
try
aTGA.LoadFromStream(Stream);
aStream := TMemoryStream.Create;
try
aTGA.Bitmap.SaveToStream(aStream);
aStream.Position:=0;
inherited LoadFromStream(aStream);
finally
aStream.Free;
end;
finally
aTGA.Free;
end;
end;
initialization
TPicture.RegisterFileFormat('TGA','TGA-Format', TTGABitmap);
finalization
TPicture.UnRegisterGraphicClass(TTGABitmap);
end.
|
unit uDownloads.Model.Conexao.Firedac;
interface
uses
System.SysUtils, uDownloads.Model.Interfaces,
Data.DB, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.SQLite,
FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, FireDAC.VCLUI.Wait, FireDAC.Comp.Client;
type
EErroConexao = class(Exception)
public
constructor Create(AcMensagem: String); overload;
end;
TModelConexaoFiredac = class(TInterfacedObject, IConexao)
private
FoConexao: TFDConnection;
public
class function New: IConexao;
constructor Create;
function Connection: TCustomConnection;
destructor Destroy; override;
end;
implementation
const
_databasePath = 'C:\sqlite\teste.db';
_driverNameSQLITE = 'SQLITE';
class function TModelConexaoFiredac.New: IConexao;
begin
Result := Self.Create;
end;
constructor TModelConexaoFiredac.Create;
begin
try
FoConexao := TFDConnection.Create(nil);
FoConexao.DriverName := _driverNameSQLITE;
FoConexao.Params.DataBase := _databasePath;
FoConexao.Connected := True;
except
on E: Exception do
raise EErroConexao.Create(E.Message);
end;
end;
function TModelConexaoFiredac.Connection: TCustomConnection;
begin
Result := FoConexao;
end;
destructor TModelConexaoFiredac.Destroy;
begin
if System.Assigned(FoConexao) then
System.SysUtils.FreeAndNil(FoConexao);
inherited;
end;
{ EErroConexao }
constructor EErroConexao.Create(AcMensagem: String);
begin
Self.Message := 'Ocorreu o seguinte erro ao se conectar com o banco de dados: '
+ AcMensagem;
end;
end.
|
const
MAX = 1000000;
type
TCondition = record
l, r, op: integer;
end;
var
line: string;
fin, fout: text;
Conditions: array of TCondition;
Number: array [1..6] of integer;
i, j, count: integer;
function ToCond(l: string): TCondition;
var
operand: string;
begin
result.l := ord(l[1]) - ord('0');
result.r := ord(l[length(l)]) - ord('0');
operand := copy(l, 2, length(l) - 2);
case(operand) of
'=': result.op := 1;
'>': result.op := 2;
'<': result.op := 3;
'<>': result.op := 4;
'>=': result.op := 5;
'<=': result.op := 6;
end;
end;
function IsRight: boolean;
begin
case Conditions[j].op of
1: result := Number[Conditions[j].l] = Number[Conditions[j].r];
2: result := Number[Conditions[j].l] > Number[Conditions[j].r];
3: result := Number[Conditions[j].l] < Number[Conditions[j].r];
4: result := Number[Conditions[j].l] <> Number[Conditions[j].r];
5: result := Number[Conditions[j].l] >= Number[Conditions[j].r];
6: result := Number[Conditions[j].l] <= Number[Conditions[j].r];
end;
end;
procedure Increment;
var
k: integer;
begin
k := 6;
Number[k] += 1;
while(Number[k] = 10) do
begin
Number[k] := 0;
k -= 1;
Number[k] += 1;
end;
end;
begin
assign(fin, 'input.txt'); assign(fout, 'output.txt');
reset(fin);
rewrite(fout);
count := 0;
while(not EOF(fin)) do
begin
readln(fin, line);
setlength(Conditions, length(Conditions) + 1);
Conditions[high(Conditions)] := ToCond(line);
end;
for i := 0 to MAX - 1 do
begin
count += 1;
for j := 0 to high(Conditions) do
if not IsRight then
begin
count -= 1;
break;
end;
Increment;
end;
writeln(fout, count);
close(fin); close(fout);
end.
|
unit ProCierreMes;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Mask, RxToolEdit, RXSpin, StdCtrls, RXCtrls, StrMan, ESBDates;
type
TfraCierreMes = class(TFrame)
xlbNombre: TRxLabel;
mmoMsg: TMemo;
xlbDias: TRxLabel;
RxLabel1: TRxLabel;
cboAnio: TComboBox;
cboMes: TComboBox;
private
{ Private declarations }
procedure IniciarPeriodo;
public
{ Public declarations }
procedure SetUp;
procedure Ejecutar;
end;
implementation
uses Main, DM_MBA, Avance, MsgError;
{$R *.DFM}
procedure TfraCierreMes.SetUp;
var iAnio,iMes,iDia:Integer;
begin
xlbNombre.Caption := '** Cierre de Mes **';
mmoMsg.Lines.Clear;
mmoMsg.Lines.Add('Este proceso acumula las ventas, devoluciones y compras del mes.');
mmoMsg.Lines.Add('Este proceso se puede ejecutar varias veces durante el mes para ');
mmoMsg.Lines.Add('ir acumulando los totales parciales del mes en curso.');
oEmp.Retrieve;
cboAnio.SetFocus;
ESBDates.OptDecodeDateI(oEmp.FechaIniPeriodo,iAnio,iMes,iDia);
cboAnio.Text := sm.StrFloat(iAnio,'####');
cboMes.Text := sm.StrFloat(iMes,'##');
end;
procedure TfraCierreMes.Ejecutar;
var tAnio,tMes:String;
iAnio,iMes,iRes,iError:Integer;
begin
Screen.Cursor := crHourGlass;
frmAvance.Show;
frmAvance.Update;
frmAvance.Msg := 'Acumulando Facturas y Notas de Crédito ...';
DM1.Start;
oEmp.ProcesandoCierre := True;
DM1.Commit;
DM1.Start;
// Calculo de las ventas por documentos
DM1.ispPro.Unprepare;
DM1.ispPro.AutoDefineParams := True;
DM1.ispPro.StoredProcName := 'PRO_ACUMVENTAS01';
DM1.ispPro.Prepare;
tAnio := sm.Strip (cboAnio.Text);
tMes := sm.Strip (cboMes.Text);
iAnio := sm.ToI (tAnio);
iMes := sm.ToI (tMes);
DM1.ispPro.ParamByName('P_ANIO').AsSmallInt := iAnio;
DM1.ispPro.ParamByName('P_PERIODO').AsSmallInt := iMes;
DM1.ispPro.ExecProc;
{
// Calculo de las ventas por documentos
DM1.ispPro.Unprepare;
DM1.ispPro.AutoDefineParams := True;
DM1.ispPro.StoredProcName := 'PRO_CIERREMES';
DM1.ispPro.Prepare;
tAnio := sm.Strip (cboAnio.Text);
tMes := sm.Strip (cboMes.Text);
iAnio := sm.ToI (tAnio);
iMes := sm.ToI (tMes);
DM1.ispPro.ParamByName('p_Anio').AsSmallInt := iAnio;
DM1.ispPro.ParamByName('p_Periodo').AsSmallInt := iMes;
DM1.ispPro.ExecProc;
frmAvance.Percent := 30;
frmAvance.Msg := 'Calculando Estadistica por Producto y Familia ...';
if frmAvance.Canceled then begin
iError := 2; //Proceso Cancelado
end;
// Calculo de las ventas por producto
DM1.ispPro.Unprepare;
DM1.ispPro.AutoDefineParams := True;
DM1.ispPro.StoredProcName := 'PRO_CIERREMESPROD';
DM1.ispPro.Prepare;
tAnio := sm.Strip (cboAnio.Text);
tMes := sm.Strip (cboMes.Text);
iAnio := sm.ToI (tAnio);
iMes := sm.ToI (tMes);
DM1.ispPro.ParamByName('p_Anio').AsSmallInt := iAnio;
DM1.ispPro.ParamByName('p_Periodo').AsSmallInt := iMes;
DM1.ispPro.ExecProc;
// Cierre mensual de Inventarios
frmAvance.Percent := 50;
frmAvance.Msg := 'Haciendo el cierre mensual de Almacenes ...';
DM1.ispPro.Unprepare;
DM1.ispPro.AutoDefineParams := True;
DM1.ispPro.StoredProcName := 'MBA10017_U00';
DM1.ispPro.Prepare;
tAnio := sm.Strip (cboAnio.Text);
tMes := sm.Strip (cboMes.Text);
iAnio := sm.ToI (tAnio);
iMes := sm.ToI (tMes);
DM1.ispPro.ParamByName('Anio').AsSmallInt := iAnio;
DM1.ispPro.ParamByName('Periodo').AsSmallInt := iMes;
DM1.ispPro.ParamByName('FechaAct').AsDateTime := Date+Time;
DM1.ispPro.ParamByName('UserAct').AsString := oUser.LOGIN;
DM1.ispPro.ExecProc;
}
frmAvance.Percent := 100;
frmAvance.Msg := 'Terminado';
frmAvance.Finish (True);
frmAvance.Close;
DM1.Commit;
DM1.Start;
oEmp.ProcesandoCierre := False;
DM1.Commit;
iRes := 0;
if (Date > oEmp.FechaFinPeriodo) then begin
frmMsg.ClearAll;
frmMsg.Style := smTitle;
frmMsg.AddMsg('El proceso de Cierre Mensual ha terminado!!!');
frmMsg.AddMsg('');
frmMsg.Style := smDefault;
frmMsg.AddMsg('Al iniciar nuevo período, el sistema permitirá capturar documentos del nuevo mes que inicia.');
frmMsg.Question := '¿Deseas Iniciar el nuevo período?';
frmMsg.ShowAsk := True;
frmMsg.ShowCancel := True;
iRes := frmMsg.ShowModal;
if iRes = mrOk then IniciarPeriodo;
end else begin
frmMsg.ClearAll;
frmMsg.Style := smTitle;
frmMsg.AddMsg('El proceso de Acumulación ha terminado!!!');
frmMsg.AddMsg('');
frmMsg.Style := smDefault;
frmMsg.AddMsg('Como todavía no cambiamos de período, sólo se procesaron los acumulados.');
frmMsg.ShowAsk := False;
frmMsg.ShowCancel := False;
iRes := frmMsg.ShowModal;
Screen.Cursor := crDefault;
exit;
end;
Screen.Cursor := crDefault;
if iRes = mrOk then begin
frmMsg.ClearAll;
frmMsg.Style := smTitle;
frmMsg.AddMsg('El proceso de Cierre Mensual y el inicio del período ha terminado exitosamente!!!');
frmMsg.AddMsg('Inicio del nuevo período: ' + ESBDates.Date2Str(oEmp.FechaIniPeriodo));
frmMsg.AddMsg('');
frmMsg.Style := smDefault;
frmMsg.AddMsg('Ya se puede iniciar operaciones normales del MBA');
frmMsg.ShowAsk := False;
frmMsg.ShowCancel := False;
iRes := frmMsg.ShowModal;
end else begin
frmMsg.ClearAll;
frmMsg.Style := smUrgent;
frmMsg.AddMsg('Se hizo el cierre de Mes pero el inicio de periodo NO se realizó. El MBA continuará trabajando con el periodo anterior!');
frmMsg.AddMsg('');
frmMsg.Style := smDefault;
frmMsg.AddMsg('El período actual inició el: ' + ESBDates.Date2Str(oEmp.FechaIniPeriodo));
frmMsg.AddMsg('Posteriormente se podrá realizar de nuevo el cierre del mes y el inicio del período.');
frmMsg.AddMsg('');
frmMsg.Style := smDefault;
frmMsg.AddMsg('Ya se puede continuar con las operaciones normales del MBA');
frmMsg.ShowAsk := False;
frmMsg.ShowCancel := False;
iRes := frmMsg.ShowModal;
end;
end;
procedure TfraCierreMes.IniciarPeriodo;
var tAnio,tMes:String;
iAnio,iMes,iDia,iRes,iDias:Integer;
xFechaIni,xFechaFin:TDatetime;
begin
oEmp.FechaIniPeriodo := oEmp.FechaFinPeriodo + 1;
ESBDates.OptDecodeDateI(oEmp.FechaIniPeriodo,iAnio,iMes,iDia);
oEmp.PeriodoActual := iMes;
iDias := ESBDates.DaysInMonth(oEmp.FechaIniPeriodo);
oEmp.FechaFinPeriodo := ESBDates.OptEncodeDateI(iAnio,iMes,iDias);
oEmp.IniciarPeriodo;
// Calculando existencias para el nuevo periodo
{
// 10/Ene/2010
// EL nuevo calculo de existencia es Existencia Inicial Periodo +
// entradas Periodo - Salidas periodo
// Por eso cancelé este parte del cierre.
// LAs existencias iniciales SOLO se incializaran con el conteo fisico a actual
frmAvance.Show;
frmAvance.Update;
frmAvance.Percent := 70;
frmAvance.Msg := 'Inicializando existencias del periodo actual ...';
DM1.ispPro.Unprepare;
DM1.ispPro.AutoDefineParams := True;
DM1.ispPro.StoredProcName := 'MBA10016_U08';
DM1.ispPro.Prepare;
DM1.ispPro.ParamByName('FechaAct').AsDateTime := Date+Time;
DM1.ispPro.ParamByName('UserAct').AsString := oUser.LOGIN;
DM1.ispPro.ExecProc;
}
frmAvance.Percent := 100;
frmAvance.Msg := 'Terminado';
frmAvance.Finish (True);
frmAvance.Close;
end;
end.
|
unit BCEditor.Highlighter.Colors;
interface
uses
System.Classes, Vcl.Graphics, BCEditor.Highlighter.Info;
type
TBCEditorHighlighterElement = record
Background: TColor;
Foreground: TColor;
Name: string;
Style: TFontStyles;
end;
PBCEditorHighlighterElement = ^TBCEditorHighlighterElement;
TBCEditorHighlighterColors = class(TObject)
strict private
FFileName: string;
FInfo: TBCEditorHighlighterInfo;
FElements: TList;
FName: string;
public
constructor Create;
destructor Destroy; override;
function GetElement(Name: string): PBCEditorHighlighterElement;
procedure Clear;
property FileName: string read FFileName write FFileName;
property Info: TBCEditorHighlighterInfo read FInfo write FInfo;
property Name: string read FName write FName;
property Styles: TList read FElements write FElements;
end;
implementation
{ TBCEditorHighlighterColors }
constructor TBCEditorHighlighterColors.Create;
begin
inherited;
FElements := TList.Create;
FInfo := TBCEditorHighlighterInfo.Create;
end;
destructor TBCEditorHighlighterColors.Destroy;
begin
Clear;
FElements.Free;
FInfo.Free;
inherited;
end;
procedure TBCEditorHighlighterColors.Clear;
var
i: Integer;
begin
for i := FElements.Count - 1 downto 0 do
Dispose(PBCEditorHighlighterElement(FElements.Items[i]));
FElements.Clear;
end;
function TBCEditorHighlighterColors.GetElement(Name: string): PBCEditorHighlighterElement;
var
i: Integer;
begin
Result := nil;
for i := 0 to FElements.Count - 1 do
if PBCEditorHighlighterElement(FElements.Items[i])^.Name = Name then
begin
Result := FElements.Items[i];
Break;
end;
end;
end.
|
unit SFPLib;
{$MODE Delphi}
interface
uses
Math, LCLIntf, LCLType, LMessages, SysUtils;
type
SFPvalue = object
S,F,P: Extended;
end;
type
RGBvalue = object
R,G,B: Byte;
end;
type
RGBrange = object
rmax,rmin: Byte;
gmax,gmin: Byte;
bmax,bmin: Byte;
end;
type
SFPrange = object
smax,smin: Byte;
fmax,fmin: Byte;
pmax,pmin: Byte;
end;
function GetRGBValue(pixel: Cardinal): RGBvalue;
function IsRGBInRange(RGB: RGBvalue; Range: RGBrange): Boolean;
function RGB2SFP(r,g,b: Byte): SFPvalue;
implementation
function GetRGBValue(pixel: Cardinal): RGBvalue;
var
RGB: RGBvalue;
begin
RGB.R := GetRValue(pixel);
RGB.G := GetGValue(pixel);
RGB.B := GetBValue(pixel);
Result := RGB;
end;
function IsRGBInRange(RGB: RGBvalue; Range: RGBrange): Boolean;
begin
if (RGB.R >= Range.rmin) and (RGB.R <= Range.rmax) and
(RGB.G >= Range.gmin) and (RGB.G <= Range.gmax) and
(RGB.B >= Range.bmin) and (RGB.B <= Range.bmax) then
Result := TRUE
else
Result := FALSE;
end;
function RGB2SFP(r,g,b: Byte): SFPvalue;
var
SFP: SFPvalue;
rsin,rcos: Real;
begin
// the fun starts here :-)
rsin := (sin(2/3*PI)*g/255 + sin(4/3*PI)*b/255)*180/PI;
rcos := (r/255 + cos(2/3*PI)*g/255 + cos(4/3*PI)*b/255)*180/PI;
SFP.S := (SQRT(SQR(sin(120*PI/180)*g + sin(240*PI/180)*b) + SQR(r+cos(120*PI/180)*g+cos(240*PI/180)*b)));
SFP.F := (0.298*r + 0.594*g + 0.108*b);
// it just begun ;-)
if (r = g) and (g = b) then SFP.P := -1
else
begin
if (r + g + b) = 0 then SFP.P := 0 else
begin
if ((rsin > 0) and (rcos < 0)) or ((rsin < 0) and (rcos < 0)) then
SFP.P := 180*255/360 + (ArcTan(rsin/rcos)*(180/PI)*255/360)
else if (rsin < 0) and (rcos > 0) then
SFP.P := 255 + (ArcTan(rsin/rcos)*(180/PI)*255/360)
else if (rcos = 0) then
begin
if (rsin > 0) then SFP.P := 90/360*255/360
else if (rsin < 0) then SFP.P := 270/360*255/360
end
else
SFP.P := ArcTan(rsin/rcos)*(180/PI)*255/360;
end;
end;
// here it ends :-(
Result := SFP;
end;
end.
|
Program time;
Var
upo_hour, hour, min, sec: Integer;
Begin
Write ('Write the time in seconds : ');
Read(sec);
hour:= (sec div 3600);
upo_hour:= (sec mod 3600);
min:= (upo_hour div 60);
sec:= (sec mod 60);
Writeln (hour,'hr');
Writeln (min,'min');
Writeln (sec,'sec')
End. |
unit uStringEntwickler;
{$H+}
interface
uses
Classes, SysUtils, fgl, uGrammatik;
type TCardinalList = TFPGList<Cardinal>;
type TStringEntwickler = class
private
FGrammatik: TGrammatik;
{ Dieser Speichert den entwickelten String. Wenn es Parameter gibt, so enthaelt dieser
Platzhalter fuer die tatsaechlichen Zahlen die als Parameter reingegeben werden. }
FEntwickelterString: String;
{ Das ist der tatsaechlichen gezeichneter String. }
FZuZeichnenderString: String;
{ Dieser Wert MUSS ein vielfaches von 10 sein.
Dieser Wert (geteilt durch 100) bestimmt die Anzahl der Nachkommastellen, die
beim zufaelligen bestimmen des Strings beruecksichtigt werden. }
FMaximalerZufallsraum: Cardinal;
// getter-Funktionen fuer properties
{ Rueckgabe: Gibt zurueck, ob dieser Buchstabe ueberhaupt existiert und dem nach ersetzt
werden kann. Wenn false zurueckgegeben wurde, so kann dieser string ueberhaupt nicht
ersetze werden. Demnach steht auch kein sinvoller wert in der Variable ret.}
function gibEinzusetzendenString(c: String; var ret: String) : Boolean;
function gibAxiom : String;
function gibRegeln : TRegelDictionary;
{ Aufgabe: Die Zufaelligkeitsraeume werden als Cardinal gespeichert. Hierbei wird
der Fliesskommawert ab dem log_10(FMaximalerZufallsraum)-2 ten Wert verworfen. Wir nehmen
also nicht mehr bei der Zufaelligkeit ruecksicht darauf. }
function convertiereRealZuCardinal(wert: Real) : Cardinal;
{ Aufgabe: Zu zeichnender String wird auf den Stand von entwickelterString mit Einsetzung
von Werten gebracht. Dieser String besitzt wie Werte, mit welchen gezeichnet werden soll. }
procedure aktualisiereZuZeichnendenString;
public
constructor Create(gram: TGrammatik); overload;
constructor Create(gram: TGrammatik; entwickelterS: String); overload; // review!!
destructor Destroy; override;
property axiom: String read gibAxiom;
property regeln: TRegelDictionary read gibRegeln;
property entwickelterString: String read FEntwickelterString;
property zuZeichnenderString: String read FZuZeichnenderString;
{ Aufgabe: Hier wird eine Liste von Parametern reingegeben. Damit kann man die Zahlenwerte
der Parameter aendern. Wenn man im Axiom insgesamt anz_Ax Zahlenwerte aufgelistet hat, so MUSS
die Laenge der Liste auch anz_Ax sein. }
procedure aendereParameter(para: TStringList);
{ Aufgabe: Entwickelt den String gemaess der gegebenen Grammatik bis zur
rekursions Tiefe, die angegeben wurde.}
procedure entwickeln(rekursionsTiefe: Cardinal);
function copy : TStringEntwickler;
end;
implementation
constructor TStringEntwickler.Create(gram: TGrammatik);
begin
randomize;
FGrammatik := gram;
FEntwickelterString := '';
FZuZeichnenderString := '';
// es werden vier stellen nach dem Komma beruecksichtigt
FMaximalerZufallsraum := 100 * 10000;
end;
constructor TStringEntwickler.Create(gram: TGrammatik; entwickelterS: String);
begin
randomize;
FGrammatik := gram;
FEntwickelterString := entwickelterS;
aktualisiereZuZeichnendenString;
// es werden vier stellen nach dem Komma beruecksichtigt
FMaximalerZufallsraum := 100 * 10000;
end;
destructor TStringEntwickler.Destroy;
begin
FreeAndNil(FGrammatik);
FreeAndNil(FEntwickelterString);
FreeAndNil(FZuZeichnenderString);
FreeAndNil(FMaximalerZufallsraum);
end;
function TStringEntwickler.gibEinzusetzendenString(c: String; var ret: String) : Boolean;
var data: TRegelProduktionsseitenListe;
prefix: TCardinalList;
i: Cardinal;
zufaelligerWert: Cardinal;
function upper_bound(gesucht: Cardinal) : Cardinal;
var a, b, m: Cardinal;
begin
a := 0; b := prefix.Count-1;
while a <= b do
begin
m := (a+b) div 2;
if prefix[m] = gesucht then exit(m);
if prefix[m] < gesucht then a := m+1
else b := m-1;
end;
{ Wir koennen uns sicher sein, dass der Index von b gueltig ist,
da wir nur Werte suchen werden, die nicht groesser, als der groesste
Wert ist. }
result := b;
end;
begin
if FGrammatik.regeln.TryGetData(c,data) then
begin
prefix := TCardinalList.Create;
prefix.add(0);
for i := 1 to data.Count do
begin
prefix.add(prefix[i-1]+convertiereRealZuCardinal(data[i-1].zufaelligkeit));
end;
zufaelligerWert := random(FMaximalerZufallsraum)-1;
ret := data[upper_bound(zufaelligerWert)].produktion;
exit(true);
end;
result := false;
end;
function TStringEntwickler.gibAxiom : String;
begin
result := FGrammatik.axiom;
end;
function TStringEntwickler.gibRegeln : TRegelDictionary;
begin
result := FGrammatik.regeln;
end;
function TStringEntwickler.convertiereRealZuCardinal(wert: Real) : Cardinal;
begin
result := trunc(wert * (FMaximalerZufallsraum div 100));
end;
procedure TStringEntwickler.aktualisiereZuZeichnendenString;
var i: Cardinal; tmp_string: String;
begin
FZuZeichnenderString := '';
i := 1;
while (i <= length(entwickelterString)) do
begin
FZuZeichnenderString += entwickelterString[i];
if (i <> length(entwickelterString) - 1) and
(entwickelterString[i+1] = '(') then
begin
inc(i);
while (true) do
begin
if (entwickelterString[i] = ';') then
begin
FZuZeichnenderString += (FGrammatik.variableZuWert[tmp_string]) + ';';
tmp_string := ''; inc(i); continue;
end
else if (entwickelterString[i] = ')') then
begin
FZuZeichnenderString += (FGrammatik.variableZuWert[tmp_string]) + ')';
tmp_string := ''; break;
end
else if (entwickelterString[i] = '(') then
begin
FZuZeichnenderString += '('; tmp_string := ''; inc(i); continue;
end;
tmp_string += entwickelterString[i];
inc(i);
end;
end;
inc(i);
end;
end;
procedure TStringEntwickler.aendereParameter(para: TStringList);
begin
FGrammatik.aendereParameter(para);
aktualisiereZuZeichnendenString;
end;
procedure TStringEntwickler.entwickeln(rekursionsTiefe: Cardinal);
function toSmallLetter(letter: Char) : Char;
var letterAsc: Cardinal;
begin
letterAsc:=Ord(letter);
letterAsc:=letterAsc+32;
result:=Chr(letterAsc);
end;
procedure entw(tiefe: Cardinal; s: String);
var i,j: Cardinal;
data,tmp_string,links,letters: String;
paraList: TStringList;
rechteSeiteGefunden: Boolean;
smLetter: Char;
begin
i := 1;
while (i <= length(s)) do
begin
links := s[i]; paraList := TStringList.Create;
// parameter Liste richtig initialisieren (links = '<Buchstabe>(' wenn
// length(paraList) > 0)
if (i <> length(s) - 1) and (s[i+1] = '(') and (tiefe <> 0) then
begin
inc(i);
while (true) do
begin
if (s[i] = ';') then
begin
paraList.add(tmp_string); tmp_string := '';
inc(i); continue;
end
else if (s[i] = ')') then
begin
paraList.add(tmp_string); tmp_string := ''; break;
end
else if (s[i] = '(') then
begin
tmp_string := ''; links := links + '(';
inc(i); continue;
end;
tmp_string := tmp_string + s[i]; inc(i);
end;
// rekonstruktion der rechten Seite
smLetter := toSmallLetter(links[1]);
for j := 1 to paraList.Count do
begin
letters := IntToStr(j) + smLetter;
while length(letters) < TGrammatik.tokenLaenge do letters:='0'+letters;
links := links + letters;
if (j = paraList.Count) then links := links + ')'
else links := links + ';';
end;
end;
rechteSeiteGefunden := gibEinzusetzendenString(links,data);
if (tiefe <> 0) and (rechteSeiteGefunden) and (paraList.Count > 0) then
begin
// Ersetzung der Variablen
smLetter := toSmallLetter(links[1]);
for j := 0 to paraList.Count - 1 do
begin
letters := IntToStr(j+1) + smLetter;
while length(letters) < TGrammatik.tokenLaenge do letters:='0'+letters;
tmp_string:=paraList[j];
data := StringReplace(data,letters,paraList[j],[rfReplaceAll]);
end;
entw(tiefe-1,data);
end
else if (tiefe <> 0) and (rechteSeiteGefunden) and (paraList.Count = 0) then entw(tiefe-1,data)
else FEntwickelterString += s[i];
inc(i);
end;
FreeAndNil(paraList);
end;
begin
FEntwickelterString := '';
entw(rekursionsTiefe,FGrammatik.ersetztesAxiom);
aktualisiereZuZeichnendenString;
end;
function TStringEntwickler.copy : TStringEntwickler;
var tmp_string: String;
begin
tmp_string := system.Copy(
FEntwickelterString,
1,
length(FEntwickelterString)
);
result := TStringEntwickler.Create(
FGrammatik.copy,
tmp_string
);
end;
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
unit frmMain;
interface
uses
Windows, Messages, Classes, Graphics, Forms, ExtCtrls, Menus,
Controls, Dialogs, SysUtils,
OpenGL;
type
TfrmGL = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
hrc: HGLRC;
PText: pointer;
bmWidth, bmHeight:GLsizei;
procedure SetDCPixelFormat (hdc : HDC);
end;
var
frmGL: TfrmGL;
implementation
{$R *.DFM}
function ReadMonochrome(const FilePath:string;var bmWidth,bmHeight:
GLsizei): Pointer;
const
szh = SizeOf(TBitmapFileHeader);
szi = SizeOf(TBitmapInfoHeader);
var
BmpFile: file;
bfh: TBitmapFileHeader;
bmi: TBitmapInfoHeader;
siz,
size: integer;
begin
AssignFile(bmpfile,FilePath);
Reset(bmpfile,1);
size := FileSize(bmpfile) - szh - szi;
BlockRead(bmpfile,bfh,szh);
If Bfh.bfType<>$4D42 then
raise EInvalidGraphic.Create('Invalid Bitmap');
BlockRead(bmpfile,bmi,szi);
With bmi do begin
bmWidth := biWidth;
bmHeight := biHeight;
siz := biSizeImage;
end;
If size > siz then seek(bmpfile,szh+szi+size-siz);
GetMem(Result, siz);
BlockRead(bmpfile, Result^, siz);
CloseFile(bmpfile)
end;
{=======================================================================
Перерисовка окна}
procedure TfrmGL.FormPaint(Sender: TObject);
begin
wglMakeCurrent(Canvas.Handle, hrc);
glViewport (0, 0, ClientWidth, ClientHeight);
glClearColor (0.5, 0.5, 0.75, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
glBitmap(bmWidth, bmHeight, 0, 0, 0, 0, PText);
SwapBuffers (Canvas.Handle);
wglMakeCurrent(0, 0);
end;
{=======================================================================
Создание окна}
procedure TfrmGL.FormCreate(Sender: TObject);
begin
SetDCPixelFormat (Canvas.Handle);
hrc := wglCreateContext(Canvas.Handle);
glPixelStorei(GL_UNPACK_ALIGNMENT,1);
PText := ReadMonochrome('Text.bmp', bmWidth, bmHeight);
end;
{=======================================================================
Формат пикселя}
procedure TfrmGL.SetDCPixelFormat (hdc : HDC);
var
pfd : TPixelFormatDescriptor;
nPixelFormat : Integer;
begin
FillChar (pfd, SizeOf (pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat (hdc, @pfd);
SetPixelFormat (hdc, nPixelFormat, @pfd);
end;
{=======================================================================
Конец работы программы}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
wglDeleteContext(hrc);
FreeMem(PText);
end;
procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If Key = VK_ESCAPE then Close
end;
end.
|
unit u_complex;
interface
uses
SysUtils;
type
//Представление комплексного числа в виде: re — дейсвтительная часть, im — мнимая
TComplex=record
re, im:real;
end;
//иницилизация числа
function u_InitComplex(re1, im1:real):TComplex;
//Ввод компл. числа
procedure u_InputComplex(massage:string; var aRes:TComplex);
//Печать компл. числа
procedure u_PrintComplex(a: TComplex);
//Сумма двух компл. чисел
function u_SumComplex(a, b:TComplex):TComplex;
//Разность двух компл. чисел
function u_DiffComplex(a, b:TComplex):TComplex;
//Произведение двух компл. чичел
function u_MultComplex(a, b:TComplex):TComplex;
//Частное двух компл. чисел
function u_DivComplex(a, b:TComplex):TComplex;
//Корень из компл. числа
function u_RootComplex(a:TComplex):TComplex;
//Модуль компл. числа
function u_AbsolutComplex(a:TComplex):real;
implementation
//Инициализация числа
function u_InitComplex(re1, im1: real):TComplex;
begin
result.re:=re1;
result.im:=im1;
end;
//Ввод компл. числа
procedure u_InPutComplex(massage:string; var aRes:Tcomplex);
begin
writeln(massage);
writeln('Введите действительную часть');
readln(aRes.re);
writeln('Введите мнимую часть');
readln(aRes.im);
end;
//Печать компл. числа
procedure u_PrintComplex(a: TComplex);
begin
if a.im=-1 then
if a.re=0 then
writeln('-i') //-i
else
writeln(a.re:0:2,'-i') //a-i
else
if a.im=1 then
if a.re=0 then
writeln('i') //i
else
writeln(a.re:0:2,'+i') //a+i
else
if a.im=0 then
writeln(a.re:0:2) //a
else
if a.re=0 then
writeln(a.im:0:2,'i') //bi
else
if a.im<0 then
writeln(a.re:0:2,a.im:0:2,'i') //a-bi
else
writeln(a.re:0:2,'+',a.im:0:2,'i'); //a+bi
end;
//Сумма двух компл. чисел
function u_SumComplex(a, b:TComplex):TComplex;
begin
result.re:=a.re+b.re;
result.im:=a.im+b.im;
end;
//Разность двух компл. чисел
function u_DiffComplex(a, b:TComplex):TComplex;
begin
result.re:=a.re-b.re;
result.im:=a.im-b.im;
end;
//Произведение двух компл. чисел
function u_MultComplex(a, b:TComplex):TComplex;
begin
result.re:=a.re*b.re-a.im*b.im;
result.im:=a.im*b.re+a.re*b.im;
end;
//Частное двух компл. чисел
function u_DivComplex(a, b:TComplex):TComplex;
var zn: real;
begin
zn:=(b.re*b.re+b.im*b.im);
if zn = 0 then
raise exception.Create('Ошибка. Происходит деление на ноль');
result.re:=(a.re*b.re+a.im*b.im)/zn;
result.im:=(a.im*b.re-a.re*b.im)/zn;
end;
//Корень из компл. числа
function u_RootComplex(a:TComplex):TComplex;
var z: real;
begin
z:=sqrt(sqr(a.re)+sqr(a.im));
result.re:=sqrt((z+a.re)/2);
result.im:=sqrt((z-a.re)/2);
end;
//Модуль из комплексного числа
function u_AbsolutComplex(a:TComplex):real;
begin
result:=sqrt(sqr(a.re)+sqr(a.im));
end;
end.
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 16384,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
April '2000
Problem 80 O(NLgN) Greedy Method
}
program
MinimumMeanTime;
const
MaxN = 100;
var
N : Integer;
T, Map : array [1 .. MaxN] of Integer;
Mean : Extended;
I : Integer;
procedure ReadInput;
begin
Assign(Input, 'input.txt');
Reset(Input);
Readln(Input, N);
for I := 1 to N do
Readln(T[I]);
Close(Input);
end;
procedure WriteOutput;
begin
Assign(Output, 'output.txt');
Rewrite(Output);
Writeln(Mean : 0 : 1);
for I := 1 to N do
Write(Map[I], ' ');
Close(Output);
end;
procedure Sort(l, r: Integer);
var
i, j, x, y: integer;
begin
i := l; j := r; x := t[map[(l+r) DIV 2]];
repeat
while t[map[i]] < x do i := i + 1;
while x < t[map[j]] do j := j - 1;
if i <= j then
begin
y := map[i]; map[i] := map[j]; map[j] := y;
i := i + 1; j := j - 1;
end;
until i > j;
if l < j then Sort(l, j);
if i < r then Sort(i, r);
end;
procedure Greedy;
begin
for I := 1 to N do
Map[I] := I;
Sort(1, N);
for I := 1 to N do
Mean := Mean + (N + 1 - I) * T[Map[I]];
Mean := Mean / N;
end;
begin
ReadInput;
Greedy;
WriteOutput;
end.
|
unit TipoRelatorioDataUn;
interface
uses
SysUtils, Classes, FMTBcd, Provider, osSQLDataSetProvider, DB, SqlExpr, osUtils,
osCustomDataSetProvider, osSQLDataSet;
type
TTipoRelatorioData = class(TDataModule)
MasterDataSet: TosSQLDataset;
MasterProvider: TosSQLDataSetProvider;
MasterDataSetNOME: TStringField;
MasterDataSetDESCRICAO: TStringField;
MasterDataSetIDTIPORELATORIO: TIntegerField;
private
public
procedure Validate(PDataSet: TDataSet);
end;
var
TipoRelatorioData: TTipoRelatorioData;
implementation
uses osErrorHandler, SQLMainData;
{$R *.dfm}
procedure TTipoRelatorioData.Validate(PDataSet: TDataSet);
begin
with PDataSet, HError do
begin
Clear;
CheckEmpty(FieldByName('Nome'));
CheckEmpty(FieldByName('Descricao'));
Check;
end;
end;
initialization
OSRegisterClass(TTipoRelatorioData);
end.
|
{-----------------------------------------------------------------------------
Author: Roman Fadeyev
Purpose: Реализация IStockDataSource для файлов формата MetaTrader 4
History:
-----------------------------------------------------------------------------}
unit FC.StockData.MT.StockDataSource;
{$I Compiler.inc}
interface
uses SysUtils,Classes,DB,
StockChart.Definitions,
FC.Definitions,FC.StockData.StockDataSource, FC.StockData.StockDataConnectionFile,
MetaTrader.HistoryFileStruct;
type
TMTHeaderVersion = (mtV3,mtV4, mtV401);
TMTHeader = packed record
Copyright : AnsiString;
Symbol : AnsiString;
Period : integer;
Digits : integer;
TimeSign : TDateTime;
LastSync : TDateTime;
end;
TStockDataSource_MT = class(TStockDataSource_StreamToMemory)
private
FVersion : TMTHeaderVersion;
FHeader : TMTHeader;
procedure LoadHeader(aStream: TStream);
procedure LoadData(aStream: TStream;const aStartFrom, aTo: TDateTime);
public
constructor Create(const aConnection: IStockDataSourceConnection; const aSymbol: string; aInterval: TStockTimeInterval; aStream: TStream; const aStartFrom: TDateTime=0; const aTo: TDateTime=0); overload;
constructor Create(const aFileName: string;const aStartFrom: TDateTime=0; const aTo: TDateTime=0); overload;
property Version:TMTHeaderVersion read FVersion;
property Header : TMTHeader read FHeader;
end;
implementation
uses DateUtils,Math,FC.DataUtils;
constructor TStockDataSource_MT.Create(const aConnection: IStockDataSourceConnection; const aSymbol: string; aInterval: TStockTimeInterval; aStream: TStream; const aStartFrom: TDateTime=0; const aTo: TDateTime=0);
var
aSymbol_ : string;
begin
aSymbol_:=aSymbol;
LoadHeader(aStream);
if aSymbol_='' then //если при создании не указали, что за пара, берем из заголовка
aSymbol_:=FHeader.Symbol;
inherited Create(aConnection, aSymbol_,aInterval);
LoadData(aStream,aStartFrom, aTo);
end;
constructor TStockDataSource_MT.Create(const aFileName: string; const aStartFrom, aTo: TDateTime);
var
aStream: TFileStream;
aInterval : TStockTimeInterval;
begin
aStream:=TFileStreamEx.CreateForRead(aFileName);
try
LoadHeader(aStream);
if not TStockDataUtils.GetTimeIntervalByValue(FHeader.Period,aInterval) then
raise EStockError.Create('Unknown period');
inherited Create(nil,FHeader.Symbol,aInterval);
LoadData(aStream,aStartFrom, aTo);
finally
aStream.Free;
end;
end;
procedure TStockDataSource_MT.LoadData(aStream: TStream;const aStartFrom, aTo: TDateTime);
var
aRecord : TStockDataRecord;
i : integer;
aDateTime : TDateTime;
aDataOpen : TStockRealNumber;
aDataHigh : TStockRealNumber;
aDataLow : TStockRealNumber;
aDataClose : TStockRealNumber;
aDataVolume : integer;
aDataVolume4 : TStockRealNumber;
aMaxDate : TDateTime;
aNeedSort : boolean;
aDigits : integer;
aRecordSize : integer;
aReader : TReader;
aCount,j : integer;
aInt64: int64;
begin
//Дальше заголовок
aDigits:=FHeader.Digits;
aNeedSort:=false;
aMaxDate:=-1;
if FVersion=mtV401 then
aRecordSize:=60
else if FVersion=mtV4 then
aRecordSize:=sizeof(time_t)+sizeof(TStockRealNumber)*5
else
aRecordSize:=SizeOf(time_t)+sizeof(TStockRealNumber)*4+sizeof(integer);
aCount:=((aStream.Size-aStream.Position) div aRecordSize);
FRecordList.Capacity:=aCount+1;
aReader:=TReader.Create(aStream,100*1024);
try
//данные
for j := 0 to aCount-1 do
begin
if FVersion=mtV401 then
begin
{
.hst file format valid as of MT4 574 and later
the bars array (single-byte justification) . . . total 60 bytes
datetime ctm; // bar start time 8 bytes
double open; // open price 8 bytes
double high; // highest price 8 bytes
double low; // lowest price 8 bytes
double close; // close price 8 bytes
long volume; // tick count 8 bytes
int spread; // spread 4 bytes
long real_volume; // real volume 8 bytes
}
//Time
aReader.Read(aInt64,sizeof(aInt64));
aDateTime:=UnixToDateTime(aInt64);
//Open
aReader.Read(aDataOpen,sizeof(aDataOpen));
//High
aReader.Read(aDataHigh,sizeof(aDataHigh));
//Low
aReader.Read(aDataLow,sizeof(aDataLow));
//Close
aReader.Read(aDataClose,sizeof(aDataClose));
//volume
aReader.Read(aInt64,sizeof(aInt64));
aDataVolume:=aInt64;
//spread
aReader.Read(i,sizeof(i));
//real_volume
aReader.Read(aInt64,sizeof(aInt64));
end
else begin
aReader.Read(i,sizeof(i));
aDateTime:=UnixToDateTime(i);
//Open
aReader.Read(aDataOpen,sizeof(aDataOpen));
//Low
aReader.Read(aDataLow,sizeof(aDataLow));
//High
aReader.Read(aDataHigh,sizeof(aDataHigh));
//Close
aReader.Read(aDataClose,sizeof(aDataClose));
//Volume
if FVersion=mtV4 then
begin
aReader.Read(aDataVolume4,sizeof(aDataVolume4));
aDataVolume:=Trunc(aDataVolume4);
end
else begin
aReader.Read(aDataVolume,sizeof(aDataVolume));
end;
end;
if (aStartFrom>0) and (CompareDateTime(aDateTime,aStartFrom)<0) then
continue;
if (aTo>0) and (CompareDateTime(aDateTime,aTo)>0) then
continue;
if aDateTime<aMaxDate then
aNeedSort:=true
else
aMaxDate:=aDateTime;
aDataOpen:=RoundTo(aDataOpen,-aDigits);
aDataHigh:=RoundTo(aDataHigh,-aDigits);
aDataLow:=RoundTo(aDataLow,-aDigits);
aDataClose:=RoundTo(aDataClose,-aDigits);
Assert(aDataOpen>=aDataLow);
Assert(aDataClose>=aDataLow);
Assert(aDataOpen<=aDataHigh);
Assert(aDataClose<=aDataHigh);
aRecord:=TStockDataRecord.Create(aDateTime,aDataOpen, aDataHigh, aDataLow, aDataClose, aDataVolume);
FRecordList.Add(aRecord);
end;
finally
aReader.Free;
end;
if aNeedSort then
FRecordList.Sort(OnSortRecords);
end;
procedure TStockDataSource_MT.LoadHeader(aStream: TStream);
var
aVersion : integer;
aMT4Header : TMT4Header;
aMT3Header : TMT3Header;
begin
//4 байта - версия
aStream.ReadBuffer(aVersion,sizeof(aVersion));
//Дальше заголовок
if aVersion=401 then
begin
FVersion:=mtV401;
aStream.ReadBuffer(aMT4Header,sizeof(aMT4Header));
FHeader.Copyright:=aMT4Header.copyright;
FHeader.Symbol:=aMT4Header.symbol;
FHeader.Period:=aMT4Header.period;
FHeader.Digits:=aMT4Header.digits;
FHeader.TimeSign:=UnixToDateTime(aMT4Header.timesign);
FHeader.LastSync:=UnixToDateTime(aMT4Header.last_sync);
end
else if aVersion=400 then
begin
FVersion:=mtV4;
aStream.ReadBuffer(aMT4Header,sizeof(aMT4Header));
FHeader.Copyright:=aMT4Header.copyright;
FHeader.Symbol:=aMT4Header.symbol;
FHeader.Period:=aMT4Header.period;
FHeader.Digits:=aMT4Header.digits;
FHeader.TimeSign:=UnixToDateTime(aMT4Header.timesign);
FHeader.LastSync:=UnixToDateTime(aMT4Header.last_sync);
end
else if aVersion=100 then
begin
FVersion:=mtV3;
aStream.ReadBuffer(aMT3Header,sizeof(aMT3Header));
FHeader.Copyright:=aMT3Header.copyright;
FHeader.Symbol:=aMT3Header.copyright;
FHeader.Period:=aMT3Header.period;
FHeader.Digits:=4; //??
FHeader.TimeSign:=UnixToDateTime(aMT3Header.timesign);
FHeader.LastSync:=UnixToDateTime(aMT3Header.last_sync);
end
else
raise EStreamError.Create('Wrong version');
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.