text stringlengths 14 6.51M |
|---|
unit HelperLib;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Grids, Vcl.CategoryButtons;
type
TListBoxHelper = class helper for TListBox
public
procedure ShowFirst();
procedure ShowLast();
end;
TStringGridHelper = class helper for TStringGrid
public
procedure ShowFirst();
procedure ShowLast(datarows: Integer = -1);
end;
TCategoryButtonsHelper = class helper for TCategoryButtons
public
procedure LoadFromFile(filename: string; Encoding: TEncoding);
procedure SaveToFile(filename: string; Encoding: TEncoding);
procedure LoadFromText(TXT: TStringList);
procedure SaveToText(TXT: TStringList);
end;
implementation
{ TListBoxHelper }
procedure TListBoxHelper.ShowFirst();
begin
TopIndex := 0;
end;
procedure TListBoxHelper.ShowLast();
var
line_height: Integer;
lines: Integer;
begin
if Style = lbOwnerDrawFixed then begin
line_height := ItemHeight;
end
else begin
line_height := Abs(Font.Height) + 2;
end;
lines := Height div line_height;
if Items.Count < lines then begin
TopIndex := 0;
end
else begin
TopIndex := Items.Count - lines;
end;
end;
{ TStringGridHelper }
procedure TStringGridHelper.ShowFirst();
begin
TopRow := FixedRows;
end;
procedure TStringGridHelper.ShowLast(datarows: Integer);
begin
if datarows <= VisibleRowCount then begin
TopRow := FixedRows;
end
else begin
if datarows = -1 then begin
TopRow := RowCount - VisibleRowCount;
end
else begin
TopRow := (datarows + FixedRows) - VisibleRowCount;
end;
end;
end;
{ TCategoryButtonsHelper }
procedure TCategoryButtonsHelper.LoadFromFile(filename: string; Encoding: TEncoding);
var
L: TStringList;
begin
L := TStringList.Create();
try
L.LoadFromFile(filename, Encoding);
LoadFromText(L);
finally
L.Free();
end;
end;
procedure TCategoryButtonsHelper.SaveToFile(filename: string; Encoding: TEncoding);
var
L: TStringList;
begin
L := TStringList.Create();
try
SaveToText(L);
L.SaveToFile(filename, Encoding);
finally
L.Free();
end;
end;
procedure TCategoryButtonsHelper.LoadFromText(TXT: TStringList);
var
i: Integer;
strLine: string;
strText: string;
C: TButtonCategory;
B: TButtonItem;
begin
C := nil;
Categories.Clear();
for i := 0 to TXT.Count - 1 do begin
strLine := TXT[i];
if strLine[1] = Chr($09) then begin
if C = nil then begin
C := Categories.Add();
C.Caption := 'タイトル無し';
end;
strText := Trim(Copy(strLine, 2));
B := C.Items.Add();
B.Caption := strText;
B.Hint := strText;
end
else begin
C := Categories.Add();
C.Caption := strLine;
end;
end;
end;
procedure TCategoryButtonsHelper.SaveToText(TXT: TStringList);
var
i: Integer;
j: Integer;
C: TButtonCategory;
B: TButtonItem;
begin
for i := 0 to Categories.Count - 1 do begin
C := Categories[i];
TXT.Add(C.Caption);
for j := 0 to C.Items.Count - 1 do begin
B := C.Items[j];
TXT.Add(Chr($09) + B.Caption);
end;
end;
end;
end.
|
unit uloDMRetriever;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
SQLDB,
XMLConf,
SyncObjs,
FGL,
uloCoreConstants,
uloCoreInterfaces,
uloCoreTypes,
uloDMInterfaces,
uloDMTypes;
type
{ TloDMRetriever }
TloDMRetriever = class(TloThreadedDatabaseTask, IloDMRetriever)
private
fModel: TloDMModel;
fSelection: IloDMSelection;
fOnRetrieveCompleteProcedure: TThreadMethod;
public
constructor Create(
aOwner: IloObject;
// aSelection: IloDMSelection;
// aOnRetrieveCompleteProcedure: TThreadMethod;
aTaskName: String = 'Unnamed database metadata model retriever task';
aConnection: TSQLConnector = nil;
aLog: IloLogger = nil;
aConfig: TXMLConfig = nil;
aMutex: TCriticalSection = nil);
destructor Destroy; override;
function GetModel: TloDMModel;
function GetSelection: IloDMSelection;
procedure SetSelection(aSelection: IloDMSelection);
function GetOnRetrieveCompleteProcedure: TThreadMethod;
procedure SetOnRetrieveCompleteProcedure(aOnRetrieveCompleteProcedure: TThreadMethod);
procedure StartRetrieve;
function Start: Boolean; override;
function Pause: Boolean; override;
function Abort: Boolean; override;
property Selection: IloDMSelection read GetSelection;
property Model: TloDMModel read GetModel;
property OnRetrieveCompleteProcedure: TThreadMethod read GetOnRetrieveCompleteProcedure write SetOnRetrieveCompleteProcedure;
{ TODO -oAPL -cCoreTypes 3: Move 'ConnectionTest' up to TloDatabaseObject or IloDatabaseObject? }
// function ConnectionTest: Boolean;
// function RetrieveDatabaseMetadataModel(aSelection: IloDMSelection): TloDMModel; virtual; abstract;
end;
implementation
{ TloDMRetriever }
//function TloDMRetriever.ConnectionTest: Boolean;
//const
// lProcedureName = 'ConnectionTest';
//var
// lExceptionMessage: String;
//begin
// MutexEnter;
//
// LogDebug('Testing connection');
//
// try
// Result := False;
//
// if not Assigned(Connection) then
// raise TloDMException.Create(Format(
// '[%s.%s]: Unable to connect, Connection not assigned.',
// [ClassName, lProcedureName]));
//
// // Test connection
// try
// // Attempt to open the connection
// Connection.Open;
// Result := Connection.Connected;
// Connection.Close;
//
// LogDebug('Connection ok');
//
// except on e:Exception do
// begin
// // Some exception occurred when opening the connection
// { TODO -oAPL 3 -cDMM: Log as a warning? }
// // raise e;
// LogWarning(Format('Exception when testing connection: %s', [e.Message]));
//
// raise TloDMException.Create(Format(
// '[%s.%s]: Unable to connect, exception when connecting: ' + e.Message,
// [ClassName, lProcedureName]));
// end;
// end;
//
// finally
// MutexExit;
// end;
//end;
function TloDMRetriever.GetModel: TloDMModel;
begin
Result := fModel;
end;
function TloDMRetriever.GetSelection: IloDMSelection;
begin
Result := fSelection;
end;
procedure TloDMRetriever.SetSelection(aSelection: IloDMSelection);
begin
case GetTaskStatus of
loTaskReady,
loTaskCompleted,
loTaskTerminated,
loTaskFailed:
fSelection := aSelection;
else
raise TloDMException.CreateFmt('[%s]: Cannot set selection, task already in progress.', [Self.ClassName]);
end;
end;
function TloDMRetriever.GetOnRetrieveCompleteProcedure: TThreadMethod;
begin
Result := fOnRetrieveCompleteProcedure;
end;
procedure TloDMRetriever.SetOnRetrieveCompleteProcedure(aOnRetrieveCompleteProcedure: TThreadMethod);
begin
fOnRetrieveCompleteProcedure := aOnRetrieveCompleteProcedure;
end;
procedure TloDMRetriever.StartRetrieve;
begin
case GetTaskStatus of
loTaskReady,
loTaskCompleted,
loTaskTerminated,
loTaskFailed:
Start;
else
raise TloDMException.CreateFmt('[%s]: Cannot start database metadata retrieve task, task already in progress.', [Self.ClassName]);
end;
end;
function TloDMRetriever.Start: Boolean;
begin
Result:=inherited Start;
end;
function TloDMRetriever.Pause: Boolean;
begin
Result:=inherited Pause;
end;
function TloDMRetriever.Abort: Boolean;
begin
Result:=inherited Abort;
end;
constructor TloDMRetriever.Create(aOwner: IloObject; aTaskName: String; aConnection: TSQLConnector; aLog: IloLogger; aConfig: TXMLConfig;
aMutex: TCriticalSection);
const
lProcedureName = 'Create';
begin
inherited Create(
aOwner,
aTaskName,
aConnection,
aLog,
aConfig,
aMutex);
// fSelection := aSelection;
// fOnRetrieveCompleteProcedure := aOnRetrieveCompleteProcedure;
end;
destructor TloDMRetriever.Destroy;
const
lProcedureName = 'Destroy';
begin
inherited Destroy;
end;
end.
|
{$ifdef license}
(*
Copyright 2020 ChapmanWorld LLC ( https://chapmanworld.com )
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be
used to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*)
{$endif}
/// <summary>
/// cwTest unit testing framework from ChapmanWorld LLC.
/// </summary>
unit cwTest;
{$ifdef fpc}{$mode delphiunicode}{$endif}
interface
uses
sysutils
;
type
/// <summary>
/// This type of exception is raised within a test to indicate that the
/// test failed. <br/>
/// You need not raise this exception directly, instead, call one of the methods
/// of TTest from cwTest.Standard
/// </summary>
EFailedTest = class(Exception);
/// <summary>
/// A simple base class from which to derive test cases. <br/>
/// Descendants of TTestCase may be registered with the singleton
/// TestSuite using ITestSuite.RegisterTestCase() to be run as part
/// of a test suite. <br/> Add parameter-less published methods to TTestCase
/// to have them executed as tests. <br/>
/// If the test case has a method named <b>'Setup'</b> it will be called before
/// each test method. Similarly, if the test case has a method named
/// <b>'TearDown'</b> it will be called after each test method.
/// </summary>
TTestCase = class end;
/// <summary>
/// Class type for passing into RegisterTestCase.
/// </summary>
TTestCaseClass = class of TTestCase;
/// <summary>
/// Represents the three possible result states of running a test.
/// </summary>
TTestResult = (
/// <summary>
/// The test succeeded.
/// </summary>
trSucceeded,
/// <summary>
/// The test failed (did not meet test criteria).
/// </summary>
trFailed,
/// <summary>
/// An error occurred while running the test (exception was raised).
/// </summary>
trError,
/// <summary>
/// An error occurred while running the case Setup() method.
/// </summary>
trSetupError,
/// <summary>
/// An error occurred while running the case TearDown() method.
/// </summary>
trTearDownError
);
/// <summary>
/// An instance of ITestReport is passed to the singleton TestSuite
/// to receive the results of executing its test cases.
/// </summary>
ITestReport = interface
['{CFDD6581-644F-4DF0-898D-C6AAF89E4B0F}']
/// <summary>
/// Called by the ITestSuite implementation when the run of tests
/// begins. A subsequent call to EndTestSuite indicates that this
/// suite has completed its run.
/// </summary>
procedure BeginTestSuite( const TestSuite: string );
/// <summary>
/// Called when the test suite has completed a run to test cases.
/// </summary>
procedure EndTestSuite;
/// <summary>
/// Called by the ITestSuite implementation for each test case before it
/// begins. A subsequent call to EndTestCase will be made to inciate the
/// completion of a test case.
/// </summary>
procedure BeginTestCase( const TestCase: string );
/// <summary>
/// Called by the ITestSuite implementation when a test case has
/// completed its run.
/// </summary>
procedure EndTestCase;
/// <summary>
/// Called by the ITestSuite implementation for each test which is run as
/// part of a test case.
/// </summary>
procedure RecordTestResult( const TestName: string; const TestResultState: TTestResult; const Reason: string );
end;
/// <summary>
/// This is an interface for working with the singleton instance
/// TestSuite, which behaves as a collection of test cases.
/// </summary>
ITestSuite = interface
['{B8E90890-4587-461E-A6DA-71F1C45147DB}']
/// <summary>
/// Called to register a test case with the test suite.
/// </summary>
procedure RegisterTestCase( const TestCase: TTestCaseClass );
/// <summary>
/// Runs all test cases that have been registered with the suite.
/// </summary>
/// <returns>
/// The total number of errors or failures.
/// </returns>
function Run( const SuiteName: string; const TestReports: array of ITestReport ): nativeuint;
end;
implementation
end.
|
program lab4;
const
Digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ' ', '-', '.'];
Accuracy = 0.0000000001;
type
PtrPolynTerm = ^TPolynomialTerm;
TPolynomialTerm = record
Coefficient : real;
Exponent : integer;
Next : PtrPolynTerm;
end;
TPolynomial = Object
private
Head : PtrPolynTerm;
Backup : PtrPolynTerm;
public
Size : integer;
MaxPwr : integer;
constructor Initialize;
procedure Enqueue ( P : TPolynomialTerm);
procedure Dequeue (var P : PtrPolynTerm );
procedure Print (var res : Text );
procedure DecMaxPwr;
end;
constructor TPolynomial.Initialize;
begin
Head := nil;
Backup := nil;
Size := 0;
MaxPwr := 0;
end;
procedure TPolynomial.DecMaxPwr;
begin
dec(MaxPwr);
end;
procedure TPolynomial.Enqueue(P : TPolynomialTerm);
var
PtrNew, PtrCurrent : PtrPolynTerm;
begin
new(PtrNew);
PtrNew^.Coefficient := P.Coefficient;
PtrNew^.Exponent := P.Exponent;
PtrNew^.Next := nil;
if (Head = nil) then
begin
Head := PtrNew;
Backup := Head;
end
else
begin
PtrCurrent := Head;
while Head^.Next <> nil do
begin
Head := Head^.Next;
end;
Head^.Next := PtrNew;
Head := PtrCurrent;
end;
inc(Size);
end;
procedure TPolynomial.Dequeue(var P : PtrPolynTerm);
begin
P := Head;
if Head <> nil then
Head := Head^.Next;
end;
procedure TPolynomial.Print(var res : Text);
var
tmpPol : TPolynomial;
tmpPtr : PtrPolynTerm;
PolTerm : TPolynomialTerm;
i : integer;
begin
if (Size = 0) then
begin
writeln(res, 'Polynomial is empty');
end
else
begin
tmpPol.Head := Backup;
tmpPol.Dequeue(tmpPtr);
PolTerm.Coefficient := tmpPtr^.Coefficient;
PolTerm.Exponent := tmpPtr^.Exponent;
write(res, PolTerm.Coefficient:1:3, 'x^(', PolTerm.Exponent, ')');
i := 2;
for i := i to Size do
begin
tmpPol.Dequeue(tmpPtr);
if abs((tmpPtr^.Coefficient - 0)) < Accuracy then
continue;
if (tmpPtr^.Coefficient >= 0.0) then
write(res, ' + ')
else
write(res, ' ');
PolTerm.Coefficient := tmpPtr^.Coefficient;
PolTerm.Exponent := tmpPtr^.Exponent;
write(res, PolTerm.Coefficient:1:3, 'x^(', PolTerm.Exponent, ')');
end;
writeln(res);
end;
end;
procedure Subtract(var Base : TPolynomial; Subtrahend : TPolynomial);
var
tmpBase : TPolynomial;
tmpSubt : TPolynomial;
resPolyn : TPolynomial;
tmpTerm : TPolynomialTerm;
tmpBTerm : PtrPolynTerm;
tmpSTerm : PtrPolynTerm;
priority : byte;
begin
tmpBase.Head := Base.Head;
tmpBase.Backup := Base.Backup;
tmpBase.Size := Base.Size;
tmpBase.MaxPwr := Base.MaxPwr;
tmpSubt.Head := Subtrahend.Head;
tmpSubt.Backup := Subtrahend.Backup;
tmpSubt.Size := Subtrahend.Size;
tmpSubt.MaxPwr := Subtrahend.MaxPwr;
resPolyn.Initialize;
if (tmpBase.MaxPwr > tmpSubt.MaxPwr) then
resPolyn.MaxPwr := tmpBase.MaxPwr
else
resPolyn.MaxPwr := tmpSubt.MaxPwr;
priority := 2;
while ((tmpBase.Head <> nil) AND (tmpSubt.Head <> nil)) do
begin
if (priority = 0) OR (priority = 2) then
tmpBase.Dequeue(tmpBTerm);
if (priority = 1) OR (priority = 2) then
tmpSubt.Dequeue(tmpSTerm);
if (tmpBTerm^.Exponent = tmpSTerm^.Exponent) then
begin
tmpTerm.Exponent := tmpBTerm^.Exponent;
tmpTerm.Coefficient := tmpBTerm^.Coefficient - tmpSTerm^.Coefficient;
priority := 2;
end
else if (tmpBTerm^.Exponent > tmpSTerm^.Exponent) then
begin
tmpTerm.Exponent := tmpBTerm^.Exponent;
tmpTerm.Coefficient := tmpBTerm^.Coefficient;
priority := 0;
end
else
begin
tmpTerm.Exponent := tmpSTerm^.Exponent;
tmpTerm.Coefficient := -1 * tmpSTerm^.Coefficient;
priority := 1;
end;
resPolyn.Enqueue(tmpTerm);
end;
while (tmpBase.Head <> nil) do
begin
tmpBase.Dequeue(tmpBTerm);
tmpTerm.Exponent := tmpBTerm^.Exponent;
tmpTerm.Coefficient := tmpBTerm^.Coefficient;
resPolyn.Enqueue(tmpTerm);
end;
while (tmpSubt.Head <> nil) do
begin
tmpSubt.Dequeue(tmpSTerm);
tmpTerm.Exponent := tmpSTerm^.Exponent;
tmpTerm.Coefficient := -1 * tmpBTerm^.Coefficient;
resPolyn.Enqueue(tmpTerm);
end;
Base := resPolyn;
end;
procedure Multiply(var tmp : TPolynomial; Base : TPolynomial; Multiplier : TPolynomialTerm);
var
tmpBase : TPolynomial;
resPolyn : TPolynomial;
tmpTermP : PtrPolynTerm;
tmpTerm : TPolynomialTerm;
begin
tmpBase.Head := Base.Backup;
tmpBase.Size := Base.Size;
tmpBase.MaxPwr := Base.MaxPwr;
resPolyn.Initialize;
while (tmpBase.Head <> nil) do
begin
tmpBase.Dequeue(tmpTermP);
tmpTerm.Exponent := tmpTermP^.Exponent + Multiplier.Exponent;
tmpTerm.Coefficient := tmpTermP^.Coefficient * Multiplier.Coefficient;
resPolyn.Enqueue(tmpTerm);
end;
tmp := resPolyn;
end;
procedure Divide (var Dividend, Quontity, Remainder : TPolynomial; Divisor : TPolynomial);
var
dividendTerm : PtrPolynTerm;
divisorTerm : PtrPolynTerm;
tmpTerm : TPolynomialTerm;
tmpBase : TPolynomial;
tmpDivisor : TPolynomial;
tmp : TPolynomial;
begin
tmpBase.Head := Dividend.Head;
tmpBase.Backup := Dividend.Backup;
tmpBase.Size := Dividend.Size;
tmpBase.MaxPwr := Dividend.MaxPwr;
tmpDivisor.Head := Divisor.Head;
tmpDivisor.Backup := Divisor.Backup;
tmpDivisor.Size := Divisor.Size;
tmpDivisor.MaxPwr := Divisor.MaxPwr;
if (Remainder.Size = 0) then
begin
if (tmpBase.MaxPwr < tmpDivisor.MaxPwr) then
begin
Remainder := Dividend;
Remainder.Backup := Remainder.Backup^.Next;
Remainder.Size := Remainder.Size - 1;
end
else
begin
tmpBase .Dequeue(dividendTerm);
tmpDivisor.Dequeue(divisorTerm);
tmpTerm.Exponent := dividendTerm^.Exponent - divisorTerm^.Exponent;
tmpTerm.Coefficient := dividendTerm^.Coefficient / divisorTerm^.Coefficient;
tmp.Initialize;
Multiply(tmp, tmpDivisor, tmpTerm);
Quontity.Enqueue(tmpTerm);
Subtract(Dividend, tmp);
Dividend.MaxPwr := Dividend.MaxPwr - 1;
Dividend.Head := Dividend.Head^.Next;
end;
Divide(Dividend, Quontity, Remainder, Divisor);
end;
end;
procedure ParsePolynomial(var P : TPolynomial; var src, res : Text);
var
tmpString : String;
tmpTerm : TPolynomialTerm;
tmpCoeff : real;
tmpExp : integer;
i, j : integer;
tmpFile : Text;
begin
readln(src, tmpString);
writeln(res, 'Original entry:');
writeln(res, tmpString);
for i := 1 to length(tmpString) do
begin
for j := 1 to length(tmpString) do
begin
if not(tmpString[j] in Digits) then
begin
delete(tmpString, j, 1);
break;
end;
end;
end;
assign(tmpFile, 'tmp.txt');
rewrite(tmpFile);
write(tmpFile, tmpString);
close(tmpFile);
reset(tmpFile);
read(tmpFile, tmpTerm.Coefficient);
read(tmpFile, tmpTerm.Exponent);
P.MaxPwr := tmpTerm.Exponent;
P.Enqueue(tmpTerm);
i := P.MaxPwr - 1;
while not eof(tmpFile) do
begin
read(tmpFile, tmpCoeff);
read(tmpFile, tmpExp);
while i > tmpExp do
begin
tmpTerm.Coefficient := 0;
tmpTerm.Exponent := i;
dec(i);
P.Enqueue(tmpTerm);
end;
tmpTerm.Coefficient := tmpCoeff;
tmpTerm.Exponent := tmpExp;
P.Enqueue(tmpTerm);
dec(i);
end;
Close(tmpFile);
Erase(tmpFile);
end;
var
src, res : Text;
Dividend : TPolynomial;
Divisor : TPolynomial;
Quotient : TPolynomial;
Remainder : TPolynomial;
begin
assign(src, 'src.txt');
reset(src);
assign(res, 'out.txt');
rewrite(res);
writeln(res, 'Dividend Polynomial.');
Dividend.Initialize;
ParsePolynomial(Dividend, src, res);
Dividend.Print(res);
writeln(res);
writeln(res, 'Divisor Polynomial.');
Divisor.Initialize;
ParsePolynomial(Divisor, src, res);
Divisor.Print(res);
writeln(res);
Quotient.Initialize;
Remainder.Initialize;
Divide(Dividend, Quotient, Remainder, Divisor);
writeln(res, 'Quontity: ');
Quotient.Print(res);
writeln(res);
writeln(res, 'Remainder: ');
Remainder.Print(res);
close(src);
close(res);
end.
|
{****************************************************************************************}
{ }
{ XML Data Binding }
{ }
{ Generated on: 27.03.2015 16:42:01 }
{ Generated from: D:\WORK\DSD\DSD\SOURCE\EDI\status_20150316121019_138395551.xml }
{ Settings stored in: D:\WORK\DSD\DSD\SOURCE\EDI\status_20150316121019_138395551.xdb }
{ }
{****************************************************************************************}
unit StatusXML;
interface
uses xmldom, XMLDoc, XMLIntf;
type
{ Forward Decls }
IXMLStatusType = interface;
{ IXMLStatusType }
IXMLStatusType = interface(IXMLNode)
['{FECD7351-6D75-4BDA-99A8-B3EDAC38B77A}']
{ Property Accessors }
function Get_CustomerICID: UnicodeString;
function Get_From: UnicodeString;
function Get_To_: UnicodeString;
function Get_Date: UnicodeString;
function Get_Status: UnicodeString;
function Get_DocNumber: UnicodeString;
function Get_Description: UnicodeString;
function Get_DateIn: UnicodeString;
function Get_SizeInBytes: UnicodeString;
function Get_MessageClass: UnicodeString;
procedure Set_CustomerICID(Value: UnicodeString);
procedure Set_From(Value: UnicodeString);
procedure Set_To_(Value: UnicodeString);
procedure Set_Date(Value: UnicodeString);
procedure Set_Status(Value: UnicodeString);
procedure Set_DocNumber(Value: UnicodeString);
procedure Set_Description(Value: UnicodeString);
procedure Set_DateIn(Value: UnicodeString);
procedure Set_SizeInBytes(Value: UnicodeString);
procedure Set_MessageClass(Value: UnicodeString);
{ Methods & Properties }
property CustomerICID: UnicodeString read Get_CustomerICID write Set_CustomerICID;
property From: UnicodeString read Get_From write Set_From;
property To_: UnicodeString read Get_To_ write Set_To_;
property Date: UnicodeString read Get_Date write Set_Date;
property Status: UnicodeString read Get_Status write Set_Status;
property DocNumber: UnicodeString read Get_DocNumber write Set_DocNumber;
property Description: UnicodeString read Get_Description write Set_Description;
property DateIn: UnicodeString read Get_DateIn write Set_DateIn;
property SizeInBytes: UnicodeString read Get_SizeInBytes write Set_SizeInBytes;
property MessageClass: UnicodeString read Get_MessageClass write Set_MessageClass;
end;
{ Forward Decls }
TXMLStatusType = class;
{ TXMLStatusType }
TXMLStatusType = class(TXMLNode, IXMLStatusType)
protected
{ IXMLStatusType }
function Get_CustomerICID: UnicodeString;
function Get_From: UnicodeString;
function Get_To_: UnicodeString;
function Get_Date: UnicodeString;
function Get_Status: UnicodeString;
function Get_DocNumber: UnicodeString;
function Get_Description: UnicodeString;
function Get_DateIn: UnicodeString;
function Get_SizeInBytes: UnicodeString;
function Get_MessageClass: UnicodeString;
procedure Set_CustomerICID(Value: UnicodeString);
procedure Set_From(Value: UnicodeString);
procedure Set_To_(Value: UnicodeString);
procedure Set_Date(Value: UnicodeString);
procedure Set_Status(Value: UnicodeString);
procedure Set_DocNumber(Value: UnicodeString);
procedure Set_Description(Value: UnicodeString);
procedure Set_DateIn(Value: UnicodeString);
procedure Set_SizeInBytes(Value: UnicodeString);
procedure Set_MessageClass(Value: UnicodeString);
end;
{ Global Functions }
function GetStatus(Doc: IXMLDocument): IXMLStatusType;
function LoadStatus(const XMLString: string): IXMLStatusType;
function NewStatus: IXMLStatusType;
const
TargetNamespace = '';
implementation
{ Global Functions }
function GetStatus(Doc: IXMLDocument): IXMLStatusType;
begin
Result := Doc.GetDocBinding('Status', TXMLStatusType, TargetNamespace) as IXMLStatusType;
end;
function LoadStatus(const XMLString: string): IXMLStatusType;
begin
with NewXMLDocument do begin
LoadFromXML(XMLString);
Result := GetDocBinding('Status', TXMLStatusType, TargetNamespace) as IXMLStatusType;
end;
end;
function NewStatus: IXMLStatusType;
begin
Result := NewXMLDocument.GetDocBinding('Status', TXMLStatusType, TargetNamespace) as IXMLStatusType;
end;
{ TXMLStatusType }
function TXMLStatusType.Get_CustomerICID: UnicodeString;
begin
Result := ChildNodes['CustomerICID'].Text;
end;
procedure TXMLStatusType.Set_CustomerICID(Value: UnicodeString);
begin
ChildNodes['CustomerICID'].NodeValue := Value;
end;
function TXMLStatusType.Get_From: UnicodeString;
begin
Result := ChildNodes['From'].Text;
end;
procedure TXMLStatusType.Set_From(Value: UnicodeString);
begin
ChildNodes['From'].NodeValue := Value;
end;
function TXMLStatusType.Get_To_: UnicodeString;
begin
Result := ChildNodes['To'].Text;
end;
procedure TXMLStatusType.Set_To_(Value: UnicodeString);
begin
ChildNodes['To'].NodeValue := Value;
end;
function TXMLStatusType.Get_Date: UnicodeString;
begin
Result := ChildNodes['Date'].Text;
end;
procedure TXMLStatusType.Set_Date(Value: UnicodeString);
begin
ChildNodes['Date'].NodeValue := Value;
end;
function TXMLStatusType.Get_Status: UnicodeString;
begin
Result := ChildNodes['Status'].Text;
end;
procedure TXMLStatusType.Set_Status(Value: UnicodeString);
begin
ChildNodes['Status'].NodeValue := Value;
end;
function TXMLStatusType.Get_DocNumber: UnicodeString;
begin
Result := ChildNodes['DocNumber'].Text;
end;
procedure TXMLStatusType.Set_DocNumber(Value: UnicodeString);
begin
ChildNodes['DocNumber'].NodeValue := Value;
end;
function TXMLStatusType.Get_Description: UnicodeString;
begin
Result := ChildNodes['Description'].Text;
end;
procedure TXMLStatusType.Set_Description(Value: UnicodeString);
begin
ChildNodes['Description'].NodeValue := Value;
end;
function TXMLStatusType.Get_DateIn: UnicodeString;
begin
Result := ChildNodes['DateIn'].Text;
end;
procedure TXMLStatusType.Set_DateIn(Value: UnicodeString);
begin
ChildNodes['DateIn'].NodeValue := Value;
end;
function TXMLStatusType.Get_SizeInBytes: UnicodeString;
begin
Result := ChildNodes['SizeInBytes'].Text;
end;
procedure TXMLStatusType.Set_SizeInBytes(Value: UnicodeString);
begin
ChildNodes['SizeInBytes'].NodeValue := Value;
end;
function TXMLStatusType.Get_MessageClass: UnicodeString;
begin
Result := ChildNodes['MessageClass'].Text;
end;
procedure TXMLStatusType.Set_MessageClass(Value: UnicodeString);
begin
ChildNodes['MessageClass'].NodeValue := Value;
end;
end. |
unit FH.DeckLink.Notification;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
System.Generics.Collections, Winapi.ActiveX, System.syncobjs, DeckLinkAPI_TLB_10_5;
type
TDeviceNotification = reference to procedure(param1: Largeuint; param2: Largeuint);
TDeckLinkNotification = class(TInterfacedObject, IDeckLinkNotificationCallback)
private
FRefCount : integer;
FDeckLink : IDecklink;
FDeckLinkNotification : IDeckLinkNotification;
FPreferencesChanged : TDeviceNotification;
FDeviceRemoved : TDeviceNotification;
FHardwareConfigurationChanged : TDeviceNotification;
FStatusChanged : TDeviceNotification;
procedure DoStatusChanged(param1: Largeuint; param2: Largeuint);
procedure DoHardwareConfigurationChanged(param1: Largeuint; param2: Largeuint);
procedure DoDeviceRemoved(param1: Largeuint; param2: Largeuint);
procedure DoPreferencesChanged(param1: Largeuint; param2: Largeuint);
procedure SetStatusChanged(AValue: TDeviceNotification);
procedure SetHardwareConfigurationChanged(AValue: TDeviceNotification);
procedure SetDeviceRemoved(AValue: TDeviceNotification);
procedure SetPreferencesChanged(AValue: TDeviceNotification);
public
constructor Create(ADeckLink: IDecklink);
destructor Destroy; override;
property OnPreferencesChanged: TDeviceNotification read FPreferencesChanged write SetPreferencesChanged;
property OnDeviceRemoved: TDeviceNotification read FDeviceRemoved write SetDeviceRemoved;
property OnHardwareConfigurationChanged: TDeviceNotification read FHardwareConfigurationChanged write SetHardwareConfigurationChanged;
property OnStatusChanged: TDeviceNotification read FStatusChanged write SetStatusChanged;
function _Release: Integer; stdcall;
function _AddRef: Integer; stdcall;
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
(* IDeckLinkNotificationCallback methods *)
function Notify(topic: _BMDNotifications; param1: Largeuint; param2: Largeuint): HResult; stdcall;
end;
implementation
(* TDeckLinkDevice *)
constructor TDeckLinkNotification.Create(ADeckLink: IDecklink);
var
LHr : HResult;
begin
FRefCount := 1;
FDeckLink := nil;
FDeckLink := ADeckLink;
if FDeckLink = nil then
Exception.Create('IDecklink is nil');
// Query the DeckLink for its IID_IDeckLinkNotification interface
LHr := FDeckLink.QueryInterface(IID_IDeckLinkNotification, FDeckLinkNotification);
if LHr<>S_OK then
begin
raise Exception.CreateFmt('Could not obtain the IDeckLinkNotification interface - result = %08x', [LHr]);
end;
end;
destructor TDeckLinkNotification.Destroy;
begin
if assigned(FPreferencesChanged) then
FDeckLinkNotification.Unsubscribe(bmdPreferencesChanged, self);
if assigned(FDeviceRemoved) then
FDeckLinkNotification.Unsubscribe(bmdDeviceRemoved, self);
if assigned(FHardwareConfigurationChanged) then
FDeckLinkNotification.Unsubscribe(bmdHardwareConfigurationChanged, self);
if assigned(FStatusChanged) then
FDeckLinkNotification.Unsubscribe(bmdStatusChanged, self);
FRefCount := 0;
inherited;
end;
function TDeckLinkNotification.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
if GetInterface(IID, Obj) then
Result := 0
else
Result := E_NOINTERFACE;
end;
function TDeckLinkNotification._AddRef: Integer;
begin
result := InterlockedIncrement(FRefCount);
end;
function TDeckLinkNotification._Release: Integer;
var
newRefValue : integer;
begin
newRefValue := InterlockedDecrement(FRefCount);
if (newRefValue = 0) then
begin
result := 0;
exit;
end;
result := newRefValue;
end;
procedure TDeckLinkNotification.SetPreferencesChanged(AValue: TDeviceNotification);
var
LHr : HResult;
begin
LHr := FDeckLinkNotification.Subscribe(bmdPreferencesChanged, self);
if LHr = S_OK then FPreferencesChanged := AValue;
end;
procedure TDeckLinkNotification.SetDeviceRemoved(AValue: TDeviceNotification);
var
LHr : HResult;
begin
LHr := FDeckLinkNotification.Subscribe(bmdDeviceRemoved, self);
if LHr = S_OK then FDeviceRemoved := AValue;
end;
procedure TDeckLinkNotification.SetHardwareConfigurationChanged(AValue: TDeviceNotification);
var
LHr : HResult;
begin
LHr := FDeckLinkNotification.Subscribe(bmdHardwareConfigurationChanged, self);
if LHr = S_OK then FHardwareConfigurationChanged := AValue;
end;
procedure TDeckLinkNotification.SetStatusChanged(AValue: TDeviceNotification);
var
LHr : HResult;
begin
LHr := FDeckLinkNotification.Subscribe(bmdStatusChanged, self);
if LHr = S_OK then FStatusChanged := AValue;
end;
procedure TDeckLinkNotification.DoPreferencesChanged(param1: Largeuint; param2: Largeuint);
begin
if assigned(FPreferencesChanged) then
FPreferencesChanged(param1, param2);
end;
procedure TDeckLinkNotification.DoDeviceRemoved(param1: Largeuint; param2: Largeuint);
begin
if assigned(FDeviceRemoved) then
FDeviceRemoved(param1, param2);
end;
procedure TDeckLinkNotification.DoHardwareConfigurationChanged(param1: Largeuint; param2: Largeuint);
begin
if assigned(FHardwareConfigurationChanged) then
FHardwareConfigurationChanged(param1, param2);
end;
procedure TDeckLinkNotification.DoStatusChanged(param1: Largeuint; param2: Largeuint);
begin
if assigned(FStatusChanged) then
FStatusChanged(param1, param2);
end;
function TDeckLinkNotification.Notify(topic: _BMDNotifications; param1: Largeuint; param2: Largeuint): HResult;
begin
case topic of
bmdPreferencesChanged : DoPreferencesChanged(param1, param2);
bmdDeviceRemoved : DoDeviceRemoved(param1, param2);
bmdHardwareConfigurationChanged : DoHardwareConfigurationChanged(param1, param2);
bmdStatusChanged : DoStatusChanged(param1, param2);
end;
result := S_OK;
end;
end.
|
{
5. A partir de un siniestro ocurrido se perdieron las actas de nacimiento y fallecimientos de toda la provincia de buenos aires de los últimos diez años.
En pos de recuperar dicha información, se deberá procesar 2 archivos por cada una de las 50 delegaciones distribuidas en la provincia,
un archivo de nacimientos y otro de fallecimientos y crear el archivo maestro reuniendo dicha información.
Los archivos detalles con nacimientos, contendrán la siguiente información:
nro partida nacimiento, nombre, apellido, dirección detallada(calle,nro, piso, depto, ciudad), matrícula del médico, nombre y apellido de la madre,
DNI madre, nombre y apellido del padre, DNI del padre.
En cambio los 50 archivos de fallecimientos tendrán:
nro partida nacimiento, DNI, nombre y apellido del fallecido, matrícula del médico que firma el deceso, fecha y hora del deceso y lugar.
Realizar un programa que cree el archivo maestro a partir de toda la información los archivos.
Se debe almacenar en el maestro: nro partida nacimiento, nombre, apellido, dirección detallada
(calle,nro, piso, depto, ciudad), matrícula del médico, nombre y apellido de la madre, DNI madre, nombre y apellido del padre, DNI del padre
y si falleció, además matrícula del médico que firma el deceso, fecha y hora del deceso y lugar.
Se deberá, además, listar en un archivo de texto la información recolectada de cada persona.
Nota: Todos los archivos están ordenados por nro partida de nacimiento que es única.
Tenga en cuenta que no necesariamente va a fallecer en el distrito donde nació la persona y además puede no haber fallecido.
}
program actas;
const
tam = 5; //50
corte = -1;
valorAlto = 9999;
type
direccion = record
calle: string;
nro: integer;
piso: integer;
depto: string;
ciudad: string;
end;
rango = 1..tam;
rDNac = record
nroPartida: integer;
nomYap: string;
direcc: direccion;
matMedica: integer;
mDni: integer;
mNomYAp: string;
pDni: integer;
pNomYap: string;
end;
rDFall = record
nroPartida: integer;
dni: integer;
nomYap: string;
matMedica: integer;
fecha: string;
hora: string;
lugar: String;
end;
rMaestro = record
nroPartida: integer;
direc : direccion;
matMedico: integer;
mNomYAp: string;
mDni: integer;
pNomYAp: string;
pDni: integer;
fallecio: boolean;
matMedicoDeceso: integer;
fecha: string;
hora: string;
lugar: string;
end;
dNac = file of rDNac;
dFall = file of rDFall;
maestro = file of rMaestro;
vDN = array [rango] of dNac; //vectores de archivos
vDF = array[rango] of dFall;
vrn = array[rango] of rDNac; //vectores para lectura de registros
vrf = array[rango] of rDFall;
//----------------------------------------------------------------------
procedure leerN(var dn: dNac; var rd: rDNac);
begin
if (not eof(dn)) then
read(dn, rd)
else
rd.nroPartida := valorAlto;
end;
procedure leerF(var df: dFall; var rf: rDFall);
begin
if (not eof(df)) then
read(df, rf)
else
rf.nroPartida := valorAlto;
end;
//----------------------------------------------------------------------
procedure minimoFallecimiento(var vF: vDF; var vRF: vrf; var minF: rDFall); //parámetros: vector de arch detalle; vector de registros; registro mínimo
var
i, posMin: integer;
begin
minF.nroPartida := valorAlto;
for i:= 1 to tam do begin
if (vrf[i].nroPartida < minF.nroPartida) then begin
posMin:= i;
minF:= vrf[i];
end;
end;
if (minF.nroPartida <> valorAlto) then
leerF(vf[posMin], vrf[posMin]);
End;
//----------------------------------------------------------------------
procedure minimoNacimiento(var vecNac: vDN; var vecRegNac: vrn; var minN: rDNac); //parámetros: vector de arch detalle; vector de registros; registro mínimo
var
i, posMin: integer;
begin
minN.nroPartida := valorAlto;
for i:= 1 to tam do begin
if (vecRegNac[i].nroPartida < minN.nroPartida) then begin
posMin:= i;
minN:= vecRegNac[i];
end;
end;
if(minN.nroPartida <> valorAlto) then
leerN(vecNac[posMin], vecRegNac[posMin]);
End;
//----------------------------------------------------------------------
procedure generarMaestro(var m: maestro; var dn: vDN; var vRN: vrn; var df: vDF; var vRF: vrf); //vecDetalle, vecRegistro x2
var
minF: rDfall; //registro detalle
minN: rDNac; //reg detalle
rm: rMaestro;
i: integer;
begin
assign(m, 'archivoMaestroDeActas');
rewrite(m);
minimoFallecimiento(df,vRF, minF); //parámetros: vector de arch detalle; vector de registros; registro mínimo
minimoNacimiento(dn,vRN,minN);
while(minN.nroPartida <> valorAlto) do begin
rm.fallecio := true;
rm.nroPartida:= minN.nroPartida;
rm.direc := minN.direcc;
rm.matMedico:= minN.matMedica;
rm.mNomYAp:= minN.NomYAp;
rm.mDni:= minN.mDni;
rm.pNomYAp:= minN.pNomYAp;
rm.pDni:= minN.pDni;
if (minN.nroPartida = minF.nroPartida) then begin
rm.fallecio:= true;
rm.matMedicoDeceso:= minF.matMedica;
rm.fecha:= minF.fecha;
rm.hora:= minF.hora;
rm.lugar:= minF.lugar;
minimoFallecimiento(df,vRF, minF);
end;
write(m, rm);
minimoNacimiento(dn,vRN,minN);
end;
close(m);
for i:= 1 to tam do begin
close(dn[i]);
close(df[i]);
end;
close(m);
End;
//----------------------------------------------------------------------
VAR
m: maestro;
vecDetalleFall: vDF; //vectores de archivos
vecDetalleNac: vDN;
vecRegFall: vrf; //vectores de registros
vecRegNac: vrn;
regNac: rDNac; //registros detalle
regFall: rDFall;
dn: dNac; //archivos detalle
df: dFall;
i: integer;
nd: string;
BEGIN
//abrir archivos para generar el maestro
for i:= 1 to tam do begin
Str(i, nd);
assign(vecDetalleFall[i], 'ArchivoDeFallecimientos-DelegacionN'+nd);
reset(vecDetalleFall[i]);
assign(vecDetalleNac[i], 'ArchivoDeNacimientos-DelegacionN'+nd);
reset(vecDetalleNac[i]);
leerN(dn, regNac);
leerF(df, regFall);
end;
generarMaestro(m,vecDetalleNac, vecRegNac,vecDetalleFall, vecRegFall); //vecDetalle, vecRegistro x2
END.
|
program fontreq;
{$IFNDEF HASAMIGA}
{$FATAL This source is compatible with Amiga, AROS and MorphOS only !}
{$ENDIF}
{
Project : fontreq
Source : RKRM
Note : Examples updated to compile for OS 3.x
FPC Note : Example update to use new style ASL Tags
}
{*
** The following example illustrates how to use a font requester.
*}
{$MODE OBJFPC}{$H+}{$HINTS ON}
{$UNITPATH ../../../Base/CHelpers}
{$UNITPATH ../../../Base/Trinity}
{$IFDEF AMIGA} {$UNITPATH ../../../Sys/Amiga} {$ENDIF}
{$IFDEF AROS} {$UNITPATH ../../../Sys/AROS} {$ENDIF}
{$IFDEF MORPHOS} {$UNITPATH ../../../Sys/MorphOS} {$ENDIF}
Uses
Exec, AGraphics, ASL, Utility,
{$IFDEF AMIGA}
SystemVarTags,
{$ENDIF}
SysUtils,
CHelpers,
Trinity;
Const
vers : PChar = '$VER: fontreq 37.0';
{* Our replacement strings for the "mode" cycle gadget. The
** first string is the cycle gadget's label. The other strings
** are the actual strings that will appear on the cycle gadget.
*}
modelist : array[0..6] of PChar =
(
'RKM Modes',
'Mode 0',
'Mode 1',
'Mode 2',
'Mode 3',
'Mode 4',
nil
);
Procedure Main(argc: integer; argv: ppchar);
var
fr : PFontRequester;
begin
{$IF DEFINED(AMIGA) or DEFINED(MORPHOS)}
If SetAndTest(AslBase, OpenLibrary('asl.library', 37)) then
{$ENDIF}
begin
If SetAndTest(fr, AllocAslRequestTags(ASL_FontRequest,
[
//* tell the requester to use my custom mode names */
TAG_(ASLFO_ModeList) , TAG_(@modelist), // TAG_(ASL_ModeList) , TAG_(@modelist),
//* Supply initial values for requester */
TAG_(ASLFO_InitialName) , TAG_(PChar('topaz.font')), // TAG_(ASL_FontName) , TAG_(PChar('topaz.font')),
TAG_(ASLFO_InitialSize) , 11, // TAG_(ASL_FontHeight) , 11,
TAG_(ASLFO_InitialStyle) , FSF_BOLD or FSF_ITALIC, // TAG_(ASL_FontStyles) , FSF_BOLD or FSF_ITALIC,
TAG_(ASLFO_InitialFrontPen) , $00, // TAG_(ASL_FrontPen) , $00,
TAG_(ASLFO_InitialBackPen) , $01, // TAG_(ASL_BackPen) , $01,
//* Only display font sizes between 8 and 14, inclusive. */
TAG_(ASLFO_MinHeight) , 8, // TAG_(ASL_MinHeight) , 8,
TAG_(ASLFO_MaxHeight) , 14, // TAG_(ASL_MaxHeight) , 14,
//* Give all the gadgetry, but only display fixed width fonts */
// TAG_(ASL_FuncFlags) , FONF_FRONTCOLOR or FONF_BACKCOLOR or FONF_DRAWMODE or FONF_STYLES or FONF_FIXEDWIDTH,
TAG_(ASLFO_Flags) , FOF_DOFRONTPEN or FOF_DOBACKPEN or FOF_DODRAWMODE or FOF_DOSTYLE or FOF_FIXEDWIDTHONLY,
TAG_DONE
])) then
begin
//* Pop up the requester */
if (AslRequest(fr, nil)) then
begin
//* The user selected something, report their choice */
WriteLn(Format
(
'%s' + LineEnding +
' YSize = %d Style = 0x%x Flags = 0x%x' + LineEnding +
' FPen = 0x%x BPen = 0x%x DrawMode = 0x%x',
[
fr^.fo_Attr.ta_Name,
fr^.fo_Attr.ta_YSize,
fr^.fo_Attr.ta_Style,
fr^.fo_Attr.ta_Flags,
fr^.fo_FrontPen,
fr^.fo_BackPen,
fr^.fo_DrawMode
])
);
end
else
//* The user cancelled the requester, or some kind of error
//* occurred preventing the requester from opening. */
WriteLn('Request Cancelled');
FreeAslRequest(fr);
end;
{$IF DEFINED(AMIGA) or DEFINED(MORPHOS)}
CloseLibrary(AslBase);
{$ENDIF}
end;
end;
begin
Main(ArgC, ArgV);
end.
|
unit Customer;
interface
uses SysUtils, Dialogs, Classes;
type
TCustomer = class(TObject)
public
constructor Create;
procedure setId(id:String);
procedure setFirstName(firstName:String);
procedure setLastName(lastName:String);
procedure setBirthDay(birthday:String);
procedure setStreet(street:String);
procedure setZip(zip:String);
procedure setCity(city:String);
procedure setEmail(email:String);
procedure setPhone(phone:String);
function save : Boolean;
private
fields : Array of String;
id : String;
firstName : String;
lastName : String;
birthday : String;
street : String;
zip : String;
city : String;
email : String;
phone : String;
saveFile : TStringList;
end;
implementation
constructor TCustomer.Create;
begin
{ create the needed directories }
createDir('cst');
{ set the fields }
setlength(Self.fields, 9);
Self.fields[0] := 'Kundennummer';
Self.fields[1] := 'Vorname';
Self.fields[2] := 'Name';
Self.fields[3] := 'Geburtstag';
Self.fields[4] := 'Straße';
Self.fields[5] := 'PLZ';
Self.fields[6] := 'Ort';
Self.fields[7] := 'Email';
Self.fields[8] := 'Telefonnummer';
end;
procedure TCustomer.setId(id:String);
begin
Self.id := id;
end;
procedure TCustomer.setFirstName(firstName:String);
begin
Self.firstName := firstName;
end;
procedure TCustomer.setLastName(lastName:String);
begin
Self.lastName := lastName;
end;
procedure TCustomer.setBirthDay(birthday:String);
begin
Self.birthday := birthday;
end;
procedure TCustomer.setStreet(street:String);
begin
Self.street := street;
end;
procedure TCustomer.setZip(zip:String);
begin
Self.zip := zip;
end;
procedure TCustomer.setCity(city:String);
begin
Self.city := city;
end;
procedure TCustomer.setEmail(email:String);
begin
Self.email := email;
end;
procedure TCustomer.setPhone(phone:String);
begin
Self.phone := phone;
end;
function TCustomer.save : Boolean;
var
filename : String;
begin
filename := StringReplace(Self.id, '/', '-', [rfReplaceAll, rfIgnoreCase]);
Self.saveFile := TStringList.Create;
Self.saveFile.Add('CST+'
+ Self.id + '+'
+ Self.lastName + ':'
+ Self.firstName + '+'
+ Self.birthday + '+'
+ Self.street + ':'
+ Self.zip + ':'
+ Self.city + '+'
+ Self.email
+ Self.phone + ''''
);
if (length(filename) > 0) then
Self.saveFile.saveToFile('cst\' + filename);
Result := true;
end;
end.
|
unit astar3d_world;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,astar3d_point3d;
type
TArrayOfBoolean = array of Boolean;
TWorld = class
strict private
sx: Integer;
sy: Integer;
sz: Integer;
offsetIdx: Integer;
worldBlocked: TArrayOfBoolean;
public
constructor Create(width: Integer; height: Integer); overload;
constructor Create(width: Integer; height: Integer; depth: Integer); overload;
function get_Left: Integer;
function get_Right: Integer;
function get_Bottom: Integer;
function get_Top: Integer;
function get_Front: Integer;
function get_Back: Integer;
property Left: Integer read get_Left;
property Right: Integer read get_Right;
property Bottom: Integer read get_Bottom;
property Top: Integer read get_Top;
property Front: Integer read get_Front;
property Back: Integer read get_Back;
procedure MarkPosition(position: TPoint3D; value: Boolean);
strict private
procedure MarkPositionEx(position: TPoint3D; value: Boolean);
public
function PositionIsFree(position: TPoint3D): Boolean;
end;
implementation
{$AUTOBOX ON}
{$HINTS OFF}
{$WARNINGS OFF}
constructor TWorld.Create(width: Integer; height: Integer);
begin
Create(width, height, 1);
end;
constructor TWorld.Create(width: Integer; height: Integer; depth: Integer);
var
x: Integer;
z: Integer;
zz: Integer;
y: Integer;
yy: Integer;
xx: Integer;
begin
inherited Create;
Self.sx := (width + 2);
Self.sy := (height + 2);
Self.sz := (depth + 2);
Self.offsetIdx := (0 + 1) + ((0 + 1) + (0 + 1) * sy) * sx;
setlength(worldBlocked,sx * sy * sz); ;//new Boolean[sx * sy * sz];
x := 0;
while (x < Self.sx) do
begin
y := 0;
while (y < Self.sy) do
begin
MarkPositionEx(TPoint3D.Create(x, y, 0), True);
MarkPositionEx(TPoint3D.Create(x, y, (Self.sz - 1)), True);
///*PreInc*/;
y+=1;
end;
//*PreInc*/;
x+=1;
end;
y := 0;
while (y < Self.sy) do
begin
z := 0;
while (z < Self.sz) do
begin
MarkPositionEx(TPoint3D.Create(0, y, z), True);
MarkPositionEx(TPoint3D.Create((Self.sx - 1), y, z), True);
//*PreInc*/;
z+=1;
end;
//*PreInc*/;
y+=1;
end;
z := 0;
while (z < Self.sz) do
begin
x := 0;
while (x < Self.sx) do
begin
MarkPositionEx(TPoint3D.Create(x, 0, z), True);
MarkPositionEx(TPoint3D.Create(x, (Self.sy - 1), z), True);
//*PreInc*/;
x+=1;
end;
//*PreInc*/;
z+=1;
end;
end;
function TWorld.get_Left: Integer;
begin
Result := 0;
end;
function TWorld.get_Right: Integer;
begin
Result := (Self.sx - 2);
end;
function TWorld.get_Bottom: Integer;
begin
Result := 0;
end;
function TWorld.get_Top: Integer;
begin
Result := (Self.sy - 2);
end;
function TWorld.get_Front: Integer;
begin
Result := 0;
end;
function TWorld.get_Back: Integer;
begin
Result := (Self.sz - 2);
end;
procedure TWorld.MarkPosition(position: TPoint3D; value: Boolean);
begin
//Self.worldBlocked[((Self.offsetIdx + position.X) + )] := value;
worldBlocked[offsetIdx + position.X + (position.Y + position.Z * sy) * sx] := value;
end;
procedure TWorld.MarkPositionEx(position: TPoint3D; value: Boolean);
begin
//Self.worldBlocked[(position.X + )] := value;
worldBlocked[position.X + (position.Y + position.Z * sy) * sx] := value;
end;
function TWorld.PositionIsFree(position: TPoint3D): Boolean;
begin
result:= not worldBlocked[offsetIdx + position.X + (position.Y + position.Z * sy) * sx];
// Result := (Self.worldBlocked[((Self.offsetIdx + position.X) + )] = False);
end;
end.
|
unit AdmClass_DM_Unit;
interface
uses
SysUtils, Classes, DB, IBDatabase, IBScript, BDEInfoUnit, IBSQL,
AdmClass_AdmObjects_Unit, IBCustomDataSet, IBQuery, IBUpdateSQL,
IBServices,Variants, kbmMemTable;
type
TFirebirdServer = record
ServerName: string;
Local: boolean;
end;
TDM_AdmClass = class(TDataModule)
IBScript_Adm: TIBScript;
IBTr_Adm: TIBTransaction;
IBDb_Adm: TIBDatabase;
ibsSelectListOfTables: TIBSQL;
ibsSelectListOfTables_From_S_RIGHTS: TIBSQL;
ibsSelectListOfUsers_From_S_BRIG_NOT_NULL: TIBSQL;
ibsInsertTableInto_S_RIGHTS: TIBSQL;
ibsSelectListOfProcedures: TIBSQL;
ibqYesNo_READ: TIBQuery;
ibqYesNo_ZAV: TIBQuery;
ibqYesNo_RASK: TIBQuery;
ibqYesNo_ZADV: TIBQuery;
ibqYesNo_POTER: TIBQuery;
ibqYesNo_NARAD: TIBQuery;
ibqYesNo_DEL: TIBQuery;
ibqYesNo_ADMIN: TIBQuery;
IBTr_YesNo: TIBTransaction;
ibqYesNo_READID: TIntegerField;
ibqYesNo_READNAME_R: TIBStringField;
ibqYesNo_ZAVID: TIntegerField;
ibqYesNo_ZAVNAME_R: TIBStringField;
ibqYesNo_RASKID: TIntegerField;
ibqYesNo_RASKNAME_R: TIBStringField;
ibqYesNo_ZADVID: TIntegerField;
ibqYesNo_ZADVNAME_R: TIBStringField;
ibqYesNo_POTERID: TIntegerField;
ibqYesNo_POTERNAME_R: TIBStringField;
ibqYesNo_NARADID: TIntegerField;
ibqYesNo_NARADNAME_R: TIBStringField;
ibqYesNo_DELID: TIntegerField;
ibqYesNo_DELNAME_R: TIBStringField;
ibqYesNo_ADMINID: TIntegerField;
ibqYesNo_ADMINNAME_R: TIBStringField;
ibsTemp: TIBSQL;
IBSecurityService1: TIBSecurityService;
ibqSelect_S_BRIG: TIBQuery;
dsSelect_S_BRIG: TDataSource;
ibqSelect_S_BRIGID: TIntegerField;
ibqSelect_S_BRIGNAME_R: TIBStringField;
ibqSelect_S_BRIGDOLGN: TIBStringField;
ibqSelect_S_BRIGUID: TIBStringField;
ibqSelect_S_BRIGPRAVA: TIBStringField;
ibsUPdatePassword: TIBSQL;
ibqSelect_S_BRIGSYS_PASSWORD: TIBStringField;
IBT_ChangePass: TIBTransaction;
mem_usersPassword: TkbmMemTable;
mem_usersPassworduid: TStringField;
mem_usersPasswordsys_password: TStringField;
procedure DataModuleDestroy(Sender: TObject);
private
FAlias, FSysDbaPassword, FPathOfAlias : string;
FFirebirdServer: TFirebirdServer;
{ Private declarations }
FTablesList: TStringList;
FTablesList_From_S_RIGHTS: TStringList;
FUsersList_From_S_BRIG_NOT_NULL: TStringList;
FProceduresList: TStringList;
function GetFTablesList():TStrings;
function GetFTablesList_From_S_RIGHTS():TStrings;
function GetFUsersList_From_S_BRIG_NOT_NULL():TStrings;
function GetFProceduresList():TStrings;
{ определим местоположение сервера Firebird по алиасу }
procedure DetectServerLocation;
//
procedure ActivateIBSecurityService;
public
{ Public declarations }
constructor Create(AOwner:TComponent; _alias: string; _SysDbaPassword:string); reintroduce;
function ScriptExec(var _sql:string):boolean;
procedure AddTableTo_S_RIGHTS(_tabl_name: string);
//
procedure Commit;
procedure StartTransaction;
procedure Rollback;
//
function FillProceduresList():TStrings;
function FillTablesList():TStrings;
function FillTablesList_From_S_RIGHTS():TStrings;
function FillUsersList_From_S_BRIG_NOT_NULL():TStrings;
//
function DeleteUserFromDataBase(_uid: string): boolean;
function AddUserToDataBase(_uid: string;var _pass: string; _update_password_if_user_exists: boolean ):boolean;
function UpdateUserPasswordToDataBase(_uid: string; _pass: string ):boolean;
function ExistsUser(_uid: string): boolean;
//
procedure Connect;
procedure Init;
//
property TablesList: TStrings read GetFTablesList;
property TablesList_From_S_RIGHTS: TStrings read GetFTablesList_From_S_RIGHTS;
property UsersList_From_S_BRIG_NOT_NULL: TStrings read GetFUsersList_From_S_BRIG_NOT_NULL;
property ProceduresList: TStrings read GetFProceduresList;
property FirebirdServer: TFirebirdServer read FFirebirdServer;
property Alias:string read FAlias;
//
end;
var
DM_AdmClass: TDM_AdmClass;
implementation
{$R *.dfm}
procedure TDM_AdmClass.Connect;
var
_bdei:TBDEInfo;
//_pass:string;
begin
_bdei := TBDEInfo.Create;
try
FPathOfAlias := '';
FPathOfAlias := _bdei.IBGetPathOfAlias(FAlias);
IBDB_Adm.DatabaseName := FPathOfAlias;
IBDB_Adm.Params[0] := 'password=' + FSysDbaPassword;
try
IBDB_Adm.Connected := true;
except
on E:Exception do
raise Exception.Create('Ошибка при подключении к базе данных '#13 + 'с алиасом ' + FAlias +#13 +
'и путём: ' + FPathOfAlias + ';' + #13 + E.Message);
end;
DetectServerLocation;
//
FillProceduresList();
FillTablesList();
finally
_bdei.Free;
end;
end;
procedure TDM_AdmClass.Init;
begin
StartTransaction;
ibqSelect_S_BRIG.Open;
//
FillTablesList_From_S_RIGHTS();
FillUsersList_From_S_BRIG_NOT_NULL();
end;
function TDM_AdmClass.ExistsUser(_uid: string): boolean;
begin
//result := false;
with IBSecurityService1 do
begin
Active := True;
try
DisplayUser(_uid);
//Edit2.Text := UserInfo[0].FirstName;
result := Assigned(UserInfo[0]);
if result then
begin
//UserInfo[0].
end;
finally
Active := False;
end;
end;
end;
procedure TDM_AdmClass.ActivateIBSecurityService;
var _p:string;
begin
if FFirebirdServer.Local then _p := 'Local' else _p := 'TCP';
try
IBSecurityService1.Active := true;
except
raise Exception.Create('Неудача подключения IBSecurityService к серверу:'#13 +
'"' + FFirebirdServer.ServerName + '" по порту "' + _p + '"' );
end;
end;
procedure TDM_AdmClass.DetectServerLocation;
var {_i, } _k, _l: integer;
_s:string;
begin
_l := length(FPathOfAlias);
_k := POS(':',FPathOfAlias);
if (_k<1) or ((_k+1)>_l) then raise Exception.Create('Неправильно задан алиас!');
_s := Copy(FPathOfAlias, 1, _k-1);
FFirebirdServer.Local := FPathOfAlias[_k+1]='\'; {т.е. буква диска};
if FFirebirdServer.Local
then FFirebirdServer.ServerName := ''
else FFirebirdServer.ServerName := _s;
//
IBSecurityService1.ServerName := FFirebirdServer.ServerName;
if FFirebirdServer.Local
then IBSecurityService1.Protocol := Local
else IBSecurityService1.Protocol := TCP;
IBSecurityService1.Params.Clear;
IBSecurityService1.Params.Add('user_name=sysdba');
IBSecurityService1.Params.Add('password=' + FSysDbaPassword);
end;
function TDM_AdmClass.DeleteUserFromDataBase(_uid: string): boolean;
begin
result := true;
try
with IBSecurityService1 do
begin
ActivateIBSecurityService;
try
UserName := _uid;
DeleteUser;
finally
Active := False;
end;
end;
except
result := false;
end;
end;
function TDM_AdmClass.UpdateUserPasswordToDataBase(_uid: string; _pass: string):boolean;
begin
try
with IBSecurityService1 do
begin
ActivateIBSecurityService;
try
UserName := _uid;
FirstName := '';
MiddleName := '';
LastName := '';
UserID := 0;
GroupID := 0;
Password := _pass;
ModifyUser;
result := true;
finally
Active := false;
end;
end;
except
result := false;
end;
end;
function TDM_AdmClass.AddUserToDataBase( _uid: string; var _pass: string; _update_password_if_user_exists: boolean ):boolean;
var old_pass:string;
change_pass:boolean;
begin
change_pass:=false;
old_pass:='';
if mem_usersPassword.Locate('uid',VarArrayOf([_uid]),[loPartialKey]) then
if not mem_usersPassword.FieldByName('sys_password').IsNull then
old_pass:=mem_usersPassword.FieldByName('sys_password').AsString
else
change_pass:=true;
if (not _update_password_if_user_exists) and (old_pass<>'') then
begin
_pass:=old_pass;
end ;
result := ExistsUser(_uid);
if not result then
begin
try
with IBSecurityService1 do
begin
ActivateIBSecurityService;
//
try
UserName := _uid;
FirstName := '';
MiddleName := '';
LastName := '';
UserID := 0;
GroupID := 0;
Password := _pass;
AddUser;
change_pass:=true;
result := true;
finally
Active := false;
end;
end;
except
result := false;
end;
end
else
begin
if _update_password_if_user_exists or change_pass then
begin
try
result := UpdateUserPasswordToDataBase( _uid, _pass );
change_pass:=true;
except
result := false;
end;
end;
end;
if (not change_pass) and (old_pass<>'') then
_pass:=old_pass;
end;
function TDM_AdmClass.FillProceduresList():TStrings;
begin
FProceduresList.Clear;
with ibsSelectListOfProcedures do
begin
Close;
StartTransaction;
ExecQuery;
while not (EOF) do
begin
FProceduresList.Add(AnsiUpperCase(trim(FieldByName('proc_name').AsString)));
Next;
end;
Close;
end;
result := FProceduresList;
end;
procedure TDM_AdmClass.AddTableTo_S_RIGHTS(_tabl_name: string);
begin
with ibsInsertTableInto_S_RIGHTS do
begin
Close;
StartTransaction;
SQL.Text :=
' insert into s_rights (name_r, ur_read, ur_admin) values ( "' + _tabl_name + '", 1, 1) ';
try
ExecQuery;
Commit;
except
Rollback;
end;
Close;
end;
end;
function TDM_AdmClass.FillUsersList_From_S_BRIG_NOT_NULL():TStrings;
begin
FUsersList_From_S_BRIG_NOT_NULL.Clear;
if mem_usersPassword.Active then
mem_usersPassword.Close;
mem_usersPassword.Open;
with ibsSelectListOfUsers_From_S_BRIG_NOT_NULL do
begin
Close;
StartTransaction;
ExecQuery;
//
while not (EOF) do
begin
FUsersList_From_S_BRIG_NOT_NULL.AddObject(
(AnsiUpperCase(trim(FieldByName('uid').AsString)) + '=' +
AnsiUpperCase(trim(FieldByName('prava').AsString)) ),
pointer(FieldByName('id').AsInteger)
);
mem_usersPassword.Append;
mem_usersPassword.FieldByName('uid').AsString:=FieldByName('uid').AsString;
mem_usersPassword.FieldByName('sys_password').AsString:=FieldByName('sys_password').AsString;
mem_usersPassword.Post;
Next;
end;
Close;
end;
result := FUsersList_From_S_BRIG_NOT_NULL;
end;
function TDM_AdmClass.FillTablesList_From_S_RIGHTS():TStrings;
var _rights: string;
begin
FTablesList_From_S_RIGHTS.Clear;
with ibsSelectListOfTables_From_S_RIGHTS do
begin
Close;
StartTransaction;
ExecQuery;
//
while not (EOF) do
begin
_rights := '';
{UR_READ, UR_ZAV, UR_RASK, UR_ZADV, UR_POTER, UR_NARAD, UR_DEL, UR_ADMIN}
if (FieldByName('UR_READ').AsInteger=1) then _rights := _rights + USER_RIGHTS_STR[integer(turRead)];
if (FieldByName('UR_ZAV').AsInteger=1) then _rights := _rights + USER_RIGHTS_STR[integer(turZav)];
if (FieldByName('UR_RASK').AsInteger=1) then _rights := _rights + USER_RIGHTS_STR[integer(turRask)];
if (FieldByName('UR_ZADV').AsInteger=1) then _rights := _rights + USER_RIGHTS_STR[integer(turZadv)];
if (FieldByName('UR_POTER').AsInteger=1) then _rights := _rights + USER_RIGHTS_STR[integer(turPoter)];
if (FieldByName('UR_NARAD').AsInteger=1) then _rights := _rights + USER_RIGHTS_STR[integer(turNarad)];
if (FieldByName('UR_DEL').AsInteger=1) then _rights := _rights + USER_RIGHTS_STR[integer(turDel)];
if (FieldByName('UR_ADMIN').AsInteger=1) then _rights := _rights + USER_RIGHTS_STR[integer(turAdmin)];
//
FTablesList_From_S_RIGHTS.Add(
AnsiUpperCase(trim(FieldByName('name_r').AsString)) + '=' + _rights);
Next;
end;
Close;
end;
result := FTablesList_From_S_RIGHTS;
end;
function TDM_AdmClass.GetFUsersList_From_S_BRIG_NOT_NULL():TStrings;
begin
result := FUsersList_From_S_BRIG_NOT_NULL;
end;
function TDM_AdmClass.GetFTablesList_From_S_RIGHTS():TStrings;
begin
result := FTablesList_From_S_RIGHTS;
end;
function TDM_AdmClass.GetFProceduresList():TStrings;
begin
result := FProceduresList;
end;
procedure TDM_AdmClass.StartTransaction;
begin
if not IBDb_Adm.DefaultTransaction.InTransaction then IBDb_Adm.DefaultTransaction.StartTransaction;
end;
procedure TDM_AdmClass.Commit;
begin
if IBDb_Adm.DefaultTransaction.InTransaction then IBDb_Adm.DefaultTransaction.Commit;
end;
procedure TDM_AdmClass.Rollback;
begin
if IBDb_Adm.DefaultTransaction.InTransaction then IBDb_Adm.DefaultTransaction.Rollback;
end;
function TDM_AdmClass.GetFTablesList():TStrings;
begin
result := FTablesList;
end;
function TDM_AdmClass.FillTablesList():TStrings;
begin
FTablesList.Clear;
with ibsSelectListOfTables do
begin
Close;
StartTransaction;
ExecQuery;
while not (EOF) do
begin
FTablesList.Add(AnsiUpperCase(trim(FieldByName('tabl_name').AsString)));
Next;
end;
Close;
end;
result := FTablesList;
end;
function TDM_AdmClass.ScriptExec(var _sql:string):boolean;
begin
//result := false;
IBScript_Adm.Script.Text := _sql;
try
IBScript_Adm.ExecuteScript;
if IBTr_Adm.InTransaction then IBTr_Adm.Commit;
result := true;
except
on E:Exception do
begin
if IBTr_Adm.InTransaction then IBTr_Adm.Rollback;
//raise exception.Create('Ошибка выполнения скрипта!'+#13+E.Message);
result := false;
end;
end;
end;
constructor TDM_AdmClass.Create(AOwner:TComponent; _alias: string; _SysDbaPassword:string);
begin
FAlias := _alias;
FSysDbaPassword := _SysDbaPassword;
FTablesList := TStringList.Create;
FTablesList_From_S_RIGHTS := TStringList.Create;
FUsersList_From_S_BRIG_NOT_NULL := TStringList.Create;
FProceduresList := TStringList.Create;
inherited Create(AOwner);
end;
procedure TDM_AdmClass.DataModuleDestroy(Sender: TObject);
begin
if IBSecurityService1.Active then IBSecurityService1.Active := false;
FTablesList.Free;
FTablesList_From_S_RIGHTS.Free;
FUsersList_From_S_BRIG_NOT_NULL.Free;
FProceduresList.Free;
//
ibqSelect_S_BRIG.Close;
mem_usersPassword.Close;
//
IBDb_Adm.Connected := false;
IBDb_Adm.ForceClose;
IBDb_Adm.SetHandle( nil );
end;
end.
|
unit ProjYearWin;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, IniFiles, StdCtrls, CommUtils;
type
TfrmProjYear = class(TForm)
Memo1: TMemo;
GroupBox1: TGroupBox;
btnOk: TButton;
btnCancel: TButton;
procedure btnOkClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
class procedure ShowForm;
class function GetProjYears: TStringList;
end;
implementation
{$R *.dfm}
class procedure TfrmProjYear.ShowForm;
var
frmProjYear: TfrmProjYear;
begin
frmProjYear := TfrmProjYear.Create(nil);
try
frmProjYear.ShowModal;
finally
frmProjYear.Free;
end;
end;
class function TfrmProjYear.GetProjYears: TStringList;
var
ini: TIniFile;
begin
Result := TStringList.Create;
ini := TIniFile.Create(AppIni);
try
ini.ReadSectionValues('frmProjYear', Result);
finally
ini.Free;
end;
end;
procedure TfrmProjYear.btnOkClick(Sender: TObject);
var
ini: TIniFile;
iline: Integer;
begin
ini := TIniFile.Create(AppIni);
try
ini.EraseSection(self.Name);
for iline := 0 to Memo1.Lines.Count - 1 do
begin
ini.WriteString(self.Name, Memo1.Lines.Names[iline], Memo1.Lines.ValueFromIndex[iline]);
end;
finally
ini.Free;
end;
Close;
end;
procedure TfrmProjYear.btnCancelClick(Sender: TObject);
begin
Close;
end;
procedure TfrmProjYear.FormCreate(Sender: TObject);
var
ini: TIniFile;
begin
Memo1.Clear;
ini := TIniFile.Create(AppIni);
try
ini.ReadSectionValues(Self.Name, Memo1.Lines);
finally
ini.Free;
end;
end;
end.
|
unit MainFrm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, DBGrids, StdCtrls, Buttons, Menus, UtilsUnit,Registry;
type
{ TMainForm }
TMainForm = class(TForm)
JvDBGrid1: TDBGrid;
FromDatabase: TEdit;
MainMenu1: TMainMenu;
File1: TMenuItem;
Label1: TLabel;
FromUserName: TEdit;
Label2: TLabel;
FromPassword: TEdit;
Label3: TLabel;
FromServerName: TEdit;
Label4: TLabel;
FromTable: TEdit;
Label5: TLabel;
JvBitBtn1: TBitBtn;
Label6: TLabel;
ToDatabase: TEdit;
Label7: TLabel;
ToUserName: TEdit;
Label8: TLabel;
ToPassword: TEdit;
Label9: TLabel;
ToServerName: TEdit;
JvDBGrid2: TDBGrid;
OutputLog: TMemo;
JvBitBtn3: TBitBtn;
BtnCompareRight: TBitBtn;
FromUniqueField: TEdit;
Label11: TLabel;
SQLEdit: TMemo;
Label10: TLabel;
SQL: TMemo;
Button1: TButton;
SaveDialog1: TSaveDialog;
Button2: TButton;
Button3: TButton;
About1: TMenuItem;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure About1Click(Sender: TObject);
procedure JvBitBtn1Click(Sender: TObject);
procedure BtnCompareRightClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
uses datafrm, AboutFrm;
{$R *.lfm}
procedure TMainForm.About1Click(Sender: TObject);
begin
Application.CreateForm(TAboutForm, AboutForm);
AboutForm.showmodal;
AboutForm.Free;
end;
procedure TMainForm.Button1Click(Sender: TObject);
begin
if Savedialog1.Execute then
begin
SQL.Lines.SaveToFile(SaveDialog1.FileName);
end;
end;
procedure TMainForm.Button2Click(Sender: TObject);
begin
if Savedialog1.Execute then
begin
Outputlog.Lines.SaveToFile(SaveDialog1.FileName);
end;
end;
procedure TMainForm.Button3Click(Sender: TObject);
begin
if MessageDlg('Are you sure you want to Run this it cannot be undone!',
mtConfirmation, [mbYes, mbNo], 0) = mrYes then
begin
Dataform.ToTransaction.Commit;
Dataform.ToTransaction.StartTransaction;
try
Dataform.ToQuery2.SQL.Clear;
Dataform.ToQuery2.SQL.Add(SQL.Lines.Text);
Dataform.ToQuery2.ExecSQL;
Dataform.ToQuery2.SQL.Clear;
Dataform.ToTransaction.Commit;
showmessage('Finished');
finally
if DataForm.ToTransaction.Active then
begin
Dataform.ToTransaction.Rollback;
showmessage('Something went wrong all changes were dropped!');
end
else
begin
Dataform.ToTransaction.StartTransaction;
end;
end;
end;
end;
procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Dataform.FromQuery1.Close;
Dataform.ToQuery1.Close;
Dataform.ToQuery2.Close;
SetRegistryData(HKEY_CURRENT_USER,
'\Software\CompareMSSQLTables\',
'FromDatabase', rdString, FromDatabase.Text);
SetRegistryData(HKEY_CURRENT_USER,
'\Software\CompareMSSQLTables\',
'FromUserName', rdString, FromUserName.Text);
SetRegistryData(HKEY_CURRENT_USER,
'\Software\CompareMSSQLTables\',
'FromPassword', rdString, encrypt(FromPassword.Text));
SetRegistryData(HKEY_CURRENT_USER,
'\Software\CompareMSSQLTables\',
'FromServerName', rdString, FromServerName.Text);
SetRegistryData(HKEY_CURRENT_USER,
'\Software\CompareMSSQLTables\',
'FromTable', rdString, FromTable.Text);
SetRegistryData(HKEY_CURRENT_USER,
'\Software\CompareMSSQLTables\',
'FromUniqueField', rdString, FromUniqueField.Text);
SetRegistryData(HKEY_CURRENT_USER,
'\Software\CompareMSSQLTables\',
'ToDatabase', rdString, ToDatabase.Text);
SetRegistryData(HKEY_CURRENT_USER,
'\Software\CompareMSSQLTables\',
'ToUserName', rdString, ToUserName.Text);
SetRegistryData(HKEY_CURRENT_USER,
'\Software\CompareMSSQLTables\',
'ToPassword', rdString, encrypt(ToPassword.Text));
SetRegistryData(HKEY_CURRENT_USER,
'\Software\CompareMSSQLTables\',
'ToServerName', rdString, ToServerName.Text);
SetRegistryData(HKEY_CURRENT_USER,
'\Software\CompareMSSQLTables\',
'SQLEdit', rdString, SQLEdit.Text);
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
try
FromDatabase.Text := GetRegistryData(HKEY_CURRENT_USER,'\Software\CompareMSSQLTables\','FromDatabase');
except
FromDatabase.Text := '';
end;
try
FromUserName.Text := GetRegistryData(HKEY_CURRENT_USER,'\Software\CompareMSSQLTables\','FromUserName');
except
FromUserName.Text := '';
end;
try
FromPassword.Text := Decrypt(GetRegistryData(HKEY_CURRENT_USER,'\Software\CompareMSSQLTables\','FromPassword'));
except
FromPassword.Text := '';
end;
try
FromServerName.Text := GetRegistryData(HKEY_CURRENT_USER,'\Software\CompareMSSQLTables\','FromServerName');
except
FromServerName.Text := '';
end;
try
FromTable.Text := GetRegistryData(HKEY_CURRENT_USER,'\Software\CompareMSSQLTables\','FromTable');
except
FromTable.Text := '';
end;
try
FromUniqueField.Text := GetRegistryData(HKEY_CURRENT_USER,'\Software\CompareMSSQLTables\','FromUniqueField');
except
FromUniqueField.Text := '';
end;
try
ToDatabase.Text := GetRegistryData(HKEY_CURRENT_USER,'\Software\CompareMSSQLTables\','ToDatabase');
except
ToDatabase.Text := '';
end;
try
ToUserName.Text := GetRegistryData(HKEY_CURRENT_USER,'\Software\CompareMSSQLTables\','ToUserName');
except
ToUserName.Text := '';
end;
try
ToPassword.Text := Decrypt(GetRegistryData(HKEY_CURRENT_USER,'\Software\CompareMSSQLTables\','ToPassword'));
except
ToPassword.Text := '';
end;
try
ToServerName.Text := GetRegistryData(HKEY_CURRENT_USER,'\Software\CompareMSSQLTables\','ToServerName');
except
ToServerName.Text := '';
end;
try
SQLEdit.Text := GetRegistryData(HKEY_CURRENT_USER,'\Software\CompareMSSQLTables\','SQLEdit');
except
SQLEdit.Text := '';
end;
end;
procedure TMainForm.JvBitBtn1Click(Sender: TObject);
begin
if POS(FromTable.Text,SQLEdit.Text) = 0 then
begin
showmessage('Table name must be present in Query');
exit;
end;
try
Dataform.FromConnection.Close;
Dataform.FromConnection.Params.Clear;
// Dataform.FromConnection.Params.Add('DriverID=MSSQL');
Dataform.FromConnection.DatabaseName := FromDatabase.Text;
Dataform.FromConnection.UserName := FromUserName.Text;
Dataform.FromConnection.Password := FromPassword.Text;
Dataform.FromConnection.HostName := FromServerName.Text;
Dataform.FromConnection.Open;
DataForm.FromQuery1.close;
with Dataform.FromQuery1.SQL do
begin
Clear;
Text := SQLEdit.Text;
end;
Dataform.FromQuery1.Open;
except
begin
ShowMessage('Unable to connect to MSSQL From Server, make sure the Database exist');
Dataform.FromConnection.Close;
end;
raise;
end;
try
Dataform.ToConnection.Close;
Dataform.ToConnection.Params.Clear;
Dataform.ToConnection.DatabaseName := ToDatabase.Text;
Dataform.ToConnection.UserName := ToUserName.Text;
Dataform.ToConnection.Password := ToPassword.Text;
Dataform.ToConnection.HostName := ToServerName.Text;
Dataform.ToConnection.Open;
DataForm.ToQuery1.close;
with Dataform.ToQuery1.SQL do
begin
Clear;
Text := SQLEdit.Text;
end;
Dataform.ToQuery1.Open;
except
begin
ShowMessage('Unable to connect to MSSQL To Server, make sure the Database exist');
Dataform.ToConnection.Close;
end;
raise;
end;
end;
procedure TMainForm.BtnCompareRightClick(Sender: TObject);
var
I:Integer;
s: String;
RecordChanged: Boolean;
FieldsString,ValuesString,QueryString:WideString;
begin
if Dataform.ToConnection.Connected = False then
begin
showmessage('Connect to SQL server first');
exit;
end;
Outputlog.Clear;
SQL.Clear;
FieldsString := '';
ValuesString := '';
OutputLog.Lines.Clear;
Dataform.FromQuery1.First;
Dataform.FromQuery1.DisableControls;
while not Dataform.FromQuery1.EOF do
begin
DataForm.ToQuery2.close;
with Dataform.ToQuery2.SQL do
begin
Clear;
Add('select * from ' + FromTable.Text);
Add('where ' + FROMUniquefield.Text + ' = ' + ConvertFieldtoSQLString(Dataform.FromQuery1.FieldByName(FromUniquefield.Text)));
end;
Dataform.ToQuery2.Open;
Dataform.ToQuery2.Prepare;
if Dataform.ToQuery2.RecordCount = 0 then
begin
OutputLog.Lines.Add('Insert ' + Dataform.FromQuery1.FieldByName(FromUniquefield.Text).asString);
for I := 0 to Dataform.FromQuery1.Fields.Count - 1 do
begin
if FieldsString = '' then
begin
FieldsString := DataForm.FromQuery1.Fields[I].FieldName;
ValuesString := ConvertFieldtoSQLString(DataForm.FromQuery1.Fields[I]);
end
else
begin
FieldsString := FieldsString + ',' + DataForm.FromQuery1.Fields[I].FieldName;
ValuesString := ValuesString + ',' + ConvertFieldtoSQLString(DataForm.FromQuery1.Fields[I]);
end;
end;
QueryString := 'insert into ' + FromTable.Text + ' (' + FieldsString + ') Values (' + ValuesString + ');';
SQL.Lines.Add(QueryString);
FieldsString := '';
ValuesString := '';
end
else
begin
s := 'Update ' + Dataform.FromQuery1.FieldByName(FromUniquefield.Text).asString;
RecordChanged := False;
for I := 0 to Dataform.FromQuery1.Fields.Count - 1 do
begin
if Dataform.ToQuery2.Fields[I].Value <> Dataform.FromQuery1.Fields[I].Value then
begin
// showmessage(InttoStr(I));
RecordChanged := True;
if FieldsString = '' then
FieldsString := DataForm.FromQuery1.Fields[I].FieldName + ' = ' + ConvertFieldtoSQLString(DataForm.FromQuery1.Fields[I])
else
FieldsString := FieldsString + ',' + DataForm.FromQuery1.Fields[I].FieldName + ' = ' + ConvertFieldtoSQLString(DataForm.FromQuery1.Fields[I]);
end;
end;
if RecordChanged = true then
begin
QueryString := 'update ' + FromTable.Text + ' set ' + FieldsString + ' where ' + FromUniqueField.Text + ' = ' + ConvertFieldtoSQLString(Dataform.FromQuery1.FieldByName(FromUniquefield.Text)) + ';';
SQL.Lines.Add(QueryString);
FieldsString := '';
OutputLog.Lines.Add(s);
end;
end;
Dataform.FromQuery1.Next;
end;
Dataform.FromQuery1.EnableControls;
dataform.ToQuery2.close;
showmessage('Finished');
end;
end.
|
unit ImportGroupItemsTest;
interface
uses dbTest, dbObjectTest, ObjectTest;
type
TImportGroupItemsTest = class (TdbObjectTestNew)
published
procedure ProcedureLoad; override;
procedure Test; override;
end;
TImportGroupItemsObjectTest = class(TObjectTest)
function InsertDefault: integer; override;
public
function InsertUpdateImportGroupItems(const Id, ImportSettingsId, ImportGroupId: integer): integer;
constructor Create; override;
end;
implementation
uses DB, UtilConst, TestFramework, SysUtils, ImportSettingsTest, ImportGroupTest;
{ TdbUnitTest }
procedure TImportGroupItemsTest.ProcedureLoad;
begin
ScriptDirectory := ProcedurePath + 'OBJECTS\ImportGroupItems\';
inherited;
end;
procedure TImportGroupItemsTest.Test;
var Id: integer;
RecordCount: Integer;
ObjectTest: TImportGroupItemsObjectTest;
begin
ObjectTest := TImportGroupItemsObjectTest.Create;
// Получим список
RecordCount := ObjectTest.GetDataSet.RecordCount;
// Вставка Типа импорта
Id := ObjectTest.InsertDefault;
try
// Получим список ролей
Check(ObjectTest.GetDataSet.RecordCount = (RecordCount + 1), 'Количество записей не изменилось');
finally
ObjectTest.Delete(Id);
end;
end;
{ TImportGroupItemsTest }
constructor TImportGroupItemsObjectTest.Create;
begin
inherited Create;
spInsertUpdate := 'gpInsertUpdate_Object_ImportGroupItems';
spSelect := 'gpSelect_Object_ImportGroupItems';
spGet := 'gpGet_Object_ImportGroupItems';
end;
function TImportGroupItemsObjectTest.InsertDefault: integer;
var vbImportSettingsId, vbImportGroupId: integer;
begin
vbImportSettingsId := TImportSettingsObjectTest.Create.GetDefault;
vbImportGroupId := TImportGroupObjectTest.Create.GetDefault;
result := InsertUpdateImportGroupItems(0, vbImportSettingsId, vbImportGroupId);
inherited;
end;
function TImportGroupItemsObjectTest.
InsertUpdateImportGroupItems(const Id, ImportSettingsId, ImportGroupId: integer): integer;
begin
FParams.Clear;
FParams.AddParam('ioId', ftInteger, ptInputOutput, Id);
FParams.AddParam('inImportSettingsId', ftInteger, ptInput, ImportSettingsId);
FParams.AddParam('inImportGroupId', ftInteger, ptInput, ImportGroupId);
result := InsertUpdate(FParams);
end;
initialization
// TestFramework.RegisterTest('Объекты', TImportGroupItemsTest.Suite);
end.
|
unit VideoDataReceiver;
interface
uses
Classes, RTDisplay, IdBaseComponent, SysUtils,
IdComponent, IdTCPConnection, IdTCPClient, SyncObjs;
type
TNewDataArriveEvent = procedure(sender : TObject; Ch1, Ch2 : pointer; Count : integer) of object;
TVideoDataReceiver = class(TThread)
private
DataReceiver : TIdTCPClient;
lock : THandle;
fDataType : integer;
fRays : integer;
fCells : integer;
fCodes : boolean;
fChannel : integer;
BufferSize : integer;
SentCells : integer;
ch1, ch2 : pointer;
fNewDataArriveEvent : TNewDataArriveEvent;
procedure PaintData();
procedure setCells(const Value: integer);
procedure setChannel(const Value: integer);
procedure setCodes(const Value: boolean);
procedure setDataType(const Value: integer);
procedure setRays(const Value: integer);
protected
procedure Execute; override;
public
constructor Create(Host : string; Port : integer; Channel, DataType, Rays, Cells : integer; Codes : boolean);
destructor Destroy; override;
property DataType : integer read fDataType write setDataType;
property Rays : integer read fRays write setRays;
property Cells : integer read fCells write setCells;
property Codes : boolean read fCodes write setCodes;
property Channel : integer read fChannel write setChannel;
property OnNewDataArriveEvent : TNewDataArriveEvent read fNewDataArriveEvent write fNewDataArriveEvent;
end;
implementation
uses
Windows, Shell_Client, Constants;
{ TVideoDataReceiver }
constructor TVideoDataReceiver.Create(Host : string; Port : integer; Channel, DataType, Rays, Cells : integer; Codes : boolean);
begin
inherited Create( True );
FreeOnTerminate := true;
Priority := tpHigher;
lock := CreateMutex(nil, false, 'VideoDataReceiver');
DataReceiver := TIdTCPClient.Create( nil );
DataReceiver.Port := Port;
DataReceiver.Host := Host;
DataReceiver.Connect(oscMaxTimeServerConnect);
self.DataType := DataType;
self.Rays := Rays;
self.Cells := Cells;
self.Codes := Codes;
self.Channel := Channel;
Resume;
end;
destructor TVideoDataReceiver.Destroy;
begin
if DataReceiver.Connected
then DataReceiver.Disconnect;
DataReceiver.Free;
inherited;
end;
procedure TVideoDataReceiver.Execute;
begin
while (not Terminated) do
begin
if WaitForSingleObject(lock, 1000) = WAIT_OBJECT_0
then
try
try
DataReceiver.WriteLn('ch' + IntToStr(fChannel));
SentCells := DataReceiver.ReadCardinal;
BufferSize := SentCells * sizeof(word);
case fChannel of
0 : begin
GetMem(ch1, BufferSize);
FillChar(ch1^, BufferSize, 0);
DataReceiver.ReadBuffer(ch1^, BufferSize);
end;
1 : begin
GetMem(ch2, BufferSize);
FillChar(ch2^, BufferSize, 0);
DataReceiver.ReadBuffer(ch2^, BufferSize);
end;
2 : begin
GetMem(ch1, BufferSize);
FillChar(ch1^, BufferSize, 0);
DataReceiver.ReadBuffer(ch1^, BufferSize);
GetMem(ch2, BufferSize);
FillChar(ch2^, BufferSize, 0);
DataReceiver.ReadBuffer(ch2^, BufferSize);
end;
end;
if SentCells = fCells
then
begin
Synchronize(PaintData);
if Assigned(fNewDataArriveEvent)
then fNewDataArriveEvent(self, ch1, ch2, BufferSize);
end;
Sleep(100);
finally
ReleaseMutex(lock);
end;
except
Terminate;
end;
end;
end;
procedure TVideoDataReceiver.PaintData;
begin
if(ch1 <> nil)
then
begin
ShellClient.Video.Video1.SetData1(ch1^);
FreeMem(ch1);
ch1 := nil;
end;
if(ch2 <> nil)
then
begin
ShellClient.Video.Video1.SetData2(ch2^);
FreeMem(ch2);
ch2 := nil;
end;
end;
procedure TVideoDataReceiver.setCells(const Value: integer);
var
result : string;
begin
if WaitForSingleObject(lock, 1000) = WAIT_OBJECT_0
then
try
DataReceiver.WriteLn(oscSetCellsCommand);
DataReceiver.WriteInteger(Value);
result := DataReceiver.ReadLn('', oscClientCommandTimeOut);
if result = oscSuccess
then fCells := Value;
finally
ReleaseMutex(lock);
end;
end;
procedure TVideoDataReceiver.setChannel(const Value: integer);
var
result : string;
begin
if WaitForSingleObject(lock, 1000) = WAIT_OBJECT_0
then
try
DataReceiver.WriteLn(oscSetChannelsCommand);
DataReceiver.WriteInteger(Value);
result := DataReceiver.ReadLn('', oscClientCommandTimeOut);
if result = oscSuccess
then fChannel := Value;
finally
ReleaseMutex(lock);
end;
end;
procedure TVideoDataReceiver.setCodes(const Value: boolean);
var
result : string;
begin
if WaitForSingleObject(lock, 1000) = WAIT_OBJECT_0
then
try
DataReceiver.WriteLn(oscSetCodesCommand);
DataReceiver.WriteInteger(Ord(Value));
result := DataReceiver.ReadLn('', oscClientCommandTimeOut);
if result = oscSuccess
then fCodes := Value;
finally
ReleaseMutex(lock);
end;
end;
procedure TVideoDataReceiver.setDataType(const Value: integer);
var
result : string;
begin
if WaitForSingleObject(lock, 1000) = WAIT_OBJECT_0
then
try
DataReceiver.WriteLn(oscSetDataTypeCommand);
DataReceiver.WriteInteger(Value);
result := DataReceiver.ReadLn('', oscClientCommandTimeOut);
if result = oscSuccess
then fDataType := Value;
finally
ReleaseMutex(lock);
end;
end;
procedure TVideoDataReceiver.setRays(const Value: integer);
var
result : string;
begin
if WaitForSingleObject(lock, 1000) = WAIT_OBJECT_0
then
try
DataReceiver.WriteLn(oscSetRaysCommand);
DataReceiver.WriteInteger(Value);
result := DataReceiver.ReadLn('', oscClientCommandTimeOut);
if result = oscSuccess
then fRays := Value;
finally
ReleaseMutex(lock);
end;
end;
end.
|
unit uConfigJuros;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uFormCadBase, ImgList, DB, ComCtrls, ToolWin, Grids, DBGrids, StdCtrls, JvExStdCtrls, JvCombobox, JvExControls, JvXPCore, JvXPButtons,
JvEdit, ConstTipos;
type
TfrmConfigJuros = class(TfrmCadBase)
chk_correcao: TCheckBox;
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure btn_PesquisarClick(Sender: TObject);
procedure chk_correcaoClick(Sender: TObject);
procedure cb_CampoChange(Sender: TObject);
procedure DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
procedure tbtn_IncluirClick(Sender: TObject);
procedure tbtn_AlterarClick(Sender: TObject);
procedure tbtn_ExcluirClick(Sender: TObject);
procedure tbtn_VisualizarClick(Sender: TObject);
procedure tbtn_ExcelClick(Sender: TObject);
procedure tbtn_ImprimirClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
function Incluir: Boolean;
function Alterar: Boolean;
procedure OpenConfigJuros;
{ Public declarations }
end;
var
frmConfigJuros: TfrmConfigJuros;
implementation
uses uDMPrincipal, ZDataset, uDMAction, uConfigJurosCad, uConfigJurosRel;
{$R *.dfm}
{ TfrmConfigJuros }
function TfrmConfigJuros.Alterar: Boolean;
begin
with DMPrincipal.qry_executaSQL do
begin
Active := False;
SQL.Clear;
SQL.Add('CALL sp_ConfigJuros_IU (:vOP, :vAnoLetivo, :vDiaInicial, :vDiaFinal, :vMulta, :vJuros, :vCorrecao)');
ParamByName('vOP').Value := 'U';
ParamByName('vAnoLetivo').Value := ds1.DataSet.FieldValues['AnoLetivo'];
ParamByName('vDiaInicial').Value := frmConfigJurosCad.edt_DiaInicial.Text;
ParamByName('vDiaFinal').Value := frmConfigJurosCad.edt_DiaFinal.Text;
ParamByName('vMulta').AsFloat := StrToFloat(frmConfigJurosCad.edt_Multa.Text);
ParamByName('vJuros').AsFloat := StrToFloat(frmConfigJurosCad.edt_Juros.Text);
if frmConfigJurosCad.chk_correcao.Checked then
ParamByName('vCorrecao').Value := 1
else
ParamByName('vCorrecao').Value := 0;
try
DMPrincipal.Zconn.StartTransaction;
ExecSQL;
except on E: Exception do
begin
Result := False;
DMPrincipal.Zconn.Rollback;
Application.MessageBox(PAnsiChar(e.Message + #13 +
'Erro ao Tentar Alterar este Registro!'
+ #13 +
'Entre em contato com o Suporte do Sistema!'), 'Atenção!',MB_ICONWARNING);
Exit;
end;
end;
DMPrincipal.Zconn.Commit;
Result := True;
end;
end;
procedure TfrmConfigJuros.btn_PesquisarClick(Sender: TObject);
var
comando : string;
begin
inherited;
comando := 'select * from ConfigJuros';
Pesquisar(DMPrincipal.qry_ConfigJuros,cb_Campo,comando,edt_Pesquisa.Text);
DMPrincipal.Espiao.RegistraLog(Self.Caption, btn_Pesquisar.Caption, cb_Campo.Text+' = '+edt_Pesquisa.Text);
end;
procedure TfrmConfigJuros.cb_CampoChange(Sender: TObject);
begin
inherited;
if cb_Campo.Text = 'Correção' then
begin
btn_Pesquisar.Enabled := False;
edt_Pesquisa.Visible := False;
chk_correcao.Visible := True;
end else
begin
btn_Pesquisar.Enabled := True;
edt_Pesquisa.Visible := True;
chk_correcao.Visible := False;
ds1.DataSet.Filtered := False;
end;
end;
procedure TfrmConfigJuros.chk_correcaoClick(Sender: TObject);
begin
inherited;
if chk_correcao.Checked then
begin
ds1.DataSet.Filtered := False;
ds1.DataSet.Filter := 'Correcao = 1';
ds1.DataSet.Filtered := True;
end else
begin
ds1.DataSet.Filtered := False;
ds1.DataSet.Filter := 'Correcao = 0';
ds1.DataSet.Filtered := True;
end;
end;
procedure TfrmConfigJuros.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
var
X, Y : Integer;
begin
if Column.FieldName = 'Correcao' then
begin
DBGrid1.Canvas.Pen.Color := DBGrid1.Canvas.Brush.Color;
DBGrid1.Canvas.Rectangle(Rect);
x := (Rect.Left + Rect.Right - DMPrincipal.imgLst.Width) div 2;
y := (Rect.Top + Rect.Bottom - DMPrincipal.imgLst.Height) div 2;
DMPrincipal.imgLst.Draw(DBGrid1.Canvas, x, y, 0);
if ds1.DataSet.FieldValues['Correcao'] = 1 then
DMPrincipal.imgLst.Draw(DBGrid1.Canvas, x, y, 1);
end;
end;
procedure TfrmConfigJuros.FormCreate(Sender: TObject);
begin
inherited;
ds1.DataSet := DMPrincipal.qry_ConfigJuros;
OpenConfigJuros;
PreencheCombo(cb_Campo);
end;
procedure TfrmConfigJuros.FormDestroy(Sender: TObject);
begin
inherited;
DMPrincipal.Espiao.RegistraLog(Self.Caption, tbtn_Fechar.Caption, 'Saiu');
end;
procedure TfrmConfigJuros.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
inherited;
if Key = VK_Return then
btn_PesquisarClick(Sender);
end;
function TfrmConfigJuros.Incluir: Boolean;
begin
with DMPrincipal.qry_executaSQL do
begin
Active := False;
SQL.Clear;
SQL.Add('CALL sp_ConfigJuros_IU (:vOP, :vAnoLetivo, :vDiaInicial, :vDiaFinal, :vMulta, :vJuros, :vCorrecao)');
ParamByName('vOP').Value := 'I';
ParamByName('vAnoLetivo').Value := vUser.AnoLetivo;
ParamByName('vDiaInicial').Value := frmConfigJurosCad.edt_DiaInicial.Text;
ParamByName('vDiaFinal').Value := frmConfigJurosCad.edt_DiaFinal.Text;
ParamByName('vMulta').AsFloat := StrToFloat(frmConfigJurosCad.edt_Multa.Text);
ParamByName('vJuros').AsFloat := StrToFloat(frmConfigJurosCad.edt_Juros.Text);
if frmConfigJurosCad.chk_correcao.Checked then
ParamByName('vCorrecao').Value := 1
else
ParamByName('vCorrecao').Value := 0;
try
DMPrincipal.Zconn.StartTransaction;
ExecSQL;
except on E: Exception do
begin
Result := False;
DMPrincipal.Zconn.Rollback;
Application.MessageBox(PAnsiChar(e.Message + #13 +
'Erro ao Tentar Incluir este Registro!'
+ #13 +
'Entre em contato com o Suporte do Sistema!'), 'Atenção!',MB_ICONWARNING);
Exit;
end;
end;
DMPrincipal.Zconn.Commit;
Result := True;
end;
end;
procedure TfrmConfigJuros.OpenConfigJuros;
begin
with DMPrincipal.qry_ConfigJuros do
begin
Close;
SQL.Clear;
SQL.Add('SELECT * FROM ConfigJuros');
Open;
end;
end;
procedure TfrmConfigJuros.tbtn_AlterarClick(Sender: TObject);
var
ponto : TBookmark;
begin
inherited;
ds1.DataSet.DisableControls;
ponto := ds1.DataSet.GetBookmark;
Application.CreateForm(TfrmConfigJurosCad, frmConfigJurosCad);
try
frmConfigJurosCad.Operacao := opAlterar;
frmConfigJurosCad.ShowModal;
if frmConfigJurosCad.ModalResult = mrOk then
begin
DMPrincipal.Espiao.Esp_AlteracaoGuarda(Self.Caption, ds1.DataSet);
Alterar;
OpenConfigJuros;
ds1.DataSet.GotoBookmark(ponto);
DMPrincipal.Espiao.Esp_AlteracaoVerifica( Self.Caption,'AnoLetivo;DiaInicial', ds1.DataSet,[ds1.DataSet.FieldByName('AnoLetivo').AsString,
ds1.DataSet.FieldByName('DiaInicial').AsString]);
end;
finally
ds1.DataSet.EnableControls;
ds1.DataSet.FreeBookMark(ponto);
FreeAndNil(frmConfigJurosCad);
end;
end;
procedure TfrmConfigJuros.tbtn_ExcelClick(Sender: TObject);
begin
inherited;
DMPrincipal.Espiao.RegistraLog(Self.Caption, tbtn_Excel.Caption, '');
end;
procedure TfrmConfigJuros.tbtn_ExcluirClick(Sender: TObject);
begin
inherited;
if Application.MessageBox('Deseja realmente Excluir?', 'Exclusão!', MB_YESNO + MB_ICONQUESTION) = ID_YES then
begin
ExcluirRegistro(DMPrincipal.Zconn, DMPrincipal.qry_sp_Delete, ds1.DataSet,'ConfigJuros','DiaInicial','DiaInicial');
DMPrincipal.Espiao.Esp_IncExc(Self.Caption, tbtn_Excluir.Caption, ds1.DataSet, ['AnoLetivo', 'DiaInicial', 'DiaFinal', 'Multa', 'Juros', 'Correcao']);
end;
OpenConfigJuros;
end;
procedure TfrmConfigJuros.tbtn_ImprimirClick(Sender: TObject);
begin
inherited;
Try
Application.CreateForm(TqRelConfigJuros,qRelConfigJuros);
qRelConfigJuros.ShowModal;
DMPrincipal.Espiao.RegistraLog(Self.Caption, tbtn_Imprimir.Caption, 'Imprimir');
finally
freeAndNil(qRelConfigJuros);
end;
end;
procedure TfrmConfigJuros.tbtn_IncluirClick(Sender: TObject);
begin
inherited;
Application.CreateForm(TfrmConfigJurosCad, frmConfigJurosCad);
try
frmConfigJurosCad.Operacao := opIncluir;
frmConfigJurosCad.ShowModal;
if frmConfigJurosCad.ModalResult = mrOk then
begin
Incluir;
OpenConfigJuros;
ds1.DataSet.Last;
DMPrincipal.Espiao.Esp_IncExc(Self.Caption, tbtn_Incluir.Caption,ds1.DataSet,['AnoLetivo','DiaInicial','DiaFinal','Multa','Juros','Correcao']);
end;
finally
FreeAndNil(frmConfigJurosCad);
end;
end;
procedure TfrmConfigJuros.tbtn_VisualizarClick(Sender: TObject);
begin
inherited;
ds1.DataSet.DisableControls;
Application.CreateForm(TfrmConfigJurosCad, frmConfigJurosCad);
try
frmConfigJurosCad.Operacao := opVisualizar;
frmConfigJurosCad.ShowModal;
DMPrincipal.Espiao.RegistraLog(Self.Caption, tbtn_Visualizar.Caption, 'AnoLetivo: '+ds1.DataSet.FieldValues['AnoLetivo']);
finally
ds1.DataSet.EnableControls;
FreeAndNil(frmConfigJurosCad);
end;
end;
end.
|
unit mainu;
{
This program was created to help show you how to display 3D models without using DirectX, OpenGl...
but instead just your own code.
Feel free to change anything you want.
You might try adding different types of shapes to the model like cubes, pyramids, cylinders...
My email address is greijos@hotmail.com
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TForm1 = class(TForm)
ScrollBar1: TScrollBar;
ScrollBar2: TScrollBar;
Button1: TButton;
Button2: TButton;
ScrollBar3: TScrollBar;
procedure FormCreate(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure ScrollBar1Change(Sender: TObject);
procedure ScrollBar2Change(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure ScrollBar3Change(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
tpoint3d = record
x,y,z: real;
end;
TLine = record
p1,p2: tpoint3d; // coordinates of the 2 points on the ends of the line segment
end;
var
Form1: TForm1;
lines: array of TLine; // all the lines in a 3D wireframe model
mv: integer; // the vertical middle
mh: integer; // the horizontal middle
h,v: real; // the angles
cosh,sinh,cosv,sinv: real;
// precalculated trig values for xyztox and xyztoy functions
sz: real; // magnification
implementation
{$R *.DFM}
function xyztox(x,y,z: real): integer;
begin
result:=mh+round((x*cosh+z*sinh)*sz);
end;
function xyztoy(x,y,z: real): integer;
begin
result:=mv+round(sz*(y*cosv+(-x*sinh+z*cosh)*sinv));
end;
{ the above 2 functions were created with math related to the projection of a point in space onto a 2D graph.
It is quite difficult to explain the math but I have created a program to help illustrate how the math works.
If you want to get this illustration program or have any specific questions, contact me about it.
}
procedure UpdateDisplay;
var
bit1: tbitmap;
x: integer;
begin
// start by updating the settings for drawing the display
mv:=form1.clientheight shr 1; // same as div 2
mh:=form1.clientwidth shr 1;
cosh:=cos(h);
sinh:=sin(h);
cosv:=cos(v);
sinv:=sin(v);
// settings now updated
bit1:=tbitmap.create;
bit1.height:=form1.clientheight;
bit1.width:=form1.clientwidth;
// now the dimensions of the bitmap are updated
for x:=high(lines) downto 0 do
with bit1.canvas do
begin
moveto(xyztox(lines[x].p1.x,lines[x].p1.y,lines[x].p1.z),xyztoy(lines[x].p1.x,lines[x].p1.y,lines[x].p1.z));
lineto(xyztox(lines[x].p2.x,lines[x].p2.y,lines[x].p2.z),xyztoy(lines[x].p2.x,lines[x].p2.y,lines[x].p2.z));
end;
form1.canvas.draw(0,0,bit1); // draw the bitmap on the form to show the user the update
bit1.free;
// free the bitmap so it doesn't waste memory
end;
procedure Addline(ln1: TLine);
begin
SetLength(lines,high(lines)+2);
lines[high(lines)]:=ln1;
end;
procedure AddSphere(r: real; c: tpoint3d);
// r = the radius of the sphere
// c = the centre point of the sphere
var
ln1: tline;
x,y: integer;
lat,long: real;
cr: real; // the radius of a circle inside the sphere
begin
for y:=-3 to 3 do // draw lines in circles parallel to the equator
begin
lat:=y*pi/6;
ln1.p1.y:=r*sin(lat)+c.y;
ln1.p2.y:=ln1.p1.y;
// calculated the y coordinate of a circle in the sphere
for x:=0 to 12 do
begin
long:=x*pi/6;
cr:=r*cos(lat);
ln1.p1:=ln1.p2;
ln1.p2.x:=cr*cos(long)+c.x;
ln1.p2.z:=cr*sin(long)+c.z;
if x<>0 then
Addline(ln1);
end;
end;
for x:=0 to 12 do // reverse the wire pattern so it looks like a grid
// draw the pattern parallel to the meridians
begin
long:=x*pi/6;
for y:=-3 to 3 do
begin
lat:=y*pi/6;
ln1.p1:=ln1.p2;
cr:=r*cos(lat);
ln1.p2.x:=cr*cos(long)+c.x;
ln1.p2.z:=cr*sin(long)+c.z;
ln1.p2.y:=r*sin(lat)+c.y;
// calculated the y coordinate of a circle in the sphere
if y<>-3 then
Addline(ln1);
end;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
randomize; // generate a random seed so the random function won't keep returning the same results.
sz:=1;
h:=scrollbar1.position*pi/180;
v:=scrollbar2.position*pi/180;
// set initial values
end;
procedure TForm1.FormPaint(Sender: TObject);
begin
UpdateDisplay;
end;
procedure TForm1.ScrollBar1Change(Sender: TObject);
begin // update the horizontal rotation angle
h:=scrollbar1.position*pi/180;
updatedisplay;
end;
procedure TForm1.ScrollBar2Change(Sender: TObject);
begin // update the vertical rotation angle
v:=scrollbar2.position*pi/180;
updatedisplay;
end;
procedure TForm1.Button1Click(Sender: TObject);
var // create a random sphere
c: tpoint3d;
begin
c.x:=random(300-150);
c.y:=random(300-150);
c.z:=random(300-150);
AddSphere(random(50),c); // add the sphere to the model
updatedisplay; // show the changes to the model
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
lines:=nil; // clear all of the information out of the lines array
updatedisplay; // show the changes to the model
end;
procedure TForm1.ScrollBar3Change(Sender: TObject);
begin // update the magnification of the model
sz:=scrollbar3.position/20;
updatedisplay;
end;
end.
|
unit TSTOProjectWorkSpace.IO;
interface
Uses Windows, Classes, HsStreamEx, HsInterfaceEx,
TSTOProjectWorkSpaceIntf, TSTOScriptTemplate.IO, TSTOHackSettings;
Type
ITSTOWorkSpaceProjectSrcFilesIO = Interface(ITSTOWorkSpaceProjectSrcFiles)
['{4B61686E-29A0-2112-83D8-AF14FA400832}']
Function Remove(Const Item : ITSTOWorkSpaceProjectSrcFile) : Integer;
Function GetOnChange() : TNotifyEvent;
Procedure SetOnChange(AOnChange : TNotifyEvent);
Property OnChange : TNotifyEvent Read GetOnChange Write SetOnChange;
End;
ITSTOWorkSpaceProjectSrcFolderIO = Interface(ITSTOWorkSpaceProjectSrcFolder)
['{4B61686E-29A0-2112-9A95-856C256092DA}']
Function GetOnChange() : TNotifyEvent;
Procedure SetOnChange(AOnChange : TNotifyEvent);
Property OnChange : TNotifyEvent Read GetOnChange Write SetOnChange;
End;
ITSTOWorkSpaceProjectSrcFoldersIO = Interface(ITSTOWorkSpaceProjectSrcFolders)
['{4B61686E-29A0-2112-B4BD-C15FECA88CC7}']
Function GetOnChange() : TNotifyEvent;
Procedure SetOnChange(AOnChange : TNotifyEvent);
Function Get(Index : Integer) : ITSTOWorkSpaceProjectSrcFolderIO;
Procedure Put(Index : Integer; Const Item : ITSTOWorkSpaceProjectSrcFolderIO);
Function Add() : ITSTOWorkSpaceProjectSrcFolderIO; OverLoad;
Function Add(Const AItem : ITSTOWorkSpaceProjectSrcFolderIO) : Integer; OverLoad;
Property Items[Index : Integer] : ITSTOWorkSpaceProjectSrcFolderIO Read Get Write Put; Default;
Property OnChange : TNotifyEvent Read GetOnChange Write SetOnChange;
End;
ITSTOWorkSpaceProjectGroupIO = Interface;
ITSTOWorkSpaceProjectIO = Interface(ITSTOWorkSpaceProject)
['{4B61686E-29A0-2112-84E7-E72095D7D3D9}']
Function GetWorkSpace() : ITSTOWorkSpaceProjectGroupIO;
Function GetGlobalSettings() : ITSTOHackSettings;
Function GetSrcPath() : String;
Function GetOnChange() : TNotifyEvent;
Procedure SetOnChange(AOnChange : TNotifyEvent);
Property WorkSpace : ITSTOWorkSpaceProjectGroupIO Read GetWorkSpace;
Property GlobalSettings : ITSTOHackSettings Read GetGlobalSettings;
Property SrcPath : String Read GetSrcPath;
Property OnChange : TNotifyEvent Read GetOnChange Write SetOnChange;
End;
ITSTOWorkSpaceProjectGroupIO = Interface(ITSTOWorkSpaceProjectGroup)
['{4B61686E-29A0-2112-A7E7-81D654C5F3FD}']
Function GetFileName() : String;
Function GetAsXml() : String;
Procedure SetAsXml(Const AXmlString : String);
Function GetHackSettings() : ITSTOHackSettings;
Function Get(Index : Integer) : ITSTOWorkSpaceProjectIO;
Procedure Put(Index : Integer; Const Item : ITSTOWorkSpaceProjectIO);
Function Add() : ITSTOWorkSpaceProjectIO; OverLoad;
Function Add(Const AItem : ITSTOWorkSpaceProjectIO) : Integer; OverLoad;
Function GetModified() : Boolean;
Function GetOnChange() : TNotifyEvent;
Procedure SetOnChange(AOnChange : TNotifyEvent);
Procedure LoadFromStream(ASource : IStreamEx);
Procedure LoadFromFile(Const AFileName : String);
Procedure SaveToStream(ATarget : IStreamEx);
Procedure SaveToFile(Const AFileName : String);
Procedure ForceChanged();
Procedure CreateWsGroupProject(APath : String; Const AHackFileName : String);
Procedure CreateWsProject(APath : String; AProject : ITSTOWorkSpaceProjectIO);
Procedure GenerateScripts(AProject : ITSTOWorkSpaceProjectIO);
Procedure CompileMod(AWorkSpaceProject : ITSTOWorkSpaceProjectIO);
Procedure PackMod(AWorkSpaceProject : ITSTOWorkSpaceProjectIO);
Property FileName : String Read GetFileName;
Property AsXml : String Read GetAsXml Write SetAsXml;
Property HackSettings : ITSTOHackSettings Read GetHackSettings;
Property Items[Index : Integer] : ITSTOWorkSpaceProjectIO Read Get Write Put; Default;
Property Modified : Boolean Read GetModified;
Property OnChange : TNotifyEvent Read GetOnChange Write SetOnChange;
End;
TTSTOWorkSpaceProjectGroupIO = Class(TObject)
Public
Class Function CreateProjectGroup() : ITSTOWorkSpaceProjectGroupIO;
End;
implementation
Uses
Forms, SysUtils,
HsXmlDocEx, HsZipUtils, HsCheckSumEx, HsStringListEx, HsFunctionsEx,
TSTOZero.Bin, TSTOProjectWorkSpaceImpl, TSTOProjectWorkSpace.Types,
TSTOProjectWorkSpace.Bin, TSTOProjectWorkSpace.Xml;
Type
ITSTOWorkSpaceProjectIOEx = Interface(ITSTOWorkSpaceProjectIO)
['{4B61686E-29A0-2112-84E7-E72095D7D3D9}']
Procedure SetWorkSpace(AWorkSpace : ITSTOWorkSpaceProjectGroupIO);
Property WorkSpace : ITSTOWorkSpaceProjectGroupIO Read GetWorkSpace Write SetWorkSpace;
End;
TTSTOWorkSpaceProjectSrcFilesIO = Class(TTSTOWorkSpaceProjectSrcFiles, ITSTOWorkSpaceProjectSrcFilesIO)
Private
FOnChange : TNotifyEvent;
Protected
Function Remove(Const Item : ITSTOWorkSpaceProjectSrcFile) : Integer;
Procedure DoChanged(Sender : TObject);
Function GetOnChange() : TNotifyEvent;
Procedure SetOnChange(AOnChange : TNotifyEvent);
End;
TTSTOWorkSpaceProjectSrcFolderIO = Class(TTSTOWorkSpaceProjectSrcFolder, ITSTOWorkSpaceProjectSrcFolderIO)
Protected
Function GetOnChange() : TNotifyEvent; Virtual; Abstract;
Procedure SetOnChange(AOnChange : TNotifyEvent); Virtual; Abstract;
End;
TTSTOWorkSpaceProjectSrcFoldersIO = Class(TTSTOWorkSpaceProjectSrcFolders, ITSTOWorkSpaceProjectSrcFoldersIO)
Private
FOnChange : TNotifyEvent;
Protected
Function GetItemClass() : TInterfacedObjectExClass; OverRide;
Function Get(Index : Integer) : ITSTOWorkSpaceProjectSrcFolderIO; OverLoad;
Procedure Put(Index : Integer; Const Item : ITSTOWorkSpaceProjectSrcFolderIO); OverLoad;
Function Add() : ITSTOWorkSpaceProjectSrcFolderIO; OverLoad;
Function Add(Const AItem : ITSTOWorkSpaceProjectSrcFolderIO) : Integer; OverLoad;
Procedure DoChange(Sender : TObject);
Function GetOnChange() : TNotifyEvent;
Procedure SetOnChange(AOnChange : TNotifyEvent);
End;
TTSTOWorkSpaceProjectIO = Class(TTSTOWorkSpaceProject, ITSTOWorkSpaceProjectIO, ITSTOWorkSpaceProjectIOEx)
Private
FOnChange : TNotifyEvent;
FWorkSpace : Pointer;
Protected
Function GetWorkSpaceProjectSrcFoldersClass() : TTSTOWorkSpaceProjectSrcFoldersClass; OverRide;
Function GetWorkSpace() : ITSTOWorkSpaceProjectGroupIO;
Procedure SetWorkSpace(AWorkSpace : ITSTOWorkSpaceProjectGroupIO);
Function GetSrcPath() : String;
Function GetGlobalSettings() : ITSTOHackSettings;
Function GetOnChange() : TNotifyEvent;
Procedure SetOnChange(AOnChange : TNotifyEvent);
Procedure SetProjectName(Const AProjectName : AnsiString); OverRide;
Procedure SetProjectKind(Const AProjectKind : TWorkSpaceProjectKind); OverRide;
Procedure SetProjectType(Const AProjectType : TWorkSpaceProjectType); OverRide;
Procedure SetZeroCrc32(Const AZeroCrc32 : DWord); OverRide;
Procedure SetPackOutput(Const APackOutput : Boolean); OverRide;
Procedure SetOutputPath(Const AOutputPath : AnsiString); OverRide;
Procedure SetCustomScriptPath(Const ACustomScriptPath : AnsiString); OverRide;
Procedure SetCustomModPath(Const ACustomModPath : AnsiString); OverRide;
Public
Constructor Create(AWorkSpace : ITSTOWorkSpaceProjectGroupIO); ReIntroduce;
End;
TTSTOWorkSpaceProjectGroupIOImpl = Class(TTSTOWorkSpaceProjectGroup,
ITSTOWorkSpaceProjectGroupIO, IBinTSTOWorkSpaceProjectGroup, IXmlTSTOWorkSpaceProjectGroup)
Private
FFileName : String;
FHackSettings : ITSTOHackSettings;
FOnChange : TNotifyEvent;
FModified : Boolean;
FBinImpl : IBinTSTOWorkSpaceProjectGroup;
FXmlImpl : IXmlTSTOWorkSpaceProjectGroup;
Function GetBinImplementor() : IBinTSTOWorkSpaceProjectGroup;
Function GetXmlImplementor() : IXmlTSTOWorkSpaceProjectGroup;
Protected
Property BinImpl : IBinTSTOWorkSpaceProjectGroup Read GetBinImplementor Implements IBinTSTOWorkSpaceProjectGroup;
Property XmlImpl : IXmlTSTOWorkSpaceProjectGroup Read GetXmlImplementor Implements IXmlTSTOWorkSpaceProjectGroup;
Function GetFileName() : String;
Function GetItemClass() : TInterfacedObjectExClass; OverRide;
Function Get(Index : Integer) : ITSTOWorkSpaceProjectIO; OverLoad;
Procedure Put(Index : Integer; Const Item : ITSTOWorkSpaceProjectIO); OverLoad;
Function Add() : ITSTOWorkSpaceProjectIO; OverLoad;
Function Add(Const AItem : ITSTOWorkSpaceProjectIO) : Integer; OverLoad;
Function GetAsXml() : String;
Procedure SetAsXml(Const AXmlString : String);
Procedure SetProjectGroupName(Const AProjectGroupName : AnsiString); OverRide;
Procedure SetHackFileName(Const AHackFileName : AnsiString); OverRide;
Procedure SetPackOutput(Const APackOutput : Boolean); OverRide;
Procedure SetOutputPath(Const AOutputPath : AnsiString); OverRide;
Function GetHackSettings() : ITSTOHackSettings;
Function GetModified() : Boolean;
Procedure DoOnChange(Sender : TObject);
Function GetOnChange() : TNotifyEvent;
Procedure SetOnChange(AOnChange : TNotifyEvent);
Procedure LoadFromStream(ASource : IStreamEx);
Procedure LoadFromFile(Const AFileName : String);
Procedure SaveToStream(ATarget : IStreamEx);
Procedure SaveToFile(Const AFileName : String);
Procedure ForceChanged();
Procedure CreateWsProject(APath : String; AProject : ITSTOWorkSpaceProjectIO);
Procedure CreateWsGroupProject(APath : String; Const AHackFileName : String);
Procedure GenerateScripts(AProject : ITSTOWorkSpaceProjectIO);
Procedure CompileMod(AWorkSpaceProject : ITSTOWorkSpaceProjectIO);
Procedure PackMod(AWorkSpaceProject : ITSTOWorkSpaceProjectIO);
Public
Procedure AfterConstruction(); OverRide;
Procedure BeforeDestruction(); OverRide;
End;
Class Function TTSTOWorkSpaceProjectGroupIO.CreateProjectGroup() : ITSTOWorkSpaceProjectGroupIO;
Begin
Result := TTSTOWorkSpaceProjectGroupIOImpl.Create();
End;
(******************************************************************************)
Function TTSTOWorkSpaceProjectSrcFilesIO.Remove(Const Item : ITSTOWorkSpaceProjectSrcFile) : Integer;
Begin
InHerited Remove(Item As IInterfaceEx);
DoChanged(Self);
End;
Procedure TTSTOWorkSpaceProjectSrcFilesIO.DoChanged(Sender : TObject);
Begin
If Assigned(FOnChange) Then
FOnChange(Sender);
End;
Function TTSTOWorkSpaceProjectSrcFilesIO.GetOnChange() : TNotifyEvent;
Begin
Result := FOnChange;
End;
Procedure TTSTOWorkSpaceProjectSrcFilesIO.SetOnChange(AOnChange : TNotifyEvent);
Begin
FOnChange := AOnChange;
End;
Function TTSTOWorkSpaceProjectSrcFoldersIO.GetItemClass() : TInterfacedObjectExClass;
Begin
Result := TTSTOWorkSpaceProjectSrcFolderIO;
End;
Function TTSTOWorkSpaceProjectSrcFoldersIO.Get(Index : Integer) : ITSTOWorkSpaceProjectSrcFolderIO;
Begin
Result := InHerited Get(Index) As ITSTOWorkSpaceProjectSrcFolderIO;
End;
Procedure TTSTOWorkSpaceProjectSrcFoldersIO.Put(Index : Integer; Const Item : ITSTOWorkSpaceProjectSrcFolderIO);
Begin
InHerited Put(Index, Item);
End;
Function TTSTOWorkSpaceProjectSrcFoldersIO.Add() : ITSTOWorkSpaceProjectSrcFolderIO;
Begin
Result := InHerited Add() As ITSTOWorkSpaceProjectSrcFolderIO;
Result.OnChange := DoChange;
End;
Function TTSTOWorkSpaceProjectSrcFoldersIO.Add(Const AItem : ITSTOWorkSpaceProjectSrcFolderIO) : Integer;
Begin
Result := InHerited Add(AItem);
AItem.OnChange := DoChange;
End;
Procedure TTSTOWorkSpaceProjectSrcFoldersIO.DoChange(Sender : TObject);
Begin
If Assigned(FOnChange) Then
FOnChange(Sender);
End;
Function TTSTOWorkSpaceProjectSrcFoldersIO.GetOnChange() : TNotifyEvent;
Begin
Result := FOnChange;
End;
Procedure TTSTOWorkSpaceProjectSrcFoldersIO.SetOnChange(AOnChange : TNotifyEvent);
Begin
FOnChange := AOnChange;
End;
Constructor TTSTOWorkSpaceProjectIO.Create(AWorkSpace : ITSTOWorkSpaceProjectGroupIO);
Begin
InHerited Create(True);
FWorkSpace := Pointer(AWorkSpace);
End;
Function TTSTOWorkSpaceProjectIO.GetWorkSpace() : ITSTOWorkSpaceProjectGroupIO;
Begin
Result := ITSTOWorkSpaceProjectGroupIO(FWorkSpace);
End;
Procedure TTSTOWorkSpaceProjectIO.SetWorkSpace(AWorkSpace : ITSTOWorkSpaceProjectGroupIO);
Begin
FWorkSpace := Pointer(AWorkSpace);
End;
Function TTSTOWorkSpaceProjectIO.GetSrcPath() : String;
Begin
If CustomModPath = '' Then
Raise Exception.Create('You must configure Custom mod path in project settings');
Result := ExtractFilePath(ExcludeTrailingBackslash(CustomModPath)) + '0\';
End;
Function TTSTOWorkSpaceProjectIO.GetGlobalSettings() : ITSTOHackSettings;
Begin
Result := GetWorkSpace().HackSettings;
End;
Function TTSTOWorkSpaceProjectIO.GetWorkSpaceProjectSrcFoldersClass() : TTSTOWorkSpaceProjectSrcFoldersClass;
Begin
Result := TTSTOWorkSpaceProjectSrcFoldersIO;
End;
Function TTSTOWorkSpaceProjectIO.GetOnChange() : TNotifyEvent;
Begin
Result := FOnChange;
End;
Procedure TTSTOWorkSpaceProjectIO.SetOnChange(AOnChange : TNotifyEvent);
Begin
FOnChange := AOnChange;
End;
Procedure TTSTOWorkSpaceProjectIO.SetProjectName(Const AProjectName : AnsiString);
Begin
If GetProjectName() <> AProjectName Then
Begin
InHerited SetProjectName(AProjectName);
If Assigned(FOnChange) Then
FOnChange(Self);
End;
End;
Procedure TTSTOWorkSpaceProjectIO.SetProjectKind(Const AProjectKind : TWorkSpaceProjectKind);
Begin
If GetProjectKind() <> AProjectKind Then
Begin
InHerited SetProjectKind(AProjectKind);
If Assigned(FOnChange) Then
FOnChange(Self);
End;
End;
Procedure TTSTOWorkSpaceProjectIO.SetProjectType(Const AProjectType : TWorkSpaceProjectType);
Begin
If GetProjectType() <> AProjectType Then
Begin
InHerited SetProjectType(AProjectType);
If Assigned(FOnChange) Then
FOnChange(Self);
End;
End;
Procedure TTSTOWorkSpaceProjectIO.SetZeroCrc32(Const AZeroCrc32 : DWord);
Begin
If GetZeroCrc32() <> AZeroCrc32 Then
Begin
InHerited SetZeroCrc32(AZeroCrc32);
If Assigned(FOnChange) Then
FOnChange(Self);
End;
End;
Procedure TTSTOWorkSpaceProjectIO.SetPackOutput(Const APackOutput : Boolean);
Begin
If GetPackOutput() <> APackOutput Then
Begin
InHerited SetPackOutput(APackOutput);
If Assigned(FOnChange) Then
FOnChange(Self);
End;
End;
Procedure TTSTOWorkSpaceProjectIO.SetOutputPath(Const AOutputPath : AnsiString);
Begin
If GetOutputPath() <> AOutputPath Then
Begin
InHerited SetOutputPath(AOutputPath);
If Assigned(FOnChange) Then
FOnChange(Self);
End;
End;
Procedure TTSTOWorkSpaceProjectIO.SetCustomScriptPath(Const ACustomScriptPath : AnsiString);
Begin
If GetCustomScriptPath() <> ACustomScriptPath Then
Begin
InHerited SetCustomScriptPath(ACustomScriptPath);
If Assigned(FOnChange) Then
FOnChange(Self);
End;
End;
Procedure TTSTOWorkSpaceProjectIO.SetCustomModPath(Const ACustomModPath : AnsiString);
Begin
If GetCustomModPath() <> ACustomModPath Then
Begin
InHerited SetCustomModPath(ACustomModPath);
If Assigned(FOnChange) Then
FOnChange(Self);
End;
End;
Procedure TTSTOWorkSpaceProjectGroupIOImpl.AfterConstruction();
Begin
FModified := False;
InHerited AfterConstruction();
End;
Procedure TTSTOWorkSpaceProjectGroupIOImpl.BeforeDestruction();
Begin
FBinImpl := Nil;
FXmlImpl := Nil;
FHackSettings := Nil;
InHerited BeforeDestruction();
End;
Function TTSTOWorkSpaceProjectGroupIOImpl.GetBinImplementor() : IBinTSTOWorkSpaceProjectGroup;
Begin
If Not Assigned(FBinImpl) Then
FBinImpl := TBinTSTOWorkSpaceProjectGroup.CreateWSProjectGroup();
FBinImpl.Assign(Self);
Result := FBinImpl;
End;
Function TTSTOWorkSpaceProjectGroupIOImpl.GetXmlImplementor() : IXmlTSTOWorkSpaceProjectGroup;
Begin
If Not Assigned(FXmlImpl) Then
FXmlImpl := TXmlTSTOWorkSpaceProjectGroup.CreateWSProjectGroup();
FXmlImpl.Assign(Self);
Result := FXmlImpl;
End;
Function TTSTOWorkSpaceProjectGroupIOImpl.GetItemClass() : TInterfacedObjectExClass;
Begin
Result := TTSTOWorkSpaceProjectIO;
End;
Function TTSTOWorkSpaceProjectGroupIOImpl.Get(Index : Integer) : ITSTOWorkSpaceProjectIO;
Begin
Result := InHerited Get(Index) As ITSTOWorkSpaceProjectIO;
End;
Procedure TTSTOWorkSpaceProjectGroupIOImpl.Put(Index : Integer; Const Item : ITSTOWorkSpaceProjectIO);
Begin
InHerited Add(Item);
End;
Function TTSTOWorkSpaceProjectGroupIOImpl.Add() : ITSTOWorkSpaceProjectIO;
Begin
Result := InHerited Add() As ITSTOWorkSpaceProjectIO;
(Result As ITSTOWorkSpaceProjectIOEx).WorkSpace := Self;
Result.OnChange := DoOnChange;
End;
Function TTSTOWorkSpaceProjectGroupIOImpl.Add(Const AItem : ITSTOWorkSpaceProjectIO) : Integer;
Begin
Result := InHerited Add(AItem);
(AItem As ITSTOWorkSpaceProjectIOEx).WorkSpace := Self;
AItem.OnChange := DoOnChange;
End;
Function TTSTOWorkSpaceProjectGroupIOImpl.GetFileName() : String;
Begin
Result := FFileName;
End;
Function TTSTOWorkSpaceProjectGroupIOImpl.GetAsXml() : String;
Begin
Result := FormatXmlData(XmlImpl.Xml);
FXmlImpl := Nil;
End;
Procedure TTSTOWorkSpaceProjectGroupIOImpl.SetAsXml(Const AXmlString : String);
Var X : Integer;
Begin
FXmlImpl := TXmlTSTOWorkSpaceProjectGroup.CreateWSProjectGroup(AXmlString);
Assign(FXmlImpl);
FXmlImpl := Nil;
For X := 0 To Count - 1 Do
With Get(X) As ITSTOWorkSpaceProjectIOEx Do
Begin
WorkSpace := Self;
OnChange := DoOnChange;
End;
End;
Procedure TTSTOWorkSpaceProjectGroupIOImpl.SetProjectGroupName(Const AProjectGroupName : AnsiString);
Begin
If GetProjectGroupName() <> AProjectGroupName Then
Begin
InHerited SetProjectGroupName(AProjectGroupName);
DoOnChange(Self);
End;
End;
Procedure TTSTOWorkSpaceProjectGroupIOImpl.SetHackFileName(Const AHackFileName : AnsiString);
Begin
If GetHackFileName() <> AHackFileName Then
Begin
InHerited SetHackFileName(AHackFileName);
DoOnChange(Self);
End;
End;
Procedure TTSTOWorkSpaceProjectGroupIOImpl.SetPackOutput(Const APackOutput : Boolean);
Begin
If GetPackOutput() <> APackOutput Then
Begin
InHerited SetPackOutput(APackOutput);
DoOnChange(Self);
End;
End;
Procedure TTSTOWorkSpaceProjectGroupIOImpl.SetOutputPath(Const AOutputPath : AnsiString);
Begin
If GetOutputPath() <> AOutputPath Then
Begin
InHerited SetOutputPath(AOutputPath);
DoOnChange(Self);
End;
End;
Function TTSTOWorkSpaceProjectGroupIOImpl.GetHackSettings() : ITSTOHackSettings;
Begin
If Not Assigned(FHackSettings) Then
Begin
FHackSettings := TTSTOHackSettings.CreateHackSettings();
If FileExists(HackFileName) Then
FHackSettings.LoadFromFile(HackFileName);
FHackSettings.OnChanged := DoOnChange;
End;
Result := FHackSettings;
End;
Function TTSTOWorkSpaceProjectGroupIOImpl.GetModified() : Boolean;
Begin
Result := FModified;
End;
Procedure TTSTOWorkSpaceProjectGroupIOImpl.ForceChanged();
Begin
DoOnChange(Self);
End;
Procedure TTSTOWorkSpaceProjectGroupIOImpl.DoOnChange(Sender : TObject);
Begin
If Assigned(FOnChange) Then
FOnChange(Sender);
FModified := True;
End;
Function TTSTOWorkSpaceProjectGroupIOImpl.GetOnChange() : TNotifyEvent;
Begin
Result := FOnChange;
End;
Procedure TTSTOWorkSpaceProjectGroupIOImpl.SetOnChange(AOnChange : TNotifyEvent);
Begin
FOnChange := AOnChange;
End;
Procedure TTSTOWorkSpaceProjectGroupIOImpl.LoadFromStream(ASource : IStreamEx);
Var X : Integer;
Begin
FBinImpl := TBinTSTOWorkSpaceProjectGroup.CreateWSProjectGroup();
FBinImpl.LoadFromStream(ASource);
Assign(FBinImpl);
For X := 0 To Count - 1 Do
With Get(X) As ITSTOWorkSpaceProjectIOEx Do
Begin
WorkSpace := Self;
OnChange := DoOnChange;
End;
FBinImpl := Nil;
End;
Procedure TTSTOWorkSpaceProjectGroupIOImpl.LoadFromFile(Const AFileName : String);
Var lMem : IMemoryStreamEx;
Begin
FFileName := AfileName;
If SameText(ExtractFileExt(AFileName), '.xml') Then
With TStringList.Create() Do
Try
LoadFromFile(AFileName);
SetAsXml(Text);
Finally
Free();
End
Else
Begin
lMem := TMemoryStreamEx.Create();
Try
lMem.LoadFromFile(AFileName);
lMem.Position := 0;
LoadFromStream(lMem);
Finally
lMem := Nil;
End;
End;
End;
Procedure TTSTOWorkSpaceProjectGroupIOImpl.SaveToStream(ATarget : IStreamEx);
Begin
BinImpl.SaveToStream(ATarget);
FBinImpl := Nil;
FModified := False;
End;
Procedure TTSTOWorkSpaceProjectGroupIOImpl.SaveToFile(Const AFileName : String);
Var lMem : IMemoryStreamEx;
Begin
If SameText(ExtractFileExt(AFileName), '.xml') Then
With TStringList.Create() Do
Try
Text := GetAsXml();
SaveToFile(AFileName);
Finally
Free();
End
Else
Begin
lMem := TMemoryStreamEx.Create();
Try
SaveToStream(lMem);
lMem.SaveToFile(AFileName);
Finally
lMem := Nil;
End;
End;
If Assigned(FHackSettings) Then
FHackSettings.SaveToFile();
FModified := False;
End;
Procedure TTSTOWorkSpaceProjectGroupIOImpl.CreateWsProject(APath : String; AProject : ITSTOWorkSpaceProjectIO);
Procedure RecursiveSearch(AStartPath : String; AProject : ITSTOWorkSpaceProjectIO);
Var lSr : TSearchRec;
lMem : IMemoryStreamEx;
Begin
AStartPath := IncludeTrailingBackslash(AStartPath);
If FindFirst(AStartPath + '*.*', faAnyFile, lSr) = 0 Then
Try
Repeat
If (lSr.Attr And faDirectory <> 0) Then
Begin
If SameText(ExtractFileExt(lSr.Name), '.Src') Then
Begin
AProject.SrcFolders.Add().SrcPath := IncludeTrailingBackslash(AStartPath + lSr.Name);
RecursiveSearch(IncludeTrailingBackslash(AStartPath + lSr.Name), AProject);
End;
End
Else If SameText(lSr.Name, 'ZeroCrc.hex') Then
Begin
lMem := TMemoryStreamEx.Create();
Try
lMem.LoadFromFile(APath + lSr.Name);
AProject.ZeroCrc32 := lMem.ReadDWord();
AProject.ProjectKind := spkRoot;
Finally
lMem := Nil;
End;
End
Else
AProject.SrcFolders[AProject.SrcFolders.Count - 1].Add(lSr.Name);
Until FindNext(lSr) <> 0
Finally
FindClose(lSr);
End;
End;
Begin
AProject.ProjectName := ExtractFileName(ExcludeTrailingBackslash(APath));
RecursiveSearch(APath, AProject);
End;
Procedure TTSTOWorkSpaceProjectGroupIOImpl.CreateWsGroupProject(APath : String; Const AHackFileName : String);
Var lSr : TSearchRec;
lProject : ITSTOWorkSpaceProjectIO;
Begin
Clear();
APath := IncludeTrailingBackslash(APath);
If FindFirst(APath + '*.*', faDirectory, lSr) = 0 Then
Try
ProjectGroupName := ExtractFileName(ExcludeTrailingBackslash(APath));
OutputPath := APath + 'Output\' + ProjectGroupName + '\%ProjectName%\';
HackFileName := AHackFileName;
Repeat
If (lSr.Attr And faDirectory <> 0) And Not SameText(lSr.Name, '.') And Not SameText(lSr.Name, '..') Then
Begin
lProject := Add();
lProject.ProjectName := lSr.Name;
lProject.CustomModPath := APath + lSr.Name + '\1.src';
If Pos(UpperCase(lSr.Name), 'TEXTPOOL') > 0 Then
lProject.ProjectType := sptTextPools
Else If Pos(UpperCase(lSr.Name), 'GAMESCRIPT') > 0 Then
lProject.ProjectType := sptScript;
CreateWsProject(APath + lSr.Name + '\', lProject);
End;
Until FindNext(lSr) <> 0
Finally
FindClose(lSr);
End;
End;
Procedure TTSTOWorkSpaceProjectGroupIOImpl.GenerateScripts(AProject : ITSTOWorkSpaceProjectIO);
Var lTemplate : ITSTOScriptTemplateHacksIO;
X, Y, Z : Integer;
lOutPath : String;
lCanAdd : Boolean;
lModified : Boolean;
Begin
lModified := False;
lTemplate := TTSTOScriptTemplateHacksIO.CreateScriptTemplateHacks();
Try
lTemplate.Assign(GetHackSettings().ScriptTemplates);
For X := 0 To lTemplate.Count - 1 Do
If lTemplate[X].Enabled Then
Begin
lOutPath := ExtractFilePath(lTemplate[X].Settings.OutputFileName);
If (lOutPath = '') Or Not DirectoryExists(lOutPath) Then
lTemplate[X].Settings.OutputFileName :=
AProject.CustomScriptPath +
ExtractFileName(lTemplate[X].Settings.OutputFileName);
If Not DirectoryExists(ExtractFilePath(lTemplate[X].Settings.OutputFileName)) Then
ForceDirectories(ExtractFilePath(lTemplate[X].Settings.OutputFileName));
End;
lTemplate.GenerateScripts(GetHackSettings().HackMasterList);
For X := 0 To lTemplate.Count - 1 Do
If lTemplate[X].Enabled Then
Begin
If FileExists(lTemplate[X].Settings.OutputFileName) Then
Begin
lOutPath := ExtractFilePath(lTemplate[X].Settings.OutputFileName);
For Y := 0 To AProject.SrcFolders.Count - 1 Do
If SameText( IncludeTrailingBackslash(AProject.SrcFolders[Y].SrcPath),
IncludeTrailingBackslash(lOutPath) ) Then
Begin
lCanAdd := True;
For Z := 0 To AProject.SrcFolders[Y].SrcFileCount - 1 Do
If SameText( ExtractFileName(lTemplate[X].Settings.OutputFileName),
AProject.SrcFolders[Y].SrcFiles[Z].FileName ) Then
Begin
lCanAdd := False;
Break;
End;
If lCanAdd Then
Begin
AProject.SrcFolders[Y].FileList.Add().FileName := ExtractFileName(lTemplate[X].Settings.OutputFileName);
lModified := True;
End;
Break;
End;
End;
End;
Finally
lTemplate := Nil;
End;
If lModified Then
DoOnChange(Self);
End;
Procedure TTSTOWorkSpaceProjectGroupIOImpl.CompileMod(AWorkSpaceProject : ITSTOWorkSpaceProjectIO);
Var lZips : IHsMemoryZippers;
lZip : IHsMemoryZipper;
X, Y, Z : Integer;
lPos : Integer;
lZero : IBinZeroFile;
lMem : IMemoryStreamEx;
lFileList : IHsStringListEx;
lOutPath : String;
Begin
lZips := THsMemoryZippers.Create();
Try
lZips.Clear();
lOutPath := AWorkSpaceProject.OutputPath;
If lOutPath = '' Then
lOutPath := AWorkSpaceProject.WorkSpace.OutputPath;
lOutPath := IncludeTrailingBackSlash(StringReplace(lOutPath, '%ProjectName%', AWorkSpaceProject.ProjectName, [rfReplaceAll, rfIgnoreCase]));
If Not DirectoryExists(lOutPath) Then
ForceDirectories(lOutPath);
For X := 0 To AWorkSpaceProject.SrcFolders.Count - 1 Do
Begin
lZip := lZips.Add();
lFileList := THsStringListEx.CreateList();
Try
For Y := 0 To AWorkSpaceProject.SrcFolders[X].SrcFileCount - 1 Do
With AWorkSpaceProject.SrcFolders[X] Do
If FileExists(IncludeTrailingBackslash(SrcPath) + SrcFiles[Y].FileName) Then
lFileList.Add(IncludeTrailingBackslash(SrcPath) + SrcFiles[Y].FileName);
lZip.AddFiles(lFileList, faAnyFile);
lZip.FileName := ChangeFileExt(ExtractFileName(ExcludeTrailingBackslash(AWorkSpaceProject.SrcFolders[X].SrcPath)), '');
TStream(lZip.InterfaceObject).Position := 0;
Finally
lFileList := Nil;
End;
End;
lZero := TBinZeroFile.CreateBinZeroFile();
Try
lZero.ArchiveDirectory := 'KahnAbyss/TSTO DLC Generator';
For Y := 0 To lZips.Count - 1 Do
Begin
With lZero.FileDatas.Add() Do
Begin
FileName := lZips[Y].FileName;
Crc32 := GetCrc32Value(TStream(lZips[Y].InterfaceObject));
For Z := 0 To lZips[Y].Count - 1 Do
With ArchivedFiles.Add() Do
Begin
FileName1 := lZips[Y][Z].FileName;
FileExtension := StringReplace(ExtractFileExt(lZips[Y][Z].FileName), '.', '', [rfReplaceAll, rfIgnoreCase]);
FileName2 := FileName1;
FileSize := lZips[Y][Z].UncompressedSize;
ArchiveFileId := Y;
Application.ProcessMessages();
End;
End;
End;
lMem := TMemoryStreamEx.Create();
Try
If AWorkSpaceProject.ProjectKind = spkRoot Then
Begin
With lZero.FileDatas[lZero.FileDatas.Count - 1].ArchivedFiles.Add() Do
Begin
FileName1 := 'ZeroCrc.hex';
FileExtension := 'hex';
FileName2 := FileName1;
FileSize := 0;
ArchiveFileId := lZero.FileDatas.Count - 1
End;
End;
lZero.SaveToStream(lMem);
If AWorkSpaceProject.ProjectKind = spkRoot Then
Begin
lMem.Size := lMem.Size - SizeOf(DWord);
SetCrc32Value(TStream(lMem.InterfaceObject), lMem.Size - SizeOf(QWord), AWorkSpaceProject.ZeroCrc32);
lMem.Position := lMem.Size;
lMem.WriteDWord(AWorkSpaceProject.ZeroCrc32, True);
End;
Finally
lZero := Nil;
End;
If AWorkSpaceProject.PackOutput Or AWorkSpaceProject.WorkSpace.PackOutput Then
Begin
lMem.Position := 0;
lZip := THsMemoryZipper.Create();
Try
lZip.AddFromStream('0', lMem);
For X := 0 To lZips.Count - 1 Do
Begin
(lZips[X] As IMemoryStreamEx).Position := 0;
lZip.AddFromStream(lZips[X].FileName, (lZips[X] As IMemoryStreamEx));
End;
lZip.SaveToFile(lOutPath + AWorkSpaceProject.ProjectName + '.zip');
Finally
lZip := Nil;
End;
End
Else
Begin
lMem.SaveToFile(lOutPath + '0');
For X := 0 To lZips.Count - 1 Do
lZips[X].SaveToFile(lOutPath + lZips[X].FileName);
End;
Finally
lMem := Nil;
End;
Finally
lZips := Nil;
End;
End;
Procedure TTSTOWorkSpaceProjectGroupIOImpl.PackMod(AWorkSpaceProject : ITSTOWorkSpaceProjectIO);
Var lOutPath : String;
lSr : TSearchRec;
lCanPack : Boolean;
lZip : IHsMemoryZipper;
Begin
lCanPack := False;
If AWorkSpaceProject.OutputPath <> '' Then
lOutPath := AWorkSpaceProject.OutputPath
Else
lOutPath := OutputPath;
lOutPath := IncludeTrailingBackSlash(StringReplace(lOutPath, '%ProjectName%', AWorkSpaceProject.ProjectName, [rfReplaceAll, rfIgnoreCase]));
If DirectoryExists(lOutPath) Then
Begin
If FindFirst(lOutPath + '*.*', faAnyFile, lSr) = 0 Then
Try
Repeat
If lSr.Attr * faDirectory <> faDirectory Then
Begin
lCanPack := True;
Break;
End;
Until FindNext(lSr) <> 0;
Finally
FindClose(lSr);
End;
End;
If Not lCanPack Then
Begin
If MessageConfirm('Project haven''t been built do you want to buid it now?') Then
Begin
CompileMod(AWorkSpaceProject);
lCanPack := True;
End;
End;
If lCanPack Then
Begin
lZip := THsMemoryZipper.Create();
Try
lZip.AddFiles(lOutPath + '*.*', faAnyFile);
lZip.SaveToFile(ExtractFilePath(ExcludeTrailingBackslash(lOutPath)) + AWorkSpaceProject.ProjectName + '.zip');
Finally
lZip := Nil;
End;
End;
End;
end.
|
unit EditTableFrame;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, StdCtrls, DbUnit, MdUnit;
type
{ TFrameEditTable }
TFrameEditTable = class(TFrame)
btnOK: TButton;
cbKeyFieldName: TComboBox;
edTableDesc: TEdit;
edTableName: TEdit;
lbKeyFieldName: TLabel;
lbTableNameFull: TLabel;
lbTableName: TLabel;
procedure btnOKClick(Sender: TObject);
private
{ private declarations }
FDbTableInfo: TDbTableInfo;
FOnItemRename: TNotifyEvent;
procedure SetDbTableInfo(AValue: TDbTableInfo);
public
{ public declarations }
MdStorage: TMdStorage;
property DbTableInfo: TDbTableInfo read FDbTableInfo write SetDbTableInfo;
property OnItemRename: TNotifyEvent read FOnItemRename write FOnItemRename;
procedure ReadItem();
procedure WriteItem();
end;
implementation
{$R *.lfm}
{ TFrameEditTable }
procedure TFrameEditTable.btnOKClick(Sender: TObject);
begin
WriteItem();
end;
procedure TFrameEditTable.SetDbTableInfo(AValue: TDbTableInfo);
begin
FDbTableInfo := AValue;
ReadItem();
end;
procedure TFrameEditTable.ReadItem();
var
i: Integer;
TmpField: TDbFieldInfo;
begin
if not Assigned(DbTableInfo) then
Exit;
Self.Visible := False;
edTableName.Text := DbTableInfo.TableName;
edTableDesc.Text := DbTableInfo.TableDescription;
lbKeyFieldName.Enabled := False;
cbKeyFieldName.Enabled := False;
cbKeyFieldName.Text := '';
// fill key fields list
for i := 0 to DbTableInfo.FieldsCount - 1 do
begin
TmpField := DbTableInfo.Fields[i];
if TmpField.FieldType = 'I' then
begin
cbKeyFieldName.AddItem(TmpField.FieldName, TmpField);
end;
end;
Self.Visible := True;
end;
procedure TFrameEditTable.WriteItem();
begin
if not Assigned(DbTableInfo) then
Exit;
if Trim(edTableName.Text) = '' then
Exit;
DbTableInfo.TableName := Trim(edTableName.Text);
DbTableInfo.TableDescription := Trim(edTableDesc.Text);
DbTableInfo.KeyFieldName := Trim(cbKeyFieldName.Text);
if Assigned(OnItemRename) then
OnItemRename(Self);
end;
end.
|
unit zLogSystem;
// Модуль протоколирования. Применяется всеми другими модулями
interface
uses SysUtils, Classes;
const
logNormal = 0;
logInfo = 1;
logAlert = 2;
logVirus = 3;
logGood = 4;
logError = 10;
logDebug = 11;
type
// События протоколирования
TAddToLogEvent = procedure (AMsg : string; InfoType : integer) of object;
TAddToDebugLogEvent = procedure (AMsg : string) of object;
TGetLog = procedure (ALog : TStrings) of object;
// Класс, отвечающий за глобальное протоколирование
TLogger = class
private
FOnAddToLog: TAddToLogEvent;
FOnAddToDebugLog: TAddToDebugLogEvent;
FOnGetLog: TGetLog;
procedure SetOnAddToLog(const Value: TAddToLogEvent);
procedure SetOnAddToDebugLog(const Value: TAddToDebugLogEvent);
procedure SetOnGetLog(const Value: TGetLog);
public
constructor Create;
// Добавление в протокол
procedure AddToLog(AMsg : string; InfoType : integer);
procedure GetLog(ALog : TStrings);
// Добавление в отладочный протокол
procedure AddToDebugLog(AMsg : string);
// Обработчик события "добавление в протокол"
property OnAddToLog : TAddToLogEvent read FOnAddToLog write SetOnAddToLog;
// Обработчик события "добавление в отладочный протокол"
property OnAddToDebugLog : TAddToDebugLogEvent read FOnAddToDebugLog write SetOnAddToDebugLog;
// Обработчик события "запрос всех событий протокола"
property OnGetLog : TGetLog read FOnGetLog write SetOnGetLog;
end;
TProgressEvent = procedure(AMax, ACurr : integer) of object;
// Класс, отвечающий за глобальное протоколирование
TzProgress = class
private
FMax, FCurr : integer;
FOnProgress: TProgressEvent;
procedure SetOnProgress(const Value: TProgressEvent);
// Вызов обработчика прогресс-индикации
procedure DoProgress(AMax, ACurr : integer);
procedure SetMax(const Value: integer);
public
constructor Create;
procedure AddProgressMax(AStepCount : integer);
// Шаг прогресса
procedure ProgressStep(AStep : integer = 1);
published
// Обработчик события "прогресс"
property OnProgress : TProgressEvent read FOnProgress write SetOnProgress;
property Max : integer read FMax write SetMax;
end;
// Добавление в протокол
procedure AddToLog(AMsg : string; InfoType : integer);
procedure AddToFileLog(AMsg : string);
// Добавление в отладочный протокол
procedure AddToDebugLog(AMsg : string);
var
DebugLogMode : boolean = false; // Режим отладочного протоколирования
threadvar
// Имя файла, в который дублируются строки протокола
FSpoolLogFileName : string;
ZLoggerClass : TLogger;
ZProgressClass : TzProgress;
// Инициализирует систему протоколирования
function InitLogger : boolean;
implementation
uses zTranslate;
{ TLogger }
procedure TLogger.AddToDebugLog(AMsg: string);
begin
if Assigned(FOnAddToDebugLog) then
FOnAddToDebugLog(AMsg);
end;
procedure TLogger.AddToLog(AMsg: string; InfoType: integer);
begin
if Assigned(FOnAddToLog) then
FOnAddToLog(AMsg, InfoType);
end;
constructor TLogger.Create;
begin
FOnAddToLog := nil;
FOnAddToDebugLog := nil;
FOnGetLog := nil;
end;
procedure TLogger.GetLog(ALog: TStrings);
begin
if Assigned(FOnGetLog) then
FOnGetLog(ALog);
end;
procedure TLogger.SetOnAddToDebugLog(const Value: TAddToDebugLogEvent);
begin
FOnAddToDebugLog := Value;
end;
procedure TLogger.SetOnAddToLog(const Value: TAddToLogEvent);
begin
FOnAddToLog := Value;
end;
// Добавление в протокол
procedure AddToLog(AMsg : string; InfoType : integer);
begin
ZLoggerClass.AddToLog(AMsg, InfoType);
if FSpoolLogFileName <> '' then
AddToFileLog(TranslateStr(AMsg));
end;
// Добавление в отладочный протокол
procedure AddToDebugLog(AMsg : string);
begin
if DebugLogMode then
ZLoggerClass.AddToDebugLog(AMsg);
end;
procedure AddToFileLog(AMsg : string);
var
f : TextFile;
begin
if FSpoolLogFileName = '' then exit;
AssignFile(f, FSpoolLogFileName);
try
// Если файл существует - дозапись, не существует - создание
if FileExists(FSpoolLogFileName) then Append(f)
else Rewrite(f);
except
exit; // При ошибках немедленный выход, дабы не усугублять положение программы
end;
try
try Writeln(f, AMsg); except end;
finally
CloseFile(f); // в конце обязательно закроем файл
end;
end;
procedure TLogger.SetOnGetLog(const Value: TGetLog);
begin
FOnGetLog := Value;
end;
function InitLogger : boolean;
begin
FSpoolLogFileName := '';
ZLoggerClass := TLogger.Create;
ZProgressClass := TZProgress.Create;
end;
{ TzProgress }
{ TzProgress }
constructor TzProgress.Create;
begin
FOnProgress := nil;
FMax := 0;
FCurr := 0;
end;
procedure TzProgress.ProgressStep(AStep : integer = 1);
begin
inc(FCurr, AStep);
if FCurr > FMax then
FMax := FCurr;
DoProgress(FMax, FCurr);
end;
procedure TzProgress.DoProgress(AMax, ACurr : integer);
begin
if Assigned(FOnProgress) then
FOnProgress(AMax, ACurr);
end;
procedure TzProgress.SetOnProgress(const Value: TProgressEvent);
begin
FOnProgress := Value;
end;
procedure TzProgress.AddProgressMax(AStepCount: integer);
begin
if AStepCount < 0 then exit;
FMax := FMax + AStepCount;
if FCurr > FMax then
FMax := FCurr;
DoProgress(FMax, FCurr);
end;
procedure TzProgress.SetMax(const Value: integer);
begin
FMax := Value;
end;
begin
end.
|
unit AqDrop.DB.Types;
interface
{$I '..\Core\AqDrop.Core.Defines.inc'}
uses
System.TypInfo,
System.Rtti,
Data.SqlTimSt,
Data.FmtBcd,
AqDrop.Core.Types;
type
IAqDBReadValue = interface
['{F1900805-2836-42B7-88A5-776D97A02795}']
function GetName: string;
procedure SetName(const pName: string);
function GetIsNull: Boolean;
function GetAsString: string;
{$IFNDEF AQMOBILE}
function GetAsAnsiString: AnsiString;
{$ENDIF}
function GetAsBoolean: Boolean;
function GetAsTimeStamp: TSQLTimeStamp;
function GetAsTimeStampOffset: TSQLTimeStampOffset;
function GetAsBCD: TBcd;
function GetAsDate: TDate;
function GetAsTime: TTime;
function GetAsDateTime: TDateTime;
function GetAsUInt8: UInt8;
function GetAsInt8: Int8;
function GetAsUInt16: UInt16;
function GetAsInt16: Int16;
function GetAsUInt32: UInt32;
function GetAsInt32: Int32;
function GetAsUInt64: UInt64;
function GetAsInt64: Int64;
function GetAsSingle: Single;
function GetAsDouble: Double;
function GetAsCurrency: Currency;
function GetAsGUID: TGUID;
function GetAsTValue(const pAsType: PTypeInfo): TValue;
property Name: string read GetName write SetName;
property AsString: string read GetAsString;
{$IFNDEF AQMOBILE}
property AsAnsiString: AnsiString read GetAsAnsiString;
{$ENDIF}
property AsBoolean: Boolean read GetAsBoolean;
property AsTimeStamp: TSQLTimeStamp read GetAsTimeStamp;
property AsTimeStampOffset: TSQLTimeStampOffset read GetAsTimeStampOffset;
property AsBCD: TBcd read GetAsBCD;
property AsDate: TDate read GetAsDate;
property AsTime: TTime read GetAsTime;
property AsDateTime: TDateTime read GetAsDateTime;
property AsUInt8: UInt8 read GetAsUInt8;
property AsInt8: Int8 read GetAsInt8;
property AsUInt16: UInt16 read GetAsUInt16;
property AsInt16: Int16 read GetAsInt16;
property AsUInt32: UInt32 read GetAsUInt32;
property AsInt32: Int32 read GetAsInt32;
property AsUInt64: UInt64 read GetAsUInt64;
property AsInt64: Int64 read GetAsInt64;
property AsSingle: Single read GetAsSingle;
property AsDouble: Double read GetAsDouble;
property AsCurrency: Currency read GetAsCurrency;
property AsGUID: TGUID read GetAsGUID;
property IsNull: Boolean read GetIsNull;
end;
IAqDBValue = interface(IAqDBReadValue)
['{6C1F05B1-85D1-4EA3-9DBB-0EC1F90FEC27}']
procedure SetDataType(const pDataType: TAqDataType);
procedure SetAsString(const pValue: string);
{$IFNDEF AQMOBILE}
procedure SetAsAnsiString(const pValue: AnsiString);
{$ENDIF}
procedure SetAsBoolean(const pValue: Boolean);
procedure SetAsTimeStamp(const pValue: TSQLTimeStamp);
procedure SetAsTimeStampOffset(const pValue: TSQLTimeStampOffset);
procedure SetAsBCD(const pValue: TBcd);
procedure SetAsDate(const pValue: TDate);
procedure SetAsTime(const pValue: TTime);
procedure SetAsDateTime(const pValue: TDateTime);
procedure SetAsUInt8(const pValue: UInt8);
procedure SetAsInt8(const pValue: Int8);
procedure SetAsUInt16(const pValue: UInt16);
procedure SetAsInt16(const pValue: Int16);
procedure SetAsUInt32(const pValue: UInt32);
procedure SetAsInt32(const pValue: Int32);
procedure SetAsUInt64(const pValue: UInt64);
procedure SetAsInt64(const pValue: Int64);
procedure SetAsSingle(const pValue: Single);
procedure SetAsDouble(const pValue: Double);
procedure SetAsCurrency(const pValue: Currency);
procedure SetAsGUID(const pValue: TGUID);
procedure SetNull(const pDataType: TAqDataType = TAqDataType.adtUnknown);
property AsString: string read GetAsString write SetAsString;
{$IFNDEF AQMOBILE}
property AsAnsiString: AnsiString read GetAsAnsiString write SetAsAnsiString;
{$ENDIF}
property AsBoolean: Boolean read GetAsBoolean write SetAsBoolean;
property AsTimeStamp: TSQLTimeStamp read GetAsTimeStamp write SetAsTimeStamp;
property AsTimeStampOffset: TSQLTimeStampOffset read GetAsTimeStampOffset write SetAsTimeStampOffset;
property AsBCD: TBcd read GetAsBCD write SetAsBCD;
property AsDate: TDate read GetAsDate write SetAsDate;
property AsTime: TTime read GetAsTime write SetAsTime;
property AsDateTime: TDateTime read GetAsDateTime write SetAsDateTime;
property AsUInt8: UInt8 read GetAsUInt8 write SetAsUInt8;
property AsInt8: Int8 read GetAsInt8 write SetAsInt8;
property AsUInt16: UInt16 read GetAsUInt16 write SetAsUInt16;
property AsInt16: Int16 read GetAsInt16 write SetAsInt16;
property AsUInt32: UInt32 read GetAsUInt32 write SetAsUInt32;
property AsInt32: Int32 read GetAsInt32 write SetAsInt32;
property AsUInt64: UInt64 read GetAsUInt64 write SetAsUInt64;
property AsInt64: Int64 read GetAsInt64 write SetAsInt64;
property AsSingle: Single read GetAsSingle write SetAsSingle;
property AsDouble: Double read GetAsDouble write SetAsDouble;
property AsCurrency: Currency read GetAsCurrency write SetAsCurrency;
property AsGUID: TGUID read GetAsGUID write SetAsGUID;
end;
IAqDBValues<I: IAqDBReadValue> = interface
['{23BB2D01-268C-403A-B27B-120D72D45DA4}']
function GetValueByIndex(pIndex: Int32): I;
function GetValueByName(pName: string): I;
function GetCount: Int32;
property Values[pName: string]: I read GetValueByName; default;
property Values[pIndex: Int32]: I read GetValueByIndex; default;
property Count: Int32 read GetCount;
end;
IAqDBReader = interface(IAqDBValues<IAqDBReadValue>)
['{B56AAE49-6EC1-416C-89CF-5BD78F14D981}']
function Next: Boolean;
end;
IAqDBParameters = interface(IAqDBValues<IAqDBValue>)
['{AF466B6B-264D-4EDA-80B7-3FECF0144B5B}']
end;
TAqDBValueHandlerMethod = reference to procedure(pValue: IAqDBValue);
TAqDBParametersHandlerMethod = reference to procedure(pParameters: IAqDBParameters);
implementation
end.
|
unit SqlQueryBuilderTestSuite;
interface
uses TestFramework,
InsertQueryTests,
UpdateQueryTests,
WhereClauseTests;
type
TSqlQueryBuilderTestSuite = class(TTestSuite)
public
class function suite(): ITestSuite;
end;
implementation
{ TSqlQueryBuilderTestSuite }
class function TSqlQueryBuilderTestSuite.suite: ITestSuite;
begin
Result:= TTestSuite.Create('SqlQueryBuilder Test Suite');
Result.AddSuite(TInsertQueryTests.Suite);
Result.AddSuite(TUpdateQueryTests.Suite);
Result.AddSuite(TWhereClauseTests.Suite);
end;
initialization
RegisterTest(TSqlQueryBuilderTestSuite.suite);
end. |
unit View.DepartmentEdit;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, View.TemplateEdit, Data.DB,
JvComponentBase, JvFormPlacement, Vcl.StdCtrls, Vcl.ExtCtrls,
Model.LanguageDictionary,
Model.ProSu.Interfaces,
Model.ProSu.Provider,
Model.Declarations,
Spring.Data.ObjectDataset,
Model.FormDeclarations, JvExControls, JvDBLookupTreeView, Vcl.DBCtrls,
Vcl.Mask;
type
TDepartmentEditForm = class(TTemplateEdit)
edDepartmentName: TDBEdit;
edCompanyId: TDBLookupComboBox;
labelCompanyId: TLabel;
edParentDepartmentId: TJvDBLookupTreeViewCombo;
labelParentDepartmentId: TLabel;
labelDepartmentName: TLabel;
dsCompany: TDataSource;
dsTitleTree: TDataSource;
edDepartmentManagerTitleId: TJvDBLookupTreeViewCombo;
labelDepartmentManagerTitleId: TLabel;
dsParentDeptTree: TDataSource;
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
fCompanyDataset : TObjectDataset;
fTitleTreeDataset : TObjectDataset;
fParentDeptTreeDataset : TObjectDataset;
procedure RefreshTitleDataset;
procedure FormLoaded; override;
class function RequiredPermission(cmd: TBrowseFormCommand) : string; override;
public
{ Public declarations }
end;
var
DepartmentEditForm: TDepartmentEditForm;
implementation
uses
Spring.Collections,
MainDM,
Spring.Persistence.Criteria.Restrictions;
{$R *.dfm}
procedure TDepartmentEditForm.FormCreate(Sender: TObject);
begin
inherited;
Caption := ComponentDictionary.GetText(Self.ClassName, 'Caption');
labelDepartmentName.Caption := ComponentDictionary.GetText(ClassName, 'labelDepartmentName.Caption');
labelParentDepartmentId.Caption := ComponentDictionary.GetText(ClassName, 'labelParentDepartmentId.Caption');
labelCompanyId.Caption := ComponentDictionary.GetText(ClassName, 'labelCompanyId.Caption');
//labelCompanyId.Caption := ComponentDictionary.GetText(ClassName, 'labelCompanyId.Caption');
labelDepartmentManagerTitleId.Caption := ComponentDictionary.GetText(ClassName, 'labelDepartmentManagerTitleId.Caption');
end;
procedure TDepartmentEditForm.FormDestroy(Sender: TObject);
begin
inherited;
fCompanyDataset.Free;
fTitleTreeDataset.Free;
fParentDeptTreeDataset.Free;
end;
procedure TDepartmentEditForm.FormLoaded;
begin
fCompanyDataset := TObjectDataset.Create(self);
fCompanyDataset.DataList := DMMain.Session.FindWhere<TCompany>(Restrictions.NotEq('IsDeleted', -1)) as IObjectList;
fCompanyDataset.Open;
dsCompany.DataSet := fCompanyDataset;
fTitleTreeDataset := TObjectDataset.Create(self);
dsTitleTree.DataSet := fTitleTreeDataset;
RefreshTitleDataset;
if fTitleTreeDataset.RecordCount>0 then
edDepartmentManagerTitleId.FullExpand := True;
fParentDeptTreeDataset := TObjectDataset.Create(self);
dsParentDeptTree.DataSet := fParentDeptTreeDataset;
fParentDeptTreeDataset.DataList := DMMain.Session.CreateCriteria<TDepartment>
.Add(Restrictions.NotEq('IsDeleted', -1))
.Add(Restrictions.Eq('CompanyId', DMMain.Company.CompanyId)).ToList as IObjectList;
fParentDeptTreeDataset.Open;
if fParentDeptTreeDataset.RecordCount>0 then
edParentDepartmentId.FullExpand := True;
end;
procedure TDepartmentEditForm.RefreshTitleDataset;
begin
fTitleTreeDataset.Close;
fTitleTreeDataset.DataList := dmmain.Session.GetList<TTitle>('select * from Title where CompanyId=:0;',
[DataSource1.DataSet.FieldByName('CompanyId').AsInteger]) as IObjectList;
fTitleTreeDataset.Open;
end;
class function TDepartmentEditForm.RequiredPermission(
cmd: TBrowseFormCommand): string;
begin
Result := '>????<';
case cmd of
efcmdAdd: Result := '3512';
efcmdEdit: Result := '3513';
efcmdDelete: Result := '3514';
efcmdViewDetail: Result := '3515';
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ }
{ Copyright(c) 2012-2013 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit FMX.Pickers;
interface
uses
System.Classes, System.UITypes, System.Generics.Collections, System.SysUtils,
FMX.Types, FMX.Controls, FMX.Consts;
type
TPickerFactoryService = class;
EFeatureError = class (Exception);
TDropDownKind = (ddkCustom, ddkNative);
{ TCustomPicker }
// Basis for creation of any pickers. Each picker belongs to any control.
// Each picker is able to appear and desappear. Only one picker
// can displayed (other closed).
TCustomPicker = class abstract
strict private
FPickerService: TPickerFactoryService;
FOnShow: TNotifyEvent;
FOnHide: TNotifyEvent;
FParent: TControl;
protected
procedure DoShow; virtual;
procedure DoHide; virtual;
public
constructor Create(const APickerService: TPickerFactoryService); virtual;
destructor Destroy; override;
procedure Show; virtual;
procedure Hide; virtual; abstract;
function IsShown: Boolean; virtual;
public
property Parent: TControl read FParent write FParent;
property OnShow: TNotifyEvent read FOnShow write FOnShow;
property OnHide: TNotifyEvent read FOnHide write FOnHide;
end;
{ TCustomDateTimePicker }
TDatePickerShowMode = (psmDate, psmTime, psmDateTime);
TOnDateChanged = procedure (Sender: TObject; const ADateTime: TDateTime) of object;
// Picker for choosen date
TCustomDateTimePicker = class abstract (TCustomPicker)
strict private
FDate: TDateTime;
FMinDate: TDateTime;
FMaxDate: TDateTime;
FFirstDayOfWeek: TCalDayOfWeek;
FShowMode: TDatePickerShowMode;
FShowWeekNumbers: Boolean;
FTodayDefault: Boolean;
FOnDateChanged: TOnDateChanged;
protected
procedure SetShowMode(const AValue: TDatePickerShowMode); virtual;
procedure SetMinDate(const AValue: TDateTime); virtual;
procedure SetMaxDate(const AValue: TDateTime); virtual;
procedure DoDateChanged(const ADateTime: TDateTime); virtual;
public
constructor Create(const APickerService: TPickerFactoryService); override;
property Date: TDateTime read FDate write FDate;
property MinDate: TDateTime read FMinDate write SetMinDate;
property MaxDate: TDateTime read FMaxDate write SetMaxDate;
property FirstDayOfWeek: TCalDayOfWeek read FFirstDayOfWeek write FFirstDayOfWeek;
property ShowMode: TDatePickerShowMode read FShowMode write SetShowMode;
property ShowWeekNumbers: Boolean read FShowWeekNumbers write FShowWeekNumbers;
property TodayDefault: Boolean read FTodayDefault write FTodayDefault;
property OnDateChanged: TOnDateChanged read FOnDateChanged write FOnDateChanged;
end;
{ TCustomListPicker }
TOnValueChanged = procedure (Sender: TObject; const AValueIndex: Integer) of object;
{ Picker for choosen string value from list of strings. }
TCustomListPicker = class abstract (TCustomPicker)
strict private
FValues: TStrings;
FCountVisibleItems: Integer;
FItemIndex: Integer;
FItemHeight: Single;
FOnValueChanged: TOnValueChanged;
protected
procedure SetValues(AValues: TStrings); virtual;
procedure SetItemIndex(AValue: Integer); virtual;
procedure DoItemChanged(const AItemIndex: Integer); virtual;
public
constructor Create(const APickerService: TPickerFactoryService); override;
destructor Destroy; override;
property ItemIndex: Integer read FItemIndex write SetItemIndex;
property ItemHeight: Single read FItemHeight write FItemHeight;
property CountVisibleItems: Integer read FCountVisibleItems write FCountVisibleItems;
property Values: TStrings read FValues write SetValues;
property OnValueChanged: TOnValueChanged read FOnValueChanged write FOnValueChanged;
end;
{ Picker Factory Service }
{ Factory interface for creation picker instance and close all pickers }
IFMXPickerService = interface (IInterface)
['{AE1A8D3C-D5FE-4343-A7B0-2AAEDA3ABB8A}']
function CreateDateTimePicker: TCustomDateTimePicker;
function CreateListPicker: TCustomListPicker;
procedure CloseAllPickers;
end;
{ Factory of creating pickers: Date Time Picker and List Picker }
TPickerFactoryService = class abstract (TInterfacedObject, IFMXPickerService)
strict private
FPickers: TList<TCustomPicker>;
protected
function DoCreateDateTimePicker: TCustomDateTimePicker; virtual; abstract;
function DoCreateListPicker: TCustomListPicker; virtual; abstract;
procedure DoPickerRemoving(const APicker: TCustomPicker); virtual;
public
constructor Create;
destructor Destroy; override;
{ IFMXPickerService }
function CreateDateTimePicker: TCustomDateTimePicker;
function CreateListPicker: TCustomListPicker;
procedure CloseAllPickers;
end;
implementation
uses
System.Math,
{$IFDEF IOS}
FMX.Pickers.iOS;
{$ELSE}
{$IFDEF ANDROID}
FMX.Pickers.Android;
{$ELSE}
FMX.Pickers.Default;
{$ENDIF}
{$ENDIF}
{ TCustomListPicker }
constructor TCustomListPicker.Create(const APickerService: TPickerFactoryService);
begin
inherited Create(APickerService);
FValues := TStringList.Create;
end;
destructor TCustomListPicker.Destroy;
begin
FreeAndNil(FValues);
inherited Destroy;
end;
procedure TCustomListPicker.DoItemChanged(const AItemIndex: Integer);
begin
if Assigned(FOnValueChanged) then
FOnValueChanged(Parent, AItemIndex);
end;
procedure TCustomListPicker.SetItemIndex(AValue: Integer);
begin
FItemIndex := AValue;
end;
procedure TCustomListPicker.SetValues(AValues: TStrings);
begin
FValues.Assign(AValues);
end;
{ TPickerFactoryService }
procedure TPickerFactoryService.CloseAllPickers;
var
Picker: TCustomPicker;
begin
for Picker in FPickers do
Picker.Hide;
end;
constructor TPickerFactoryService.Create;
begin
inherited Create;
FPickers := TList<TCustomPicker>.Create;
end;
function TPickerFactoryService.CreateDateTimePicker: TCustomDateTimePicker;
begin
Result := DoCreateDateTimePicker;
FPickers.Add(Result);
end;
function TPickerFactoryService.CreateListPicker: TCustomListPicker;
begin
Result := DoCreateListPicker;
FPickers.Add(Result);
end;
destructor TPickerFactoryService.Destroy;
begin
FreeAndNil(FPickers);
inherited Destroy;
end;
procedure TPickerFactoryService.DoPickerRemoving(const APicker: TCustomPicker);
begin
if Assigned(FPickers) and Assigned(APicker) then
FPickers.Remove(APicker);
end;
{ TCustomPicker }
constructor TCustomPicker.Create(const APickerService: TPickerFactoryService);
begin
Assert(Assigned(APickerService), 'APickerService can not be a nil');
FPickerService := APickerService;
end;
destructor TCustomPicker.Destroy;
begin
if Assigned(FPickerService) then
FPickerService.DoPickerRemoving(Self);
inherited Destroy;
end;
procedure TCustomPicker.DoHide;
begin
if Assigned(FOnHide) then
FOnHide(Parent);
end;
procedure TCustomPicker.DoShow;
begin
if Assigned(FOnShow) then
FOnShow(Parent);
end;
function TCustomPicker.IsShown: Boolean;
begin
Result := False;
end;
procedure TCustomPicker.Show;
begin
FPickerService.CloseAllPickers;
end;
{ TCustomDateTimePicker }
constructor TCustomDateTimePicker.Create(
const APickerService: TPickerFactoryService);
begin
inherited Create(APickerService);
FMinDate := 0.0;
FMaxDate := 0.0;
end;
procedure TCustomDateTimePicker.DoDateChanged(const ADateTime: TDateTime);
begin
if Assigned(FOnDateChanged) then
FOnDateChanged(Parent, ADateTime);
end;
procedure TCustomDateTimePicker.SetMaxDate(const AValue: TDateTime);
begin
FMaxDate := AValue;
end;
procedure TCustomDateTimePicker.SetMinDate(const AValue: TDateTime);
begin
FMinDate := AValue;
end;
procedure TCustomDateTimePicker.SetShowMode(const AValue: TDatePickerShowMode);
begin
FShowMode := AValue;
end;
initialization
RegisterPickersService;
end.
|
unit SimThyrPrediction;
{ SimThyr Project }
{ A numerical simulator of thyrotropic feedback control }
{ Version 3.3.2 }
{ (c) J. W. Dietrich, 1994 - 2014 }
{ (c) Ludwig Maximilian University of Munich 1995 - 2002 }
{ (c) Ruhr University of Bochum 2005 - 2013 }
{ This unit implements a window showing predicted equilibrium values }
{ Source code released under the BSD License }
{ See http://simthyr.sourceforge.net for details }
{$mode objfpc}
interface
uses
Classes, SysUtils, FileUtil, LResources, Forms, Controls, Graphics, Dialogs,
StdCtrls, SimThyrTypes, SimThyrResources, SimThyrServices, UnitConverter;
type
{ TPrediction }
TPrediction = class(TForm)
PredictionMemo: TMemo;
private
{ private declarations }
public
{ public declarations }
end;
var
Prediction: TPrediction;
function TRH0: real;
procedure PredictEquilibrium;
procedure ClearPrediction;
procedure ShowPredictedValues;
implementation
function arc (chi: real): real;
{rechnet Winkel von Grad nach Bogenmaß um}
begin
arc := 2 * pi * (chi / 360);
end;
function arccosinus (cosphi: real): real;
{errechnet den Arcus-Cosinus einer Zahl zwischen -1 und 1}
var
arcsin: real;
begin
arcsin := arctan(cosphi / sqrt(1 - sqr(cosphi)));
arccosinus := arc(90) - arcsin;
end;
function TRH0: real;
begin
TRHe := 0; {mol/l exogeniously applied TRH}
TRHi := TRHs; {ng/l endogenious TRH, according to Rondeel et al. 1988}
TRHi := TRHi * UTRH; {mol/l}
TRH0 := TRHi + TRHe; {mol/l portal total TRH concentration}
end;
procedure PredictEquilibrium;
{predicts equilibrium values of behavioural parameters like TSH, free T4 or free T3}
begin
TRH1 := TRH0;
k1 := gH * alphaS / betaS;
k11 := alphaS / betaS;
k2 := GT * alphaT / betaT;
k21 := k2;
k22 := k21 / (1 + k41 * TBG + k42 * TBPA);
k3 := GD2 * alpha32 / (beta32 * (1 + k31 * IBS));
k5 := GD1 * alpha31 / beta31;
k51 := k5 / (1 + k30 * TBG);
k6 := 1 / (2 * (1 + SS) * alphaS2);
k61 := k6 * k11;
k7 := dH + TRH1;
k8 := alphaS2 * gH * TRH1 / (dH + TRH1);
k9 := DS * betaS2;
G3 := k3 * GR / (k3 + dR);
D3 := kM2 * dR / (k3 + dR);
a1 := (D3 + k22 + LS * G3 * k22) / k61;
b1 := D3 * dT / k61 + 2 * D3 * k9 + 2 * k9 * k22 + 2 * LS * G3 * k9 * k22 - 2 * D3 * k8 - 2 * k8 * k22;
c1 := 2 * (D3 * dT * k9 - D3 * dT * k8 - 2 * (1 + SS) * D3 * k8 * k9 * k61 - 2 * (1 + SS) * k8 * k9 * k22 * k61);
d1 := -4 * (1 + SS) * D3 * dT * k8 * k9 * k61;
r1 := c1 / a1 - 1 / 3 * sqr(b1 / a1);
s1 := 2 / 27 * sqr(b1 / a1) * (b1 / a1) - 1 / 3 * c1 * b1 / sqr(a1) + d1 / a1;
p1 := r1 / 3;
q1 := s1 / 2;
Det := p1 * p1 * p1 + q1 * q1;
if Det > 0 then
begin {Cardano-Formel, eine reale Lösung}
u := exp(ln(-q1 + sqrt(Det)) * (1 / 3));
v := exp(ln(-q1 - sqrt(Det)) * (1 / 3));
y1 := u + v; {reale Lösung nach der Cardano-Fomel}
y2 := -(u + v) / 2; {Realteil der 1. komplexen Lösung}
y3 := y2; {Realteil der 2. komplexen Lösung, identisch mit y2}
end
else
begin {Casus irreducibilis, drei reale Lösungen}
u := -q1 / (sqrt(-p1 * sqr(-p1))); {cos phi}
phi := arccosinus(u); {Winkel im Bogenmaß}
y1 := 2 * sqrt(-p1) * cos(phi / 3);
y2 := -2 * sqrt(-p1) * cos(phi / 3 + arc(60));
y3 := -2 * sqrt(-p1) * cos(phi / 3 - arc(60));
end;
TSH1 := y1 - b1 / (3 * a1);
TSH2 := y2 - b1 / (3 * a1);
TSH3 := y3 - b1 / (3 * a1);
FT41 := alphaT * GT * TSH1 / (betaT * (dT + TSH1) * (1 + k41 * TBG + k42 * TBPA));
FT42 := alphaT * GT * TSH2 / (betaT * (dT + TSH2) * (1 + k41 * TBG + k42 * TBPA));
FT43 := alphaT * GT * TSH3 / (betaT * (dT + TSH3) * (1 + k41 * TBG + k42 * TBPA));
T41 := alphaT * GT * TSH1 / (betaT * (dT + TSH1));
T42 := alphaT * GT * TSH2 / (betaT * (dT + TSH2));
T43 := alphaT * GT * TSH3 / (betaT * (dT + TSH3));
T3z1 := alpha32 * GD2 * FT41 / (beta32 * (kM2 + FT41));
T3z2 := alpha32 * GD2 * FT42 / (beta32 * (kM2 + FT42));
T3z3 := alpha32 * GD2 * FT43 / (beta32 * (kM2 + FT43));
T3n1 := T3z1 / (1 + k31 * IBS);
T3n2 := T3z2 / (1 + k31 * IBS);
T3n3 := T3z3 / (1 + k31 * IBS);
T3R1 := GR * T3n1 / (DR + T3n1);
T3R2 := GR * T3n2 / (DR + T3n2);
T3R3 := GR * T3n3 / (DR + T3n3);
FT31 := k51 * FT41 / (kM1 + FT41);
FT32 := k51 * FT42 / (kM1 + FT42);
FT33 := k51 * FT43 / (kM1 + FT43);
T31 := k5 * FT41 / (kM1 + FT41);
T32 := k5 * FT42 / (kM1 + FT42);
T33 := k5 * FT43 / (kM1 + FT43);
end;
procedure ClearPrediction;
{clears the contents of the prediction window}
var
theCaption: String;
begin
theCaption := Prediction.PredictionMemo.Lines[0];
Prediction.PredictionMemo.Clear;
Prediction.PredictionMemo.Lines.Text := theCaption;
end;
procedure ShowPredictedValues;
{writes predicted values into the memo field of the prediction window}
var
FF: TFloatFormat;
FT4conversionFactor, FT3conversionFactor: real;
TT4conversionFactor, TT3conversionFactor, cT3conversionFactor: real;
begin
FT4conversionFactor := ConvertedValue(1, T4_MOLAR_MASS, 'mol/l', gParameterUnit[FT4_pos]);
TT4conversionFactor := ConvertedValue(1, T4_MOLAR_MASS, 'mol/l', gParameterUnit[TT4_pos]);
TT3conversionFactor := ConvertedValue(1, T3_MOLAR_MASS, 'mol/l', gParameterUnit[TT3_pos]);
FT3conversionFactor := ConvertedValue(1, T3_MOLAR_MASS, 'mol/l', gParameterUnit[FT3_pos]);
cT3conversionFactor := ConvertedValue(1, T3_MOLAR_MASS, 'mol/l', gParameterUnit[cT3_pos]);
ClearPrediction;
Prediction.Show;
FF := ffFixed;
writeaMemoLine(Prediction.PredictionMemo, '');
writeaMemoLine(Prediction.PredictionMemo, 'TRH: ' + FloatToStrF(TRH1 / UTRH, FF, 0, 4) + ' ' + gParameterUnit[TRH_pos]);
writeaMemoLine(Prediction.PredictionMemo, 'TSH: ' + FloatToStrF(TSH1 * gParameterFactor[pTSH_pos], FF, 0, 4) + ', ' + FloatToStrF(TSH2 * gParameterFactor[pTSH_pos], FF, 0, 4) + ' and ' + FloatToStrF(TSH3 * gParameterFactor[pTSH_pos], FF, 0, 4) + ' ' + gParameterUnit[TSH_pos]);
writeaMemoLine(Prediction.PredictionMemo, 'TT4: ' + FloatToStrF(T41 * TT4conversionFactor, FF, 0, 4) + ', ' + FloatToStrF(T42 * TT4conversionFactor, FF, 0, 4) + ' and ' + FloatToStrF(T43 * TT4conversionFactor, FF, 0, 4) + ' ' + gParameterUnit[TT4_pos]);
writeaMemoLine(Prediction.PredictionMemo, 'FT4: ' + FloatToStrF(FT41 * FT4conversionFactor, FF, 0, 4) + ', ' + FloatToStrF(FT42 * FT4conversionFactor, FF, 0, 4) + ' and ' + FloatToStrF(FT43 * FT4conversionFactor, FF, 0, 4) + ' ' + gParameterUnit[FT4_pos]);
writeaMemoLine(Prediction.PredictionMemo, 'TT3: ' + FloatToStrF(T31 * TT3conversionFactor, FF, 0, 4) + ', ' + FloatToStrF(T32 * TT3conversionFactor, FF, 0, 4) + ' and ' + FloatToStrF(T33 * TT3conversionFactor, FF, 0, 4) + ' ' + gParameterUnit[TT3_pos]);
writeaMemoLine(Prediction.PredictionMemo, 'FT3: ' + FloatToStrF(FT31 * FT3conversionFactor, FF, 0, 4) + ', ' + FloatToStrF(FT32 * FT3conversionFactor, FF, 0, 4) + ' and ' + FloatToStrF(FT33 * FT3conversionFactor, FF, 0, 4) + ' ' + gParameterUnit[FT3_pos]);
writeaMemoLine(Prediction.PredictionMemo, 'cT3: ' + FloatToStrF(T3z1 * cT3conversionFactor, FF, 0, 4) + ', ' + FloatToStrF(T3z2 * cT3conversionFactor, FF, 0, 4) + ' and ' + FloatToStrF(T3z2 * cT3conversionFactor, FF, 0, 4) + ' ' + gParameterUnit[FT3_pos]);
writeaMemoLine(Prediction.PredictionMemo, '');
writeaMemoLine(Prediction.PredictionMemo, NEGATIVE_VALUES_HINT);
writeaMemoLine(Prediction.PredictionMemo, DEVIATION_STRING);
Prediction.PredictionMemo.SelStart := 0;
Prediction.PredictionMemo.SelLength := 0;
end;
initialization
{$I simthyrprediction.lrs}
end.
|
unit ExportTabularCOBJ;
uses ExportCore,
ExportTabularCore,
ExportJson;
var ExportTabularCOBJ_outputLines: TStringList;
function initialize(): Integer;
begin
ExportTabularCOBJ_outputLines := TStringList.create();
ExportTabularCOBJ_outputLines.add(
'"File"' // Name of the originating ESM
+ ', "Form ID"' // Form ID
+ ', "Editor ID"' // Editor ID
+ ', "Product"' // Reference to product
+ ', "Recipe"' // Reference to recipe
+ ', "Components"' // Sorted JSON array of the components needed to craft. Each component is formatted as
// `[editor id] ([amount])`
);
end;
function canProcess(el: IInterface): Boolean;
begin
result := signature(el) = 'COBJ';
end;
function process(cobj: IInterface): Integer;
var product: IInterface;
recipe: IInterface;
begin
if not canProcess(cobj) then begin
addWarning(name(cobj) + ' is not a COBJ. Entry was ignored.');
exit;
end;
product := eBySign(cobj, 'CNAM');
recipe := eBySign(cobj, 'GNAM');
ExportTabularCOBJ_outputLines.add(
escapeCsvString(getFileName(getFile(cobj))) + ', '
+ escapeCsvString(stringFormID(cobj)) + ', '
+ escapeCsvString(evBySign(cobj, 'EDID')) + ', '
+ escapeCsvString(ifThen(not assigned(linksTo(product)), '', gev(product))) + ', '
+ escapeCsvString(ifThen(not assigned(linksTo(recipe)), '', gev(recipe))) + ', '
+ escapeCsvString(getJsonComponentArray(cobj))
);
end;
function finalize(): Integer;
begin
createDir('dumps/');
ExportTabularCOBJ_outputLines.saveToFile('dumps/COBJ.csv');
ExportTabularCOBJ_outputLines.free();
end;
(**
* Returns the components of [cobj] as a serialized JSON array of editor IDs and counts.
*
* @param cobj the constructible object to return the components of
* @return the components of [cobj] as a serialized JSON array of editor IDs and counts
*)
function getJsonComponentArray(cobj: IInterface): String;
var i: Integer;
components: IInterface;
component: IInterface;
resultList: TStringList;
begin
resultList := TStringList.create();
components := eBySign(cobj, 'FVPA');
for i := 0 to eCount(components) - 1 do begin
component := eByIndex(components, i);
resultList.add(
'{' +
'"Component":"' + escapeJson(evByName(component, 'Component')) + '"' +
',"Count":"' + escapeJson(evByName(component, 'Count')) + '"' +
',"Curve Table":"' + escapeJson(evByName(component, 'Curve Table')) + '"' +
'}'
);
end;
resultList.sort();
result := listToJsonArray(resultList);
resultList.free();
end;
end.
|
unit ClipbrdMon;
interface
uses windows,Messages,Classes,WinUtils;
type
TClipboardMonitor = class(TMessageComponent)
private
FActive: boolean;
FNextViewer : THandle;
FOnChanged: TNotifyEvent;
procedure SetActive(const Value: boolean);
protected
procedure WMCHANGECBCHAIN(var Message:TMessage); message WM_CHANGECBCHAIN;
procedure WMDRAWCLIPBOARD(var Message:TMessage); message WM_DRAWCLIPBOARD;
public
constructor Create(AOwner : TComponent); override;
Destructor Destroy;override;
procedure Add;
procedure Delete;
published
property Active : boolean read FActive write SetActive default false;
property OnChanged : TNotifyEvent read FOnChanged write FOnChanged;
end;
implementation
{ TClipboardMonitor }
constructor TClipboardMonitor.Create(AOwner: TComponent);
begin
inherited;
FActive := false;
FNextViewer := 0;
end;
destructor TClipboardMonitor.Destroy;
begin
active := false;
inherited;
end;
procedure TClipboardMonitor.Add;
begin
if not FActive then
begin
FNextViewer := SetClipboardViewer(FUtilWindow.Handle);
FActive := true;
end;
end;
procedure TClipboardMonitor.Delete;
begin
if FActive then
begin
ChangeClipboardChain(FUtilWindow.Handle, FNextViewer);
FActive := false;
end;
end;
procedure TClipboardMonitor.SetActive(const Value: boolean);
begin
if (FActive <> Value) then
if (csDesigning in ComponentState) then
FActive := Value
else
if value then
Add
else
delete;
end;
procedure TClipboardMonitor.WMCHANGECBCHAIN(var Message: TMessage);
begin
if LongWord(Message.wParam) = FNextViewer then
FNextViewer := Message.lParam else
// Otherwise, pass the message to the next link.
if (FNextViewer <>0 ) then
SendMessage(FNextViewer, Message.Msg, Message.wParam, Message.lParam);
end;
procedure TClipboardMonitor.WMDRAWCLIPBOARD(var Message: TMessage);
begin
if Assigned(FONChanged) then
FONChanged(self);
SendMessage(FNextViewer, Message.Msg, Message.wParam, Message.lParam);
end;
end.
|
{*******************************************************}
{ }
{ System Information Library }
{ 2006, Gullb3rg }
{ Codius }
{ }
{*******************************************************}
Unit unSystemInformation;
Interface
uses
Windows, Winsock,
SysUtils, NB30;
Type
POSVersionInfoEx = ^TOSVersionInfoEx;
TOSVersionInfoEx = packed record
dwOSVersionInfoSize : DWORD;
dwMajorVersion : DWORD;
dwMinorVersion : DWORD;
dwBuildNumber : DWORD;
dwPlatformId : DWORD;
szCSDVersion : Array [0..127] of AnsiChar;
wServicePackMajor : Word;
wServicePackMinor : Word;
wSuiteMask : Word;
wProductType : Byte;
wReserved : Byte;
end;
TRSystemInformation = Record
UserName : String;
OS : String;
Edition : String;
ComputerName : String;
Location : String;
LocalIP : String;
WinVersion : String;
Build : Cardinal;
WindowsID : String;
ServicePack : String;
VolumeSerial : String;
DefultBrowser : String;
MACAdress : String;
WinEdition : String;
UpTime : String;
end;
TCSystemInformation = Class
Private
CSystemInformation : TCSystemInformation;
RSystemInformation : TRSystemInformation;
Function GetUser : String;
Function GetComputerNetName : String;
Function GetLanguage(cType: Cardinal) : String;
Function GetOS : String;
Function GetUpTime : String;
Function GetLocalIP : String;
Function GetWinVersion : String;
Function GetBuild : Cardinal;
Function GetWindowsID : String;
Function GetServicePack : String;
Function FindVolumeSerial(const Drive : PChar) : String;
Function GetDefultBrowser : String;
Function GetMACAdress : String;
Function GetWinEdition : String;
Function GetOSVerInfo(var Info: TOSVersionInfoEx): Boolean;
Function ViewUser : String;
Function ViewComputerNetName : String;
Function ViewLanguage : String;
Function ViewOS : String;
Function ViewUpTime : String;
Function ViewLocalIP : String;
Function ViewWinVersion : String;
Function ViewBuild : Cardinal;
Function ViewWindowsID : String;
Function ViewServicePack : String;
Function ViewVolumeSerial : String;
Function ViewDefultBrowser : String;
Function ViewMACAdress : String;
Function ViewWinEdition : String;
Public
Constructor Create;
Procedure Refresh;
Property UserName : String Read ViewUser;
Property ComputerName : String Read ViewComputerNetName;
Property Language : String Read ViewLanguage;
Property OS : String Read ViewOS;
Property UpTime : String Read ViewUpTime;
Property LocalIP : String Read ViewLocalIP;
Property WinVersion : String Read ViewWinVersion;
Property Build : Cardinal Read ViewBuild;
Property WindowsID : String Read ViewWindowsID;
Property ServicePack : String Read ViewServicePack;
Property VolumeSerial : String Read ViewVolumeSerial;
Property DefultBrowser : String Read ViewDefultBrowser;
Property MACAdress : String Read ViewMACAdress;
Property WinEdition : String Read ViewWinEdition;
end;
Const
VER_NT_WORKSTATION = $0000001;
{$EXTERNALSYM VER_NT_WORKSTATION}
VER_SUITE_PERSONAL = $00000200;
{$EXTERNALSYM VER_SUITE_PERSONAL}
implementation
{ IntToStr
This function is used to convert integers to strings. }
Function IntToStr(Const Value: Integer): String;
Var
s : String[11];
Begin
Str(Value, s);
Result := s;
End;
{ StrToInt
This function is used to convert strings to integers. }
Function StrToInt(Const s: String): Integer;
Var
e : integer;
Begin
val(s, Result, e);
End;
{ TCSystemInformation.Create
This constructor will initialize the system information record. }
Constructor TCSystemInformation.Create;
Begin
Inherited;
Refresh;
End;
{ TCSystemInformation.Refresh
This routine will refresh the processor record. }
Procedure TCSystemInformation.Refresh;
Begin
RSystemInformation.UserName := GetUser;
RSystemInformation.ComputerName := GetComputerNetName;
RSystemInformation.WinEdition := GetWinEdition;
RSystemInformation.Location := GetLanguage(LOCALE_SENGCOUNTRY);
RSystemInformation.LocalIP := GetLocalIP;
RSystemInformation.WinVersion := GetWinVersion;
RSystemInformation.Build := GetBuild;
RSystemInformation.WindowsID := GetWindowsID;
RSystemInformation.ServicePack := GetServicePack;
RSystemInformation.VolumeSerial := FindVolumeSerial('C:\');
RSystemInformation.DefultBrowser := GetDefultBrowser;
RSystemInformation.MACAdress := GetMACAdress;
RSystemInformation.WinEdition := GetWinEdition;
RSystemInformation.UpTime := GetUpTime;
RSystemInformation.OS := GetOS;
end;
{ TCSystemInformation.ViewUser
This routine will return the username. }
Function TCSystemInformation.ViewUser : String;
Begin
Result := RSystemInformation.UserName;
End;
{ TCSystemInformation.ViewBuild
This routine will return the Build number of your OS version. }
Function TCSystemInformation.ViewBuild : Cardinal;
Begin
Result := RSystemInformation.Build;
End;
{ TCSystemInformation.ViewOS
This routine will return the OS version installed. }
Function TCSystemInformation.ViewOS : String;
Begin
Result := RSystemInformation.OS;
End;
{ TCSysemInformation.ViewComputerNetName
This routine will return the computer name. }
Function TCSystemInformation.ViewComputerNetName : String;
Begin
Result := RSystemInformation.ComputerName;
End;
{ TCSystemInformation.ViewLocation
This routine will return the location. }
Function TCSystemInformation.ViewLanguage : String;
Begin
Result := RSystemInformation.Location;
End;
{ TCSystemInformation.ViewLocalIP
This routine will return your local IP. }
Function TCSystemInformation.ViewLocalIP : String;
Begin
Result := RSystemInformation.LocalIP;
End;
{ TCSystemInformation.ViewWinVersion
This routine will return the Windows version. }
Function TCSystemInformation.ViewWinVersion : String;
Begin
Result := RSystemInformation.WinVersion;
End;
{ TCSystemInformation.ViewBuild
This routine will return Windows build number. }
Function TCSystemInformation.ViewWindowsID : String;
Begin
Result := RSystemInformation.WindowsID;
End;
{ TCSystemInformation.ViewServicePack
This routine will return yout Service Pack. }
Function TCSystemInformation.ViewServicePack : String;
Begin
Result := RSystemInformation.ServicePack;
End;
{ TCSystemInformation.ViewVolumeSerial
This routine will return root serial number. }
Function TCSystemInformation.ViewVolumeSerial : String;
Begin
Result := RSystemInformation.VolumeSerial;
End;
{ TCSystemInformation.ViewDefultBrowser
This routine will return the defult browser. }
Function TCSystemInformation.ViewDefultBrowser;
Begin
Result := RSystemInformation.DefultBrowser;
End;
{ TCSystemInformation.ViewMACAdress
This routine will return the MAC adress. }
Function TCSystemInformation.ViewMACAdress : String;
Begin
Result := RSystemInformation.MACAdress;
End;
{ TCSystemInformation.ViewWinEdition
This routine will return the Windows Edition. }
Function TCSystemInformation.ViewWinEdition : String;
Begin
Result := RSystemInformation.WinEdition;
End;
{ TCSystemInformation.ViewUpTime
This routine will return the UpTime. }
Function TCSystemInformation.ViewUpTime : String;
Begin
Result := RSystemInformation.UpTime;
End;
{ TCSystemInformation.GetUser
This routine is used to retrive Username. }
Function TCSystemInformation.GetUser: string;
Var
UserName : string;
UserNameLen : Dword;
Begin
UserNameLen := 255;
SetLength(userName, UserNameLen);
If GetUserName(pChar(UserName), UserNameLen) Then
Result := Copy(UserName,1,UserNameLen - 1)
Else
Result := 'Unknown';
End;
{ TCSystemInformation.GetComputerNetName
This routine is used to retrive computer name. }
Function TCSystemInformation.GetComputerNetName: string;
var
Temp : Array[0..255] of char;
size : dword;
begin
size := 256;
if GetComputerName(Temp, size) then
Result := Temp
else
Result := ''
end;
{ TCSystemInformation.GetLanguage
This routine is used to retrive language. }
Function TCSystemInformation.GetLanguage(cType: Cardinal): String;
Var
Temp : Array [0..255] of Char;
begin
FillChar(Temp, sizeOf(Temp), #0);
GetLocaleInfo(LOCALE_SYSTEM_DEFAULT, cType, Temp, sizeOf(Temp));
Result := String(Temp);
end;
{ TCSystemInformation.GetOSVerInfo(var Info: TOSVersionInfoEx
This routine is used to help return Windows Edition. }
Function TCSystemInformation.GetOSVerInfo(var Info: TOSVersionInfoEx): Boolean;
begin
FillChar(Info, SizeOf(TOSVersionInfoEx), 0);
Info.dwOSVersionInfoSize := SizeOf(TOSVersionInfoEx);
Result := GetVersionEx(TOSVersionInfo(Addr(Info)^));
if (not Result) then
begin
FillChar(Info, SizeOf(TOSVersionInfoEx), 0);
Info.dwOSVersionInfoSize := SizeOf(TOSVersionInfoEx);
Result := GetVersionEx(TOSVersionInfo(Addr(Info)^));
if (not Result) then
Info.dwOSVersionInfoSize := 0;
end;
end;
{ TCSystemInformation.GetWinEdition
This routine will return the windows edition. }
Function TCSystemInformation.GetWinEdition : String;
Var
Info : TOSVersionInfoEx;
Begin
If (Not GetOsVerInfo(Info)) Then
Exit;
If Info.dwPlatformId = VER_PLATFORM_WIN32_NT Then
begin
if (Info.dwOSVersionInfoSize >= SizeOf(TOSVersionInfoEx)) then
begin
If (Info.wProductType = VER_NT_WORKSTATION) Then
begin
if (Info.dwMajorVersion = 4) Then
Result := 'Workstation 4.0'
else if (Info.wSuiteMask and VER_SUITE_PERSONAL <> 0) Then
Result := 'Home Edition'
else
Result := 'Professional';
end;
end;
end;
End;
{ TCSystemInformation.GetOS
This routine is used to retrive the Operating System, }
Function TCSystemInformation.GetOS: String;
Var
OSVersionInfo :TOSVersionInfo;
Begin
OSVersionInfo.dwOSVersionInfoSize := SizeOf(TOSVersionInfo);
GetVersionEx(OSVersionInfo);
If (OSVersionInfo.dwMajorVersion = 4) And
(OSVersionInfo.dwMinorVersion = 0) Then
Begin
If (OSVersionInfo.dwPlatformId = VER_PLATFORM_WIN32_NT) Then Result := 'Windows 95';
If (OSVersionInfo.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS) Then Result := 'Windows NT';
End
Else If (OSVersionInfo.dwMajorVersion = 4) And (OSVersionInfo.dwMinorVersion = 10) Then Result := 'Windows 98'
Else If (OSVersionInfo.dwMajorVersion = 4) And (OSVersionInfo.dwMinorVersion = 90) Then Result := 'Windows ME'
Else If (OSVersionInfo.dwMajorVersion = 5) And (OSVersionInfo.dwMinorVersion = 0) Then Result := 'Windows 2000'
Else If (OSVersionInfo.dwMajorVersion = 5) And (OSVersionInfo.dwMinorVersion = 1) Then Result := 'Windows XP'
Else If (OSVersionInfo.dwMajorVersion = 6) And (OsVersionInfo.dwMinorVersion = 1) Then Result := 'Windows Vista'
Else Result := 'Unknown OS';
End;
{ TCSystemInformation.GetUptime
This routine is used to retrive the uptime. }
Function TCSystemInformation.GetUpTime: string;
const
ticksperday : Integer = 1000 * 60 * 60 * 24;
ticksperhour : Integer = 1000 * 60 * 60;
ticksperminute : Integer = 1000 * 60;
tickspersecond : Integer = 1000;
var
t: Longword;
d, h, m, s: Integer;
begin
t := GetTickCount;
d := t div ticksperday;
Dec(t, d * ticksperday);
h := t div ticksperhour;
Dec(t, h * ticksperhour);
m := t div ticksperminute;
Dec(t, m * ticksperminute);
s := t div tickspersecond;
Result := IntToStr(d) + ' Day(s) ' + IntToStr(h) + ' Hour(s) ' + IntToStr(m) +
' Minute(s) ' + IntToStr(s) + ' Seconds';
end;
{ TCSystemInformation.GetLocalIP
This routine is used to retrive local IP. }
Function TCSystemInformation.GetLocalIP: String;
type
TaPInAddr = Array[0..10] of PInAddr;
PaPInAddr = ^TaPInAddr;
var
phe : PHostEnt;
pptr : PaPInAddr;
Buffer : Array[0..63] of Char;
I : Integer;
GInitData : TWSAData;
begin
WSAStartup($101, GInitData);
Result := '';
GetHostName(Buffer, SizeOf(Buffer));
phe := GetHostByName(buffer);
if phe = nil then Exit;
pPtr := PaPInAddr(phe^.h_addr_list);
I := 0;
while pPtr^[I] <> nil do
begin
Result := inet_ntoa(pptr^[I]^);
Inc(I);
end;
WSACleanup;
end;
{ TCSystemInformation.GetWinVersion
This routine is used to retrive Windows version. }
Function TCSystemInformation.GetWinVersion: String;
Var
Version : DWORD;
MajorVersion : BYTE;
MinorVersion : BYTE;
Begin
Version := GetVersion();
MajorVersion := LOBYTE(LOWORD(Version));
MinorVersion := HIBYTE(LOWORD(Version));
Result := IntToStr(MajorVersion) + '.' + IntToStr(MinorVersion);
End;
{ TCSystemInformation.GetBuild
This routine is used to retrive Build number. }
Function TCSystemInformation.GetBuild: Cardinal;
Var
MajorVersion : BYTE;
MinorVersion : BYTE;
Version : DWORD;
Build : DWORD;
Begin
Version := GetVersion();
MajorVersion := LOBYTE(LOWORD(Version));
MinorVersion := HIBYTE(LOWORD(Version));
If (Version and $80000000) = 0 Then
Build := HIWORD(Version)
else if (MajorVersion < 4) Then
Build := HIWORD(Version) and $7FFF
else
Build := 0;
Result := Build;
End;
{ TCSystemInformation.GetWindowsID
This routine is used to retrive Windows ID. }
Function TCSystemInformation.GetWindowsID: String;
Var
gKEY : HKEY;
gSize : Cardinal;
gRegister : PChar;
Begin
GetMem(gRegister, MAX_PATH + 1);
RegOpenKeyEx(HKEY_LOCAL_MACHINE, 'SoftWare\Microsoft\Windows\CurrentVersion\', 0, KEY_QUERY_VALUE, gKEY);
gSize := 2048;
RegQueryValueEx(gKey, 'ProductID', NIL, NIL, pByte(gRegister), @gSize);
RegCloseKey(gKEY);
Result := pChar(gRegister);
FreeMem(gRegister);
End;
{ TCSystemInformation.GetServicePack
This routine is used to retrive the Service Pack. }
Function TCSystemInformation.GetServicePack: String;
Var
VersionInfo : TOSVersionInfo;
Begin
VersionInfo.dwOSVersionInfoSize := SizeOf(VersionInfo);
GetVersionEx(VersionInfo);
With VersionInfo do
begin
If szCSDVersion <> '' Then
Result := szCSDVersion;
end;
End;
{ TCSystemInformation.FindVolumeSerial
This routine is used to retrive root disk serial number. }
Function TCSystemInformation.FindVolumeSerial(const Drive : PChar): string;
var
VolumeSerialNumber : DWORD;
MaximumComponentLength : DWORD;
FileSystemFlags : DWORD;
SerialNumber : String;
begin
Result := '';
GetVolumeInformation(Drive, NIL, 0, @VolumeSerialNumber, MaximumComponentLength, FileSystemFlags, NIL, 0);
SerialNumber := IntToHex(HiWord(VolumeSerialNumber), 4) + ' - ' + IntToHex(LoWord(VolumeSerialNumber), 4);
Result := SerialNumber
end;
{ TCSystemInformation.GetDefultBrowser
This routine is used to retrive defult browser. }
Function TCSystemInformation.GetDefultBrowser: String;
Var
gKEY : HKEY;
gSize : Cardinal;
gRegister : pChar;
Begin
GetMem(gRegister, MAX_PATH+1);
RegOpenKeyEx(HKEY_LOCAL_MACHINE, 'Software\Classes\http\shell\open\command', 0, KEY_QUERY_VALUE, gKEY);
gSize := 2048;
RegQueryValueEX(gKEY, '', NIL, NIL, pByte(gRegister), @gSize);
RegCloseKey(gKEY);
Result := ExtractFileName(pChar(gRegister));
Result := ChangeFileExt(pChar(Result), '');
Result := UpperCase(Copy(pChar(Result), 1, 1)) + LowerCase(Copy(pChar(Result), 2, Length(pChar(Result))));
FreeMem(gRegister);
End;
{ TCSystemInformation.GetMACAdress
This routine is used to retrice MAC adress. }
Function TCSystemInformation.GetMACAdress: string;
var
NCB : PNCB;
Adapter : PAdapterStatus;
URetCode : PChar;
RetCode : char;
I : integer;
Lenum : PlanaEnum;
_SystemID : string;
TMPSTR : string;
begin
Result := '';
_SystemID := '';
Getmem(NCB, SizeOf(TNCB));
Fillchar(NCB^, SizeOf(TNCB), 0);
Getmem(Lenum, SizeOf(TLanaEnum));
Fillchar(Lenum^, SizeOf(TLanaEnum), 0);
Getmem(Adapter, SizeOf(TAdapterStatus));
Fillchar(Adapter^, SizeOf(TAdapterStatus), 0);
Lenum.Length := chr(0);
NCB.ncb_command := chr(NCBENUM);
NCB.ncb_buffer := Pointer(Lenum);
NCB.ncb_length := SizeOf(Lenum);
RetCode := Netbios(NCB);
i := 0;
repeat
Fillchar(NCB^, SizeOf(TNCB), 0);
Ncb.ncb_command := chr(NCBRESET);
Ncb.ncb_lana_num := lenum.lana[I];
RetCode := Netbios(Ncb);
Fillchar(NCB^, SizeOf(TNCB), 0);
Ncb.ncb_command := chr(NCBASTAT);
Ncb.ncb_lana_num := lenum.lana[I];
Ncb.ncb_callname := '* ';
Ncb.ncb_buffer := Pointer(Adapter);
Ncb.ncb_length := SizeOf(TAdapterStatus);
RetCode := Netbios(Ncb);
if (RetCode = chr(0)) or (RetCode = chr(6)) then
begin
_SystemId := IntToHex(Ord(Adapter.adapter_address[0]), 2) + '-' +
IntToHex(Ord(Adapter.adapter_address[1]), 2) + '-' +
IntToHex(Ord(Adapter.adapter_address[2]), 2) + '-' +
IntToHex(Ord(Adapter.adapter_address[3]), 2) + '-' +
IntToHex(Ord(Adapter.adapter_address[4]), 2) + '-' +
IntToHex(Ord(Adapter.adapter_address[5]), 2);
end;
Inc(i);
until (I >= Ord(Lenum.Length)) or (_SystemID <> '00-00-00-00-00-00');
FreeMem(NCB);
FreeMem(Adapter);
FreeMem(Lenum);
GetMacAdress := _SystemID;
end;
end.
|
unit MemoFrame;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, DemoInterfaces;
type
TAMemoFrame = class(TFrame, IClipboardProvider)
Memo1: TMemo;
procedure Memo1Enter(Sender: TObject);
procedure Memo1Exit(Sender: TObject);
private
{ Private declarations }
FLogger : ILogger;
protected
function CanCopy: Boolean;
function CanCut: Boolean;
function CanPaste: Boolean;
procedure Copy;
procedure Cut;
procedure Paste;
{ Public declarations }
public
procedure SetLogger(const logger : ILogger);
end;
implementation
uses
Clipbrd,
ClipbrdController;
{$R *.dfm}
function TAMemoFrame.CanCopy: Boolean;
begin
result := Memo1.SelLength > 0;
end;
function TAMemoFrame.CanCut: Boolean;
begin
result := Memo1.SelLength > 0;
end;
function TAMemoFrame.CanPaste: Boolean;
begin
result := Clipboard.AsText <> '';
end;
procedure TAMemoFrame.Copy;
begin
FLogger.Log(Debug, 'MemoFrame Copy');
Memo1.CopyToClipboard;
end;
procedure TAMemoFrame.Cut;
begin
FLogger.Log(Debug, 'MemoFrame Cut');
Memo1.CopyToClipboard;
Memo1.SelText := '';
end;
procedure TAMemoFrame.Memo1Enter(Sender: TObject);
begin
ClipboardController.SetProvider(Self);
end;
procedure TAMemoFrame.Memo1Exit(Sender: TObject);
begin
ClipboardController.UnsetProvider(Self);
end;
procedure TAMemoFrame.Paste;
begin
FLogger.Log(Debug, 'MemoFrame Paste');
Memo1.SelText := Clipboard.AsText;;
end;
procedure TAMemoFrame.SetLogger(const logger: ILogger);
begin
FLogger := logger;
end;
end.
|
unit SOLID.ComLSP;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs;
type
IArquivo = interface
procedure LerArquivo;
end;
TArquivoDelimitado = class(TInterfacedObject, IArquivo)
protected
procedure SetDelimiter; virtual; abstract;
public
procedure LerArquivo;
end;
TArquivoCSV = class(TArquivoDelimitado)
protected
procedure SetDelimiter; override;
end;
TArquivoTXT = class(TArquivoDelimitado)
protected
procedure SetDelimiter; override;
end;
TArquivoEstruturado = class(TInterfacedObject, IArquivo)
public
procedure LerArquivo;
end;
TArquivoJSON = class(TArquivoEstruturado)
protected
procedure SetDelimiter; override;
end;
TFormSemLSP = class(TForm)
public
procedure Exemplo;
end;
var
FormSemLSP: TFormSemLSP;
implementation
uses
System.Generics.Collections;
{$R *.dfm}
{ TFormSemLSP }
procedure TFormSemLSP.Exemplo;
var
Lista: TList<IArquivo>;
Arquivo: IArquivo;
begin
Lista := TList<IArquivo>.Create;
Lista.Add(TArquivoTXT.Create);
Lista.Add(TArquivoTXT.Create);
Lista.Add(TArquivoCSV.Create);
Lista.Add(TArquivoCSV.Create);
Lista.Add(TArquivoJSON.Create);
Lista.Add(TArquivoJSON.Create);
for Arquivo in Lista do
Arquivo.LerArquivo;
end;
end.
|
unit volba_f;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TForm1 = class(TForm)
CheckBox1: TCheckBox;
CheckBox2: TCheckBox;
CheckBox3: TCheckBox;
RadioButton1: TRadioButton;
Memo1: TMemo;
Arial: TRadioButton;
RadioButton3: TRadioButton;
procedure CheckBox1Click(Sender: TObject);
procedure CheckBox2Click(Sender: TObject);
procedure CheckBox3Click(Sender: TObject);
procedure RadioButton1Click(Sender: TObject);
procedure ArialClick(Sender: TObject);
procedure RadioButton3Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.ArialClick(Sender: TObject);
begin
Memo1.Font.Name := 'Arial';
end;
procedure TForm1.CheckBox1Click(Sender: TObject);
begin
if Checkbox1.Checked then Memo1.Font.Style := Memo1.Font.Style + [fsBold]
else Memo1.Font.Style := Memo1.Font.Style - [fsBold];
end;
procedure TForm1.CheckBox2Click(Sender: TObject);
begin
if Checkbox2.Checked then Memo1.Font.Style := Memo1.Font.Style + [fsItalic]
else Memo1.Font.Style := Memo1.Font.Style - [fsItalic];
end;
procedure TForm1.CheckBox3Click(Sender: TObject);
begin
if Checkbox3.Checked then Memo1.Font.Style := Memo1.Font.Style + [fsUnderline]
else Memo1.Font.Style := Memo1.Font.Style - [fsUnderline];
end;
procedure TForm1.RadioButton1Click(Sender: TObject);
begin
Memo1.Font.Name := 'Times New Roman';
end;
procedure TForm1.RadioButton3Click(Sender: TObject);
begin
Memo1.Font.Name := 'Comic Sans MS';
end;
end.
|
program numberRepresentationTest.pas;
{$BITPACKING ON}
Uses Math;
const cantBits = 32;
type TByteBits = bitpacked array[0..cantBits-1] of Boolean;
type TPByteBits = ^TByteBits;
var a:Integer;
b:single;
p,q:TPByteBits;
(* Imprime una secuencia de bits (arreglo compactado de booleanos) *)
procedure PrintBits(p:TPByteBits);
var i:integer;
begin
for i:=cantBits-1 downto 0 do begin
if p^[i] then write('1')
else write('0');
end;
end;
begin (* Programa *)
a:= 255;
b:= 0.0000075;
p:=@a;
q:=@b;
writeln('-------Int 16bits------');
PrintBits(p);writeln('');
writeln('-------Real 32bits------');
PrintBits(q);writeln('');
writeln('-----------------------');
end.
|
unit Stack;
interface
uses classes;
const
MAX_STACK_SIZE = 100;
type
TIntStack = class(TObject)
private
Data: array[1..MAX_STACK_SIZE] of integer;
Top: integer;
public
constructor Create;
destructor Destroy; override;
procedure Push(value: integer);
procedure Clear;
function Pop: integer;
end;
implementation
{ TIntStack }
procedure TIntStack.Clear;
begin
Top := 0;
end;
constructor TIntStack.Create;
begin
Clear;
end;
destructor TIntStack.Destroy;
begin
inherited;
end;
function TIntStack.Pop: integer;
begin
if Top>0 then
begin
Result := Data[Top];
Dec(Top);
end else
raise EInvalidOperation.Create('Stack is Empty');
end;
procedure TIntStack.Push(value: integer);
begin
if Top<MAX_STACK_SIZE then
begin
Inc(Top);
Data[Top] := value;
end else
raise EInvalidOperation.Create('Stack is Full');
end;
end.
|
{$ifdef license}
(*
Copyright 2020 ChapmanWorld LLC ( https://chapmanworld.com )
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be
used to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*)
{$endif}
unit cwThreading.Internal.TaskPool.Standard;
{$ifdef fpc}
{$mode delphiunicode}
{$modeswitch nestedprocvars}
{$endif}
interface
uses
cwThreading
, cwThreading.Internal
;
type
TTaskPool = class( TInterfacedObject, ITaskPool )
private
fThreadPool: IThreadPool;
fTaskSets: ITaskSetCollection;
protected
procedure ThreadHandler( const Thread: IThread );
strict private //- IThreadPool -//
{$ifndef fpc}
procedure AddTaskSet( const Tasks: array of ITask; const WhenDone: TOnComplete ); overload;
{$else}
procedure AddTaskSet( const Tasks: array of ITask; const WhenDone: TOnCompleteGlobal ); overload;
procedure AddTaskSet( const Tasks: array of ITask; const WhenDone: TOnCompleteOfObject ); overload;
procedure AddTaskSet( const Tasks: array of ITask; const WhenDone: TOnCompleteNested ); overload;
{$endif}
function getThreadCount: nativeuint;
procedure AddTaskSet( const Tasks: array of ITask ); overload;
public
constructor Create( const ThreadCount: nativeuint ); reintroduce;
destructor Destroy; override;
end;
implementation
uses
cwThreading.Internal.TaskSet.Standard
, cwThreading.Internal.TaskSetCollection.Standard
, cwThreading.Internal.ThreadPool.Standard
;
procedure TTaskPool.ThreadHandler( const Thread: IThread );
var
Task: ITaskRecord;
begin
Task := nil;
repeat
Thread.Acquire;
try
Task := fTaskSets.getNextTask;
if not assigned(Task) then begin
Thread.Sleep;
end;
if Thread.TerminateFlag then exit;
finally
Thread.Release;
end;
Thread.Wake;
if assigned(Task) then begin
Task.Execute;
end;
until False;
end;
{$ifndef fpc}
procedure TTaskPool.AddTaskSet(const Tasks: array of ITask; const WhenDone: TOnComplete);
begin
fTasksets.AddTaskSet( TTaskSet.Create( Tasks, WhenDone) );
fThreadPool.Wake;
end;
{$endif}
{$ifdef fpc}
procedure TTaskPool.AddTaskSet( const Tasks: array of ITask; const WhenDone: TOnCompleteGlobal ); overload;
begin
fTasksets.AddTaskSet( TTaskSet.Create( Tasks, WhenDone ) );
fThreadPool.Wake;
end;
{$endif}
{$ifdef fpc}
procedure TTaskPool.AddTaskSet( const Tasks: array of ITask; const WhenDone: TOnCompleteOfObject ); overload;
begin
fTasksets.AddTaskSet( TTaskSet.Create( Tasks, WhenDone) );
fThreadPool.Wake;
end;
{$endif}
{$ifdef fpc}
procedure TTaskPool.AddTaskSet( const Tasks: array of ITask; const WhenDone: TOnCompleteNested ); overload;
begin
fTasksets.AddTaskSet( TTaskSet.Create( Tasks, WhenDone ) );
fThreadPool.Wake;
end;
{$endif}
function TTaskPool.getThreadCount: nativeuint;
begin
Result := fThreadPool.getThreadCount;
end;
procedure TTaskPool.AddTaskSet( const Tasks: array of ITask );
begin
fTasksets.AddTaskSet( TTaskSet.Create( Tasks ) );
fThreadPool.Wake;
end;
constructor TTaskPool.Create( const ThreadCount: nativeuint );
begin
inherited Create;
fTaskSets := TTaskSetCollection.Create;
fThreadPool := TThreadPool.Create;
fThreadPool.AddThreads( ThreadCount, ThreadHandler );
end;
destructor TTaskPool.Destroy;
begin
fThreadPool.Terminate;
fThreadPool := nil;
fTaskSets := nil;
inherited Destroy;
end;
end.
|
unit dll_kernel32_mem;
interface
uses
atmcmbaseconst, winconst, wintype;
type
PMemoryBasicInfo = ^TMemoryBasicInfo;
TMemoryBasicInfo = record
BaseAddress : Pointer;
AllocationBase : Pointer;
AllocationProtect : DWORD;
RegionSize : DWORD;
State : DWORD;
Protect : DWORD;
Type_9 : DWORD;
end;
{
如果堆中没有充足的自由空间去满足我们的需求,LocalAlloc返回NULL。因为NULL被使用去表明一个错误,虚拟地址zero从不被分配。因此,很容易去检测NULL指针的使用
如果函数成功的话,它至少会分配我们指定大小的内存。如果分配给我们的数量多于我们指定的话,这个进程能使用整个数量的内存
使用LocalSize函数去检测被分配的字节数
}
function LocalAlloc(uFlags, uBytes: UINT): HLOCAL; stdcall; external kernel32 name 'LocalAlloc';
function LocalLock(AMem: HLOCAL): Pointer; stdcall; external kernel32 name 'LocalLock';
function LocalReAlloc(AMem: HLOCAL; uBytes, uFlags: UINT): HLOCAL; stdcall; external kernel32 name 'LocalReAlloc';
function LocalUnlock(AMem: HLOCAL): BOOL; stdcall; external kernel32 name 'LocalUnlock';
function LocalSize(AMem: HLOCAL): UINT; stdcall; external kernel32 name 'LocalSize';
function LocalFree(AMem: HLOCAL): HLOCAL; stdcall; external kernel32 name 'LocalFree';
function LocalCompact(uMinFree: UINT): UINT; stdcall; external kernel32 name 'LocalCompact';
function LocalShrink(AMem: HLOCAL; cbNewSize: UINT): UINT; stdcall; external kernel32 name 'LocalShrink';
function LocalFlags(AMem: HLOCAL): UINT; stdcall; external kernel32 name 'LocalFlags';
function VirtualProtect(lpAddress: Pointer; dwSize, flNewProtect: DWORD;
lpflOldProtect: Pointer): BOOL; stdcall; overload; external kernel32 name 'VirtualProtect';
function VirtualProtect(lpAddress: Pointer; dwSize, flNewProtect: DWORD;
var OldProtect: DWORD): BOOL; stdcall; overload; external kernel32 name 'VirtualProtect';
function VirtualProtectEx(hProcess: THandle; lpAddress: Pointer;
dwSize, flNewProtect: DWORD; lpflOldProtect: Pointer): BOOL; stdcall; overload;
external kernel32 name 'VirtualProtectEx';
function VirtualProtectEx(hProcess: THandle; lpAddress: Pointer;
dwSize, flNewProtect: DWORD; var OldProtect: DWORD): BOOL; stdcall; overload;
external kernel32 name 'VirtualProtectEx';
function VirtualLock(lpAddress: Pointer; dwSize: DWORD): BOOL; stdcall; external kernel32 name 'VirtualLock';
function VirtualUnlock(lpAddress: Pointer; dwSize: DWORD): BOOL; stdcall; external kernel32 name 'VirtualUnlock';
{ VirtualAlloc 该函数的功能是在调用进程的虚地址空间,预定或者提交一部分页
如果用于内存分配的话,并且分配类型未指定MEM_RESET,则系统将自动设置为0;
flAllocationType:
MEM_COMMIT 在内存或者指定的磁盘页文件(虚拟内存文件)中分配一物理存储区域 函数初始化这个区域为0
MEM_PHYSICAL 该类型必须和MEM_RESERVE一起使用 分配一块具有读写功能的物理内存区
MEM_RESERVE 保留虚拟地址空间以便以后提交。
MEM_RESET
MEM_TOP_DOWN 告诉系统从最高可允许的虚拟地址开始映射应用程序。
MEM_WRITE_WATCH
访问类型
PAGE_READONLY 该区域为只读。如果应用程序试图访问区域中的页的时候,将会被拒绝访问PAGE_READWRITE 区域可被应用程序读写
PAGE_EXECUTE 区域包含可被系统执行的代码。试图读写该区域的操作将被拒绝。
PAGE_EXECUTE_READ 区域包含可执行代码,应用程序可以读该区域。
PAGE_EXECUTE_READWRITE 区域包含可执行代码,应用程序可以读写该区域。
PAGE_GUARD 区域第一次被访问时进入一个STATUS_GUARD_PAGE异常,这个标志要和其他保护标志合并使用,表明区域被第一次访问的权限
PAGE_NOACCESS 任何访问该区域的操作将被拒绝
PAGE_NOCACHE RAM中的页映射到该区域时将不会被微处理器缓存(cached)
注:PAGE_GUARD和PAGE_NOCHACHE标志可以和其他标志合并使用以进一步指定页的特征。
PAGE_GUARD标志指定了一个防护页(guard page),即当一个页被提交时会因第一
次被访问而产生一个one-shot异常,接着取得指定的访问权限。PAGE_NOCACHE防止
当它映射到虚拟页的时候被微处理器缓存。这个标志方便设备驱动使用直接内存访
问方式(DMA)来共享内存块
}
function VirtualAlloc(lpvAddress: Pointer; dwSize, flAllocationType, flProtect: DWORD): Pointer; stdcall; external kernel32 name 'VirtualAlloc';
function VirtualAllocEx(hProcess: THandle; lpAddress: Pointer;
dwSize, flAllocationType: DWORD; flProtect: DWORD): Pointer; stdcall; external kernel32 name 'VirtualAllocEx';
function VirtualFree(lpAddress: Pointer; dwSize, dwFreeType: DWORD): BOOL; stdcall; external kernel32 name 'VirtualFree';
function VirtualFreeEx(hProcess: THandle; lpAddress: Pointer;
dwSize, dwFreeType: DWORD): Pointer; stdcall; external kernel32 name 'VirtualFreeEx';
function VirtualQuery(lpAddress: Pointer; var lpBuffer: TMemoryBasicInfo; dwLength: DWORD): DWORD; stdcall; external kernel32 name 'VirtualQuery';
function VirtualQueryEx(hProcess: THandle; lpAddress: Pointer;
var lpBuffer: TMemoryBasicInfo; dwLength: DWORD): DWORD; stdcall; external kernel32 name 'VirtualQueryEx';
{该函数从堆中分配一定数目的字节数.Win32内存管理器并不提供
相互分开的局部和全局堆.提供这个函数只是为了与16位的Windows相兼容}
function GlobalAlloc(uFlags: UINT; dwBytes: DWORD): HGLOBAL; stdcall; external kernel32 name 'GlobalAlloc';
function GlobalReAlloc(AMem: HGLOBAL; dwBytes: DWORD; uFlags: UINT): HGLOBAL; stdcall; external kernel32 name 'GlobalReAlloc';
function GlobalLock(AMem: HGLOBAL): Pointer; stdcall; external kernel32 name 'GlobalLock';
function GlobalSize(AMem: HGLOBAL): DWORD; stdcall; external kernel32 name 'GlobalSize';
function GlobalHandle(AMem: Pointer): HGLOBAL; stdcall; external kernel32 name 'GlobalHandle';
function GlobalUnlock(AMem: HGLOBAL): BOOL; stdcall; external kernel32 name 'GlobalUnlock';
function GlobalFree(AMem: HGLOBAL): HGLOBAL; stdcall; external kernel32 name 'GlobalFree';
function GlobalCompact(dwMinFree: DWORD): UINT; stdcall; external kernel32 name 'GlobalCompact';
procedure GlobalFix(AMem: HGLOBAL); stdcall; external kernel32 name 'GlobalFix';
procedure GlobalUnfix(AMem: HGLOBAL); stdcall; external kernel32 name 'GlobalUnfix';
// Not necessary and has no effect.
function GlobalWire(AMem: HGLOBAL): Pointer; stdcall; external kernel32 name 'GlobalWire';
function GlobalUnWire(AMem: HGLOBAL): BOOL; stdcall; external kernel32 name 'GlobalUnWire';
{ Heap Functions }
function GetProcessHeap: THandle;stdcall; external kernel32 name 'GetProcessHeap';
function GetProcessHeaps(NumberOfHeaps: DWORD; ProcessHeaps: PHandle): DWORD;stdcall; external kernel32 name 'GetProcessHeaps';
function HeapQueryInformation(HeapHandle: THANDLE; HeapInformationClass: Pointer): BOOL;stdcall; external kernel32 name 'HeapQueryInformation';
function HeapSetInformation(HeapHandle: THANDLE; HeapInformationClass: Pointer): BOOL;stdcall; external kernel32 name 'HeapSetInformation';
function HeapCreate(flOptions, dwInitialSize, dwMaximumSize: DWORD): THandle; stdcall; external kernel32 name 'HeapCreate';
function HeapDestroy(AHeap: THandle): BOOL; stdcall; external kernel32 name 'HeapDestroy';
function HeapAlloc(AHeap: THandle; dwFlags, dwBytes: DWORD): Pointer; stdcall; external kernel32 name 'HeapAlloc';
function HeapReAlloc(AHeap: THandle; dwFlags: DWORD; lpMem: Pointer; dwBytes: DWORD): Pointer; stdcall; external kernel32 name 'HeapReAlloc';
function HeapFree(AHeap: THandle; dwFlags: DWORD; lpMem: Pointer): BOOL; stdcall; external kernel32 name 'HeapFree';
function HeapSize(AHeap: THandle; dwFlags: DWORD; lpMem: Pointer): DWORD; stdcall; external kernel32 name 'HeapSize';
function HeapValidate(AHeap: THandle; dwFlags: DWORD; lpMem: Pointer): BOOL; stdcall; external kernel32 name 'HeapValidate';
function HeapCompact(AHeap: THandle; dwFlags: DWORD): UINT; stdcall; external kernel32 name 'HeapCompact';
function HeapLock(AHeap: THandle): BOOL; stdcall; external kernel32 name 'HeapLock';
function HeapUnlock(AHeap: THandle): BOOL; stdcall; external kernel32 name 'HeapUnlock';
function HeapWalk(AHeap: THandle; var lpEntry: TProcessHeapEntry): BOOL; stdcall; external kernel32 name 'HeapWalk';
{
一般的程序都是在运行前已经编译好的,因此修改指令的机会比较少,但在软件的防确解里,
倒是使用很多。当修改指令之后,怎么样才能让CPU去执行新的指令呢?这样就需要使用函数
FlushInstructionCache来把缓存里的数据重写回主内存里去,让CPU重新加载新的指令,才能执行新的指令
}
function FlushInstructionCache(hProcess: THandle; const lpBaseAddress: Pointer; dwSize: DWORD): BOOL; stdcall; external kernel32 name 'FlushInstructionCache';
function ReadProcessMemory(hProcess: THandle; const lpBaseAddress: Pointer; lpBuffer: Pointer;
nSize: DWORD; var lpNumberOfBytesRead: DWORD): BOOL; stdcall; external kernel32 name 'ReadProcessMemory';
function WriteProcessMemory(hProcess: THandle; const lpBaseAddress: Pointer; lpBuffer: Pointer;
nSize: DWORD; var lpNumberOfBytesWritten: DWORD): BOOL; stdcall; external kernel32 name 'WriteProcessMemory';
{ http://msdn.microsoft.com/en-us/library/windows/desktop/aa366781(v=vs.85).aspx#awe_functions }
{ AWE Functions }
function AllocateUserPhysicalPages(AProcess: THandle; NumberOfPages: Pointer; UserPfnArray: Pointer): BOOL; stdcall;
external kernel32 name 'AllocateUserPhysicalPages';
function FreeUserPhysicalPages(AProcess: THandle; NumberOfPages: Pointer; UserPfnArray: Pointer): BOOL; stdcall;
external kernel32 name 'FreeUserPhysicalPages';
function MapUserPhysicalPages(lpAddress: Pointer; NumberOfPages: Pointer; UserPfnArray: Pointer): BOOL; stdcall;
external kernel32 name 'MapUserPhysicalPages';
{ 64-bit Windows on Itanium-based systems: Due to the difference in page sizes,
MapUserPhysicalPagesScatter is not supported for 32-bit applications. }
function MapUserPhysicalPagesScatter(VirtualAddresses: Pointer; NumberOfPages: Pointer; PageArray: Pointer): BOOL; stdcall;
external kernel32 name 'MapUserPhysicalPagesScatter';
type
TwDLLKernel_Mem = record
LocalAlloc: function (uFlags, uBytes: UINT): HLOCAL; stdcall;
LocalLock: function (hMem: HLOCAL): Pointer; stdcall;
LocalReAlloc: function (hMem: HLOCAL; uBytes, uFlags: UINT): HLOCAL; stdcall;
LocalUnlock: function (hMem: HLOCAL): BOOL; stdcall;
LocalFree: function (hMem: HLOCAL): HLOCAL; stdcall;
LocalCompact: function (uMinFree: UINT): UINT; stdcall;
VirtualProtect: function (lpAddress: Pointer; dwSize, flNewProtect: DWORD; lpflOldProtect: Pointer): BOOL; stdcall;
// VirtualProtect: function (lpAddress: Pointer; dwSize, flNewProtect: DWORD; var OldProtect: DWORD): BOOL; stdcall; overload;
VirtualProtectEx: function (hProcess: THandle; lpAddress: Pointer; dwSize, flNewProtect: DWORD; lpflOldProtect: Pointer): BOOL; stdcall;
// VirtualProtectEx: function (hProcess: THandle; lpAddress: Pointer; dwSize, flNewProtect: DWORD; var OldProtect: DWORD): BOOL; stdcall; overload;
VirtualLock: function (lpAddress: Pointer; dwSize: DWORD): BOOL; stdcall;
VirtualUnlock: function (lpAddress: Pointer; dwSize: DWORD): BOOL; stdcall;
VirtualAlloc: function (lpvAddress: Pointer; dwSize, flAllocationType, flProtect: DWORD): Pointer; stdcall;
VirtualAllocEx: function (hProcess: THandle; lpAddress: Pointer; dwSize, flAllocationType: DWORD; flProtect: DWORD): Pointer; stdcall;
VirtualFree: function (lpAddress: Pointer; dwSize, dwFreeType: DWORD): BOOL; stdcall;
VirtualFreeEx: function (hProcess: THandle; lpAddress: Pointer; dwSize, dwFreeType: DWORD): Pointer; stdcall;
VirtualQuery: function (lpAddress: Pointer; var lpBuffer: TMemoryBasicInfo; dwLength: DWORD): DWORD; stdcall;
VirtualQueryEx: function (hProcess: THandle; lpAddress: Pointer; var lpBuffer: TMemoryBasicInfo; dwLength: DWORD): DWORD; stdcall;
GlobalAlloc: function (uFlags: UINT; dwBytes: DWORD): HGLOBAL; stdcall;
GlobalReAlloc: function (hMem: HGLOBAL; dwBytes: DWORD; uFlags: UINT): HGLOBAL; stdcall;
GlobalLock: function (hMem: HGLOBAL): Pointer; stdcall;
GlobalHandle: function (Mem: Pointer): HGLOBAL; stdcall;
GlobalUnlock: function (hMem: HGLOBAL): BOOL; stdcall;
GlobalFree: function (hMem: HGLOBAL): HGLOBAL; stdcall;
GlobalCompact: function (dwMinFree: DWORD): UINT; stdcall;
GlobalFix: procedure (hMem: HGLOBAL); stdcall;
GlobalUnfix: procedure (hMem: HGLOBAL); stdcall;
HeapCreate: function (flOptions, dwInitialSize, dwMaximumSize: DWORD): THandle; stdcall;
HeapDestroy: function (hHeap: THandle): BOOL; stdcall;
HeapAlloc: function (hHeap: THandle; dwFlags, dwBytes: DWORD): Pointer; stdcall;
HeapReAlloc: function (hHeap: THandle; dwFlags: DWORD; lpMem: Pointer; dwBytes: DWORD): Pointer; stdcall;
HeapFree: function (hHeap: THandle; dwFlags: DWORD; lpMem: Pointer): BOOL; stdcall;
HeapSize: function (hHeap: THandle; dwFlags: DWORD; lpMem: Pointer): DWORD; stdcall;
HeapValidate: function (hHeap: THandle; dwFlags: DWORD; lpMem: Pointer): BOOL; stdcall;
HeapCompact: function (hHeap: THandle; dwFlags: DWORD): UINT; stdcall;
HeapLock: function (hHeap: THandle): BOOL; stdcall;
HeapUnlock: function (hHeap: THandle): BOOL; stdcall;
HeapWalk: function (hHeap: THandle; var lpEntry: TProcessHeapEntry): BOOL; stdcall;
end;
const
{ Global Memory Flags }
GMEM_FIXED = 0;
GMEM_MOVEABLE = 2;
GMEM_NOCOMPACT = $10;
GMEM_NODISCARD = $20;
GMEM_ZEROINIT = $40;
GMEM_MODIFY = $80;
GMEM_DISCARDABLE = $100;
GMEM_NOT_BANKED = $1000;
GMEM_SHARE = $2000;
GMEM_DDESHARE = $2000;
GMEM_NOTIFY = $4000;
GMEM_LOWER = GMEM_NOT_BANKED;
GMEM_VALID_FLAGS = 32626;
GMEM_INVALID_HANDLE = $8000;
GHND = GMEM_MOVEABLE or GMEM_ZEROINIT;
GPTR = GMEM_FIXED or GMEM_ZEROINIT;
implementation
end.
|
unit TipoFormaEmissao;
interface
type
TTipoFormaEmissao = (feNormal=0, feContingencia=1, feSCAN=2, feDPEC=3, feFSDA=4,
feSVCAN=5, feSVCRS=6, feSVCSP=7, feOffLine=8);
implementation
end.
|
unit uiwindow_wndproc_mouse;
interface
uses
Windows,
Messages,
uiwindow;
function UIWndProcW_Mouse(AUIWindow: PUIWindow; AMsg: UINT; wParam: WPARAM; lParam: LPARAM; var AWndProcResult: LRESULT): Boolean;
implementation
uses
uiview,
uiview_space,
uiwindow_wndproc_paint;
var
Cursor_SizeNS: HCURSOR = 0;
Cursor_SizeWE: HCURSOR = 0;
Cursor_SizeNWSE: HCURSOR = 0;
Cursor_SizeNESW: HCURSOR = 0;
Cursor_SizeAll: HCURSOR = 0;
procedure UpdateHitTestCursor(AHitTest: integer);
begin
if (HTBOTTOM = AHitTest) or
(HTTOP = AHitTest) then
begin
if 0 = Cursor_SizeNS then
Cursor_SizeNS := LoadCursor(0, IDC_SIZENS);
if 0 <> Cursor_SizeNS then
Windows.SetCursor(Cursor_SizeNS);
end;
if (HTLEFT = AHitTest) or
(HTRIGHT = AHitTest) then
begin
if 0 = Cursor_SizeWE then
Cursor_SizeWE := LoadCursor(0, IDC_SIZEWE);
if 0 <> Cursor_SizeWE then
Windows.SetCursor(Cursor_SizeWE);
end;
if (HTTOPLEFT = AHitTest) or
(HTBOTTOMRIGHT = AHitTest) then
begin
if 0 = Cursor_SizeNWSE then
Cursor_SizeNWSE := LoadCursor(0, IDC_SIZENWSE);
if 0 <> Cursor_SizeNWSE then
Windows.SetCursor(Cursor_SizeNWSE);
end;
if (HTTOPRIGHT = AHitTest) or
(HTBOTTOMLEFT = AHitTest) then
begin
if 0 = Cursor_SizeNESW then
Cursor_SizeNESW := LoadCursor(0, IDC_SIZENESW);
if 0 <> Cursor_SizeNESW then
Windows.SetCursor(Cursor_SizeNESW);
end;
if HTCLIENT = AHitTest then
begin
if 0 = Cursor_SizeAll then
Cursor_SizeAll := LoadCursor(0, IDC_SIZEALL);
if 0 <> Cursor_SizeAll then
Windows.SetCursor(Cursor_SizeAll);
end;
end;
function WndProcW_WMLButtonDown(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT;
begin
AUIWindow.WMLButtonDown_CursorPoint := TSmallPoint(lParam);
AUIWindow.TestFocusUIView := nil;
AUIWindow.FocusMode := POINT_HITTEST(@AUIWindow.TestUIView.Space.Layout, AUIWindow.WMLButtonDown_CursorPoint);
if HTNOWHERE <> AUIWindow.FocusMode then
begin
UpdateHitTestCursor(AUIWindow.FocusMode);
AUIWindow.TestFocusUIView := @AUIWindow.TestUIView;
AUIWindow.DragStartRect.Left := AUIWindow.TestUIView.Space.Layout.Left;
AUIWindow.DragStartRect.Top := AUIWindow.TestUIView.Space.Layout.Top;
AUIWindow.DragStartRect.Right := AUIWindow.TestUIView.Space.Layout.Right;
AUIWindow.DragStartRect.Bottom := AUIWindow.TestUIView.Space.Layout.Bottom;
end;
if nil = AUIWindow.TestFocusUIView then
begin
if 20 > TSmallPoint(lParam).y then
begin
SendMessageW(AUIWindow.BaseWnd.UIWndHandle, WM_SYSCOMMAND, SC_MOVE or HTCaption, 0);
//SendMessageW(AUIWindow.BaseWnd.UIWndHandle, WM_NCLButtonDown, HTCaption, GetMessagePos);
AUIWindow.IsDragStarting := False;
end else
begin
AUIWindow.DragStartRect.Left := TSmallPoint(lParam).x;
AUIWindow.DragStartRect.Top := TSmallPoint(lParam).y;
AUIWindow.IsDragStarting := True;
end;
end;
Result := DefWindowProcW(AUIWindow.BaseWnd.UIWndHandle, WM_LBUTTONDOWN, wParam, lParam);
end;
function WndProcW_WMLButtonUp(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT;
begin
if nil = AUIWindow.TestFocusUIView then
begin
if AUIWindow.IsDragStarting then
begin
AUIWindow.IsDragStarting := false;
UIWindowPaint(AUIWindow);
end;
end else
begin
AUIWindow.TestFocusUIView := nil;
UIWindowPaint(AUIWindow);
end;
Result := DefWindowProcW(AUIWindow.BaseWnd.UIWndHandle, WM_LBUTTONUP, wParam, lParam);
end;
function WndProcW_WMLButtonDblClk(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT;
begin
Result := DefWindowProcW(AUIWindow.BaseWnd.UIWndHandle, WM_LBUTTONDBLCLK, wParam, lParam);
end;
function WndProcW_WMRButtonUp(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT;
begin
Result := DefWindowProcW(AUIWindow.BaseWnd.UIWndHandle, WM_RBUTTONUP, wParam, lParam);
end;
function WndProcW_WMRButtonDown(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT;
begin
Result := DefWindowProcW(AUIWindow.BaseWnd.UIWndHandle, WM_RBUTTONDOWN, wParam, lParam);
end;
function WndProcW_WMRButtonDblClk(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT;
begin
Result := DefWindowProcW(AUIWindow.BaseWnd.UIWndHandle, WM_RBUTTONDBLCLK, wParam, lParam);
end;
function WndProcW_WMMButtonUp(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT;
begin
Result := DefWindowProcW(AUIWindow.BaseWnd.UIWndHandle, WM_MBUTTONUP, wParam, lParam);
end;
function WndProcW_WMMButtonDown(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT;
begin
Result := DefWindowProcW(AUIWindow.BaseWnd.UIWndHandle, WM_MBUTTONDOWN, wParam, lParam);
end;
function WndProcW_WMMButtonDblClk(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT;
begin
Result := DefWindowProcW(AUIWindow.BaseWnd.UIWndHandle, WM_MBUTTONDBLCLK, wParam, lParam);
end;
function WndProcW_WMMouseMove(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT;
var
tmpHitTest: integer;
begin
AUIWindow.WMMouseMove_CursorPoint := TSmallPoint(lParam);
if nil <> AUIWindow.TestFocusUIView then
begin
if HTCLIENT = AUIWindow.FocusMode then
begin
AUIWindow.TestFocusUIView.Space.Layout.Left := AUIWindow.DragStartRect.Left + AUIWindow.WMMouseMove_CursorPoint.x - AUIWindow.WMLButtonDown_CursorPoint.x;
AUIWindow.TestFocusUIView.Space.Layout.Right := AUIWindow.TestFocusUIView.Space.Layout.Left + AUIWindow.TestFocusUIView.Space.Shape.Width;
AUIWindow.TestFocusUIView.Space.Layout.Top := AUIWindow.DragStartRect.Top + AUIWindow.WMMouseMove_CursorPoint.y - AUIWindow.WMLButtonDown_CursorPoint.y;
AUIWindow.TestFocusUIView.Space.Layout.Bottom := AUIWindow.TestFocusUIView.Space.Layout.Top + AUIWindow.TestFocusUIView.Space.Shape.Height;
end;
if HTRIGHT = AUIWindow.FocusMode then
begin
UpdateUISpaceWidth(@AUIWindow.TestFocusUIView.Space, AUIWindow.DragStartRect.Right - AUIWindow.DragStartRect.Left +
AUIWindow.WMMouseMove_CursorPoint.x - AUIWindow.WMLButtonDown_CursorPoint.x);
end;
if HTLEFT = AUIWindow.FocusMode then
begin
AUIWindow.TestFocusUIView.Space.Layout.LEFT := AUIWindow.DragStartRect.LEFT +
AUIWindow.WMMouseMove_CursorPoint.x - AUIWindow.WMLButtonDown_CursorPoint.x;
UpdateUISpaceWidth(@AUIWindow.TestFocusUIView.Space, AUIWindow.DragStartRect.Right -
AUIWindow.TestFocusUIView.Space.Layout.Left);
end;
if HTBOTTOM = AUIWindow.FocusMode then
begin
UpdateUISpaceHeight(@AUIWindow.TestFocusUIView.Space, AUIWindow.DragStartRect.Bottom - AUIWindow.DragStartRect.Top +
AUIWindow.WMMouseMove_CursorPoint.y - AUIWindow.WMLButtonDown_CursorPoint.y);
end;
if HTBOTTOMRIGHT = AUIWindow.FocusMode then
begin
UpdateUISpaceWidth(@AUIWindow.TestFocusUIView.Space, AUIWindow.DragStartRect.Right - AUIWindow.DragStartRect.Left +
AUIWindow.WMMouseMove_CursorPoint.x - AUIWindow.WMLButtonDown_CursorPoint.x);
UpdateUISpaceHeight(@AUIWindow.TestFocusUIView.Space, AUIWindow.DragStartRect.Bottom - AUIWindow.DragStartRect.Top +
AUIWindow.WMMouseMove_CursorPoint.y - AUIWindow.WMLButtonDown_CursorPoint.y);
end;
if HTTOP = AUIWindow.FocusMode then
begin
AUIWindow.TestFocusUIView.Space.Layout.Top := AUIWindow.DragStartRect.Top +
AUIWindow.WMMouseMove_CursorPoint.y - AUIWindow.WMLButtonDown_CursorPoint.y;
UpdateUISpaceHeight(@AUIWindow.TestFocusUIView.Space, AUIWindow.DragStartRect.Bottom -
AUIWindow.TestFocusUIView.Space.Layout.Top);
end;
UpdateHitTestCursor(AUIWindow.FocusMode);
end else
begin
tmpHitTest := POINT_HITTEST(@AUIWindow.TestUIView.Space.Layout, AUIWindow.WMMouseMove_CursorPoint);
UpdateHitTestCursor(tmpHitTest);
end;
UIWindowPaint(AUIWindow);
Result := DefWindowProcW(AUIWindow.BaseWnd.UIWndHandle, WM_MOUSEMOVE, wParam, lParam);
end;
function WndProcW_WMMouseWheel(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT;
begin
Result := DefWindowProcW(AUIWindow.BaseWnd.UIWndHandle, WM_MOUSEWHEEL, wParam, lParam);
end;
function WndProcW_WMSetCursor(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT;
begin
Result := DefWindowProcW(AUIWindow.BaseWnd.UIWndHandle, WM_SETCURSOR, wParam, lParam);
end;
function WndProcW_WMNCHitTest(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT;
begin
//Result := HTCLIENT;
Result := DefWindowProcW(AUIWindow.BaseWnd.UIWndHandle, WM_NCHITTEST, wParam, lParam);
end;
function WndProcW_WMMouseHover(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT;
begin
Result := DefWindowProcW(AUIWindow.BaseWnd.UIWndHandle, WM_MOUSEHOVER, wParam, lParam);
end;
function WndProcW_WMMouseLeave(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT;
begin
Result := DefWindowProcW(AUIWindow.BaseWnd.UIWndHandle, WM_MOUSELEAVE, wParam, lParam);
end;
function WndProcW_WMNCMOUSEMOVE(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT;
begin
Result := DefWindowProcW(AUIWindow.BaseWnd.UIWndHandle, WM_NCMOUSEMOVE, wParam, lParam);
end;
function WndProcW_WMNCLBUTTONUP(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT;
begin
Result := DefWindowProcW(AUIWindow.BaseWnd.UIWndHandle, WM_NCLBUTTONUP, wParam, lParam);
end;
function WndProcW_WMNCLBUTTONDOWN(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT;
begin
Result := DefWindowProcW(AUIWindow.BaseWnd.UIWndHandle, WM_NCLBUTTONDOWN, wParam, lParam);
end;
function WndProcW_WMNCLBUTTONDBLCLK(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT;
begin
Result := DefWindowProcW(AUIWindow.BaseWnd.UIWndHandle, WM_NCLBUTTONDBLCLK, wParam, lParam);
end;
function WndProcW_WMNCRBUTTONUP(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT;
begin
Result := DefWindowProcW(AUIWindow.BaseWnd.UIWndHandle, WM_NCRBUTTONUP, wParam, lParam);
end;
function WndProcW_WMNCRBUTTONDOWN(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT;
begin
Result := DefWindowProcW(AUIWindow.BaseWnd.UIWndHandle, WM_NCRBUTTONDOWN, wParam, lParam);
end;
function WndProcW_WMNCRBUTTONDBLCLK(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT;
begin
Result := DefWindowProcW(AUIWindow.BaseWnd.UIWndHandle, WM_NCRBUTTONDBLCLK, wParam, lParam);
end;
function WndProcW_WMNCMBUTTONUP(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT;
begin
Result := DefWindowProcW(AUIWindow.BaseWnd.UIWndHandle, WM_NCMBUTTONUP, wParam, lParam);
end;
function WndProcW_WMNCMBUTTONDOWN(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT;
begin
Result := DefWindowProcW(AUIWindow.BaseWnd.UIWndHandle, WM_NCMBUTTONDOWN, wParam, lParam);
end;
function WndProcW_WMNCMBUTTONDBLCLK(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT;
begin
Result := DefWindowProcW(AUIWindow.BaseWnd.UIWndHandle, WM_NCMBUTTONDBLCLK, wParam, lParam);
end;
function UIWndProcW_Mouse(AUIWindow: PUIWindow; AMsg: UINT; wParam: WPARAM; lParam: LPARAM; var AWndProcResult: LRESULT): Boolean;
begin
Result := true;
case AMsg of
WM_LButtonUp: AWndProcResult := WndProcW_WMLButtonUp(AUIWindow, wParam, lParam);
WM_LButtonDown: AWndProcResult := WndProcW_WMLButtonDown(AUIWindow, wParam, lParam);
WM_LBUTTONDBLCLK: AWndProcResult := WndProcW_WMLButtonDblClk(AUIWindow, wParam, lParam);
WM_RButtonUp: AWndProcResult := WndProcW_WMRButtonUp(AUIWindow, wParam, lParam);
WM_RButtonDown: AWndProcResult := WndProcW_WMRButtonDown(AUIWindow, wParam, lParam);
WM_RBUTTONDBLCLK: AWndProcResult := WndProcW_WMRButtonDblClk(AUIWindow, wParam, lParam);
WM_MButtonUp: AWndProcResult := WndProcW_WMMButtonUp(AUIWindow, wParam, lParam);
WM_MButtonDown: AWndProcResult := WndProcW_WMMButtonDown(AUIWindow, wParam, lParam);
WM_MBUTTONDBLCLK: AWndProcResult := WndProcW_WMMButtonDblClk(AUIWindow, wParam, lParam);
WM_MouseMove: AWndProcResult := WndProcW_WMMouseMove(AUIWindow, wParam, lParam);
WM_MOUSEWHEEL: AWndProcResult := WndProcW_WMMouseWheel(AUIWindow, wParam, lParam);
WM_SETCURSOR: AWndProcResult := WndProcW_WMSetCursor(AUIWindow, wParam, lParam);
WM_NCHITTEST: AWndProcResult := WndProcW_WMNCHitTest(AUIWindow, wParam, lParam);
WM_MOUSEHOVER: AWndProcResult := WndProcW_WMMouseHover(AUIWindow, wParam, lParam);
WM_MOUSELEAVE: AWndProcResult := WndProcW_WMMouseLeave(AUIWindow, wParam, lParam);
WM_NCMOUSEMOVE: AWndProcResult := WndProcW_WMNCMOUSEMOVE(AUIWindow, wParam, lParam);
WM_NCLBUTTONUP: AWndProcResult := WndProcW_WMNCLBUTTONUP(AUIWindow, wParam, lParam);
WM_NCLBUTTONDOWN: AWndProcResult := WndProcW_WMNCLBUTTONDOWN(AUIWindow, wParam, lParam);
WM_NCLBUTTONDBLCLK: AWndProcResult := WndProcW_WMNCLBUTTONDBLCLK(AUIWindow, wParam, lParam);
WM_NCRBUTTONUP: AWndProcResult := WndProcW_WMNCRBUTTONUP(AUIWindow, wParam, lParam);
WM_NCRBUTTONDOWN: AWndProcResult := WndProcW_WMNCRBUTTONDOWN(AUIWindow, wParam, lParam);
WM_NCRBUTTONDBLCLK: AWndProcResult := WndProcW_WMNCRBUTTONDBLCLK(AUIWindow, wParam, lParam);
WM_NCMBUTTONUP: AWndProcResult := WndProcW_WMNCMBUTTONUP(AUIWindow, wParam, lParam);
WM_NCMBUTTONDOWN: AWndProcResult := WndProcW_WMNCMBUTTONDOWN(AUIWindow, wParam, lParam);
WM_NCMBUTTONDBLCLK: AWndProcResult := WndProcW_WMNCMBUTTONDBLCLK(AUIWindow, wParam, lParam);
else
Result := false;
end;
end;
end.
|
unit FullPathName;
interface
function GetFullLongPathName(sPath: string): string;
implementation
uses Windows, SysUtils;
{
Q.
I want to change the short filename D:\PROBA\NEWSAM~1\SAMPLE.BLD
into the long one D:\Proba\New samples\sample.bld.
When I use GetFullPathName the result is the same filename
D:\PROBA\NEWSAM~1\SAMPLE.BLD.
A.
GetFullPathName is working "as designed." Many people assume
GetFullPathName=GetLongPathName, but that's not the case. In order to get the
long path, you have to iterate over each element of the path.
Here's a function that does the work for you:
ROGER : This function looks dodgy to me.
}
{
function GetExpandedPathName(const PathName: string): string;
var
Drive: String;
Path: String;
SearchRec: TSearchRec;
begin
Drive := ExtractFileDrive(PathName);
Path := Copy(PathName, Length(Drive) + 1, Length(PathName));
if (Path = '') or (Path = '\') then begin
Result := PathName;
if Result[Length(Result)] = '\' then begin
Delete(Result, Length(Result), 1);
end;
end
else begin
Path := GetLongPathName(ExtractFileDir(PathName));
if FindFirst(PathName, faAnyFile, SearchRec) = 0 then begin
Result := Path + '\' + SearchRec.FindData.cFileName;
FindClose(SearchRec);
end
else begin
Result := Path + '\' + ExtractFileName(PathName);
end
end;
end;
sysutils.ExpandFileName() is a wrapper for GetFullPathName
}
{ from Win SDK documentation:
GetFullPathName does no conversion of the specified file name, lpFileName.
If the specified file name exists, you can use GetLongPathName and
GetShortPathName to convert to long and short path names, respectively.
I take this to mean that GetFullPathName followed by a check using FileExists,
followed by a call to GetLongPathName will get a unique form for a file.
}
// *****************************************************************************
// ** TURN 8.3 AND-OR RELATIVE FILENAME, PATH INTO LONG NAME, FULL PATH FORM **
// *****************************************************************************
{ Call with sPath = valid directory or filename, short or long, with or without
path. Returns the full lfn version of sPath, or '' iff sPath invalid. }
function GetFullLongPathName(sPath: string): string;
var
n: integer;
h: HWND;
fd: Twin32findData;
begin
result := '';
sPath := expandFilename(sPath);
n := length(sPath);
if (n = 0) then EXIT;
if (n > 3) and (sPath[n] = '\') then setLength(sPath, n - 1);
//loop from end, filling result with lfn translations.
while (length(sPath) > 10) do begin
h := findFirstFile(pChar(sPath), fd);
if (h = invalid_handle_value) then begin
result := '';
EXIT;
end;
windows.findClose(h);
result := '\' + string(fd.cFileName) + result;
sPath := extractFilePath(sPath);
setLength(sPath, length(sPath) - 1);
end;
result := sPath + result;
end;
// from Peter Below
// GetFullpathname only converts the last element of the name. Try this:
{+------------------------------------------------------------
| Function GetFullLongFilename
|
| Parameters:
| shortname: filename or path to convert. This can be a
| fully qualified filename or a path relative
| to the current directory. It can contain long
| and/or short forms for the names.
| Returns:
| fully qualified filename using the long names for all elements
| of the path.
| Description:
| Recursively uses FindFirst to find the long names for
| the path elements.
| Error Conditions:
| Will raise an exception if any part of the path was not found.
|
|Created: 15.01.98 14:09:26 by P. Below
+------------------------------------------------------------}
(*
function GetFullLongFilename( shortname: string ) : string;
function GetL( shortname: string ) : string;
var
srec: TSearchRec;
begin
{ Lopp off the last element of the passed name. If we received
only a root name, e.g. c:\, ExtractFileDir returns the
path unchanged. }
Result := ExtractFileDir( shortname );
if (Result <> shortname) then begin
{ We still have an unconverted path element. So convert
the last one in the current shortname and combine the
resulting long name with what we get by calling ourselves
recursively with the rest of the path. }
if FindFirst( shortname, faAnyfile, srec ) = 0 then begin
try
Result := GetL( Result )+'\'+srec.Name;
finally
FindClose( srec );
end
end
else begin
result := '';
// raise Exception.CreateFmt('Path %s does not exist!', [shortname]);
end
end
else begin
{ Only the root remains. Remove the backslash since the
caller will add it back anyway. }
Delete(Result, length(result),1);
end;
end;
begin
{ Create fully qualified path and pass it to the converter. }
Result := GetL( ExpandFilename( shortname ));
end;
*)
end.
|
unit Selector;
interface
uses Project;
// Set various items in a TveProject to Selected, and unselect all other items.
procedure SelectAll( Project : TveProject );
procedure InvertSelection( Project : TveProject );
procedure SelectLinks( Project : TveProject );
procedure SelectLinksInSelection( Project : TveProject );
procedure SelectBreaks( Project : TveProject );
procedure SelectbreaksInSelection( Project : TveProject );
procedure SelectShortedLinks( Project : TveProject );
procedure SelectUnusedBreaks( Project : TveProject );
procedure SelectUnusedComponents( Project : TveProject );
implementation
uses Outlines, SizeableOutlines, OtherOutlines, Breaks, Netlist;
// *********************************************
// SELECT ALL ITEMS
// *********************************************
procedure SelectAll( Project : TveProject );
var
i : integer;
begin
for i := 0 to Project.BoardItemCount -1 do begin
Project.BoardItems[i].Selected := True;
end;
end;
// *********************************************
// INVERT SELECTION
// *********************************************
procedure InvertSelection( Project : TveProject );
var
i : integer;
Item : TveBoardItem;
begin
for i := 0 to Project.BoardItemCount -1 do begin
Item := Project.BoardItems[i];
Item.Selected := not Item.Selected;
end;
end;
// *********************************************
// SELECT ITEMS WITH SPECIFIED OUTLINE
// *********************************************
{
All items are unselected, then any items with an outline of OutlineClass
are selected.
}
procedure SelectItems( Project : TveProject; OutlineClass : TClass );
var
i : integer;
Item : TveBoardItem;
begin
Project.DeSelectAllItems;
for i := 0 to Project.BoardItemCount -1 do begin
Item := Project.BoardItems[i];
if Item.Outline is OutlineClass then begin
Item.Selected := True;
end;
end;
end;
// *************************************************************
// SELECT ITEMS WITH SPECIFIED OUTLINE FROM WITHIN SELECTION
// *************************************************************
{
Any items with Selected = True, are unselected unless they have
an outline of OutlineClass.
}
procedure SelectItemsInSelection( Project : TveProject; OutlineClass : TClass );
var
i : integer;
Item : TveBoardItem;
begin
for i := 0 to Project.BoardItemCount -1 do begin
Item := Project.BoardItems[i];
if Item.Selected and not (Item.Outline is OutlineClass) then begin
Item.Selected := False;
end;
end;
end;
// ****************************************
// SET SELECTED = TRUE FOR LINKS
// ****************************************
procedure SelectLinks( Project : TveProject );
begin
SelectItems( Project, TveLinkOutline );
end;
// ****************************************
// LEAVE ONLY SELECTED LINKS SELECTED
// ****************************************
procedure SelectLinksInSelection( Project : TveProject );
begin
SelectItemsInSelection( Project, TveLinkOutline );
end;
// ****************************************
// SET SELECTED = TRUE FOR BREAKS
// ****************************************
procedure SelectBreaks( Project : TveProject );
begin
SelectItems( Project, TveBreakOutline );
end;
// ****************************************
// LEAVE ONLY SELECTED BREAKS SELECTED
// ****************************************
procedure SelectbreaksInSelection( Project : TveProject );
begin
SelectItemsInSelection( Project, TveBreakOutline );
end;
// ****************************************
// LEAVE ONLY SELECTED BREAKS SELECTED
// ****************************************
procedure SelectShortedLinks( Project : TveProject );
begin
end;
// ****************************************
// SELECT UNUSED BREAKS
// ****************************************
procedure SelectUnusedBreaks( Project : TveProject );
var BreakTool : TveBreakTool;
begin
BreakTool := TveBreakTool.Create;
try
BreakTool.Project := Project;
BreakTool.SelectRedundant;
finally
BreakTool.Free;
end;
end;
// ****************************************
// SELECT UNUSED BREAKS
// ****************************************
procedure SelectUnusedComponents( Project : TveProject );
var
i : integer;
Netlist : TneNetlist;
Component : TneComponent;
BoardItem : TveBoardItem;
Designator : string;
begin
Netlist := Project.Netlist;
Project.DeSelectAllItems;
for i := 0 to Project.BoardItemCount -1 do begin
BoardItem := Project.BoardItems[i];
// detect only components, which are required by netlist -
// others are added by user to interconnect or isolate tracks.
if not BoardItem.Outline.UserDefined then begin
continue;
end;
Designator := BoardItem.Designator;
Component := Netlist.ComponentByName( Designator );
if Component = nil then begin
BoardItem.Selected := True;
end;
end;
end;
end.
|
unit ufrm_main;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
System.ImageList,
System.Actions,
System.UITypes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.ExtCtrls,
Vcl.ImgList,
Vcl.ActnList,
cxGraphics,
cxControls,
cxLookAndFeels,
cxLookAndFeelPainters,
dxRibbonSkins,
dxSkinsCore,
dxSkinBlack,
dxSkinBlue,
dxSkinBlueprint,
dxSkinCaramel,
dxSkinCoffee,
dxSkinDarkRoom,
dxSkinDarkSide,
dxSkinDevExpressDarkStyle,
dxSkinDevExpressStyle,
dxSkinFoggy,
dxSkinGlassOceans,
dxSkinHighContrast,
dxSkiniMaginary,
dxSkinLilian,
dxSkinLiquidSky,
dxSkinLondonLiquidSky,
dxSkinMcSkin,
dxSkinMetropolis,
dxSkinMetropolisDark,
dxSkinMoneyTwins,
dxSkinOffice2007Black,
dxSkinOffice2007Blue,
dxSkinOffice2007Green,
dxSkinOffice2007Pink,
dxSkinOffice2007Silver,
dxSkinOffice2010Black,
dxSkinOffice2010Blue,
dxSkinOffice2010Silver,
dxSkinOffice2013DarkGray,
dxSkinOffice2013LightGray,
dxSkinOffice2013White,
dxSkinOffice2016Colorful,
dxSkinOffice2016Dark,
dxSkinPumpkin,
dxSkinSeven,
dxSkinSevenClassic,
dxSkinSharp,
dxSkinSharpPlus,
dxSkinSilver,
dxSkinSpringTime,
dxSkinStardust,
dxSkinSummer2008,
dxSkinTheAsphaltWorld,
dxSkinsDefaultPainters,
dxSkinValentine,
dxSkinVisualStudio2013Blue,
dxSkinVisualStudio2013Dark,
dxSkinVisualStudio2013Light,
dxSkinVS2010,
dxSkinWhiteprint,
dxSkinXmas2008Blue,
dxSkinsdxRibbonPainter,
dxRibbonCustomizationForm,
cxContainer,
cxEdit,
dxSkinscxPCPainter,
dxSkinsdxBarPainter,
cxLocalization,
dxSkinsForm,
dxBar,
dxStatusBar,
dxRibbonStatusBar,
cxLabel,
dxGalleryControl,
dxRibbonBackstageViewGalleryControl,
dxRibbonBackstageView,
cxClasses,
dxRibbon,
dxGDIPlusClasses,
cxImageList,
dxSkinTheBezier,
ufrm_main_default,
ufrm_cliente,
ufrm_login;
type
Tfrm_main = class(Tfrm_main_default)
dxBarManager_1Bar2: TdxBar;
dxBarLargeButton1: TdxBarLargeButton;
Action_phonebook: TAction;
dxBarLargeButton2: TdxBarLargeButton;
Action_contract: TAction;
dxBarLargeButton3: TdxBarLargeButton;
Action_enterprise: TAction;
dxBarLargeButton4: TdxBarLargeButton;
Action_client: TAction;
Action_contract_user: TAction;
dxBarLargeButton5: TdxBarLargeButton;
Action_reseller: TAction;
dxBarLargeButton6: TdxBarLargeButton;
Action_product: TAction;
dxBarLargeButton7: TdxBarLargeButton;
dxBarManager_1Bar3: TdxBar;
Action_client_contract: TAction;
dxBarManager_1Bar4: TdxBar;
dxBarLargeButton9: TdxBarLargeButton;
Action_report: TAction;
Action_proposal_contract: TAction;
dxBarSubItem1: TdxBarSubItem;
dxBarButton1: TdxBarButton;
dxBarButton2: TdxBarButton;
procedure FormCreate(Sender: TObject);
procedure Action_phonebookExecute(Sender: TObject);
procedure Action_contractExecute(Sender: TObject);
procedure Action_enterpriseExecute(Sender: TObject);
procedure Action_clientExecute(Sender: TObject);
procedure Action_contract_userExecute(Sender: TObject);
procedure Action_resellerExecute(Sender: TObject);
procedure Action_productExecute(Sender: TObject);
procedure Action_client_contractExecute(Sender: TObject);
procedure Action_reportExecute(Sender: TObject);
procedure Action_proposal_contractExecute(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frm_main: Tfrm_main;
implementation
{$R *.dfm}
procedure Tfrm_main.Action_reportExecute(Sender: TObject);
begin
inherited;
// if not Assigned(frm_report) then begin
// frm_report := Tfrm_report.Create(Self);
// frm_report.Height := Bevel_1.Height;
// frm_report.Width := Bevel_1.Width;
// frm_report.Show;
// end else begin
// frm_report.WindowState := wsNormal;
// frm_report.Show;
// end;
end;
procedure Tfrm_main.Action_resellerExecute(Sender: TObject);
begin
inherited;
// if not Assigned(frm_reseller) then begin
// frm_reseller := Tfrm_reseller.Create(Self);
// frm_reseller.Height := Bevel_1.Height;
// frm_reseller.Width := Bevel_1.Width;
// frm_reseller.Show;
// end else begin
// frm_reseller.WindowState := wsNormal;
// frm_reseller.Show;
// end;
end;
procedure Tfrm_main.Action_clientExecute(Sender: TObject);
begin
inherited;
if not Assigned(frm_cliente) then begin
frm_cliente := Tfrm_cliente.Create(Self);
frm_cliente.Height := Bevel_1.Height;
frm_cliente.Width := Bevel_1.Width;
frm_cliente.Show;
end else begin
frm_cliente.WindowState := wsNormal;
frm_cliente.Show;
end;
end;
procedure Tfrm_main.Action_client_contractExecute(Sender: TObject);
begin
inherited;
// if not Assigned(frm_client_contract) then begin
// frm_client_contract := Tfrm_client_contract.Create(Self);
// frm_client_contract.Height := Bevel_1.Height;
// frm_client_contract.Width := Bevel_1.Width;
// frm_client_contract.Show;
// end else begin
// frm_client_contract.WindowState := wsNormal;
// frm_client_contract.Show;
// end;
end;
procedure Tfrm_main.Action_contractExecute(Sender: TObject);
begin
inherited;
// if not Assigned(frm_contract) then begin
// frm_contract := Tfrm_contract.Create(Self);
// frm_contract.Height := Bevel_1.Height;
// frm_contract.Width := Bevel_1.Width;
// frm_contract.Show;
// end else begin
// frm_contract.WindowState := wsNormal;
// frm_contract.Show;
// end;
end;
procedure Tfrm_main.Action_contract_userExecute(Sender: TObject);
begin
inherited;
// if not Assigned(frm_contract_user) then begin
// frm_contract_user := Tfrm_contract_user.Create(Self);
// frm_contract_user.Height := Bevel_1.Height;
// frm_contract_user.Width := Bevel_1.Width;
// frm_contract_user.Show;
// end else begin
// frm_contract_user.WindowState := wsNormal;
// frm_contract_user.Show;
// end;
end;
procedure Tfrm_main.Action_enterpriseExecute(Sender: TObject);
begin
inherited;
// if not Assigned(frm_enterprise) then begin
// frm_enterprise := Tfrm_enterprise.Create(Self);
// frm_enterprise.Height := Bevel_1.Height;
// frm_enterprise.Width := Bevel_1.Width;
// frm_enterprise.Show;
// end else begin
// frm_enterprise.WindowState := wsNormal;
// frm_enterprise.Show;
// end;
end;
procedure Tfrm_main.Action_phonebookExecute(Sender: TObject);
begin
inherited;
// if not Assigned(frm_phonebook) then begin
// frm_phonebook := Tfrm_phonebook.Create(Self);
// frm_phonebook.Height := Bevel_1.Height;
// frm_phonebook.Width := Bevel_1.Width;
// frm_phonebook.Show;
// end else begin
// frm_phonebook.WindowState := wsNormal;
// frm_phonebook.Show;
// end;
end;
procedure Tfrm_main.Action_productExecute(Sender: TObject);
begin
inherited;
// if not Assigned(frm_product) then begin
// frm_product := Tfrm_product.Create(Self);
// frm_product.Height := Bevel_1.Height;
// frm_product.Width := Bevel_1.Width;
// frm_product.Show;
// end else begin
// frm_product.WindowState := wsNormal;
// frm_product.Show;
// end;
end;
procedure Tfrm_main.Action_proposal_contractExecute(Sender: TObject);
begin
inherited;
// if not Assigned(frm_proposal_contract) then begin
// frm_proposal_contract := Tfrm_proposal_contract.Create(Self);
// frm_proposal_contract.Height := Bevel_1.Height;
// frm_proposal_contract.Width := Bevel_1.Width;
// frm_proposal_contract.Show;
// end else begin
// frm_proposal_contract.WindowState := wsNormal;
// frm_proposal_contract.Show;
// end;
end;
procedure Tfrm_main.FormCreate(Sender: TObject);
begin
inherited;
// frm_login := Tfrm_login.Create(Self);
// frm_login.ShowModal;
//
// if frm_login.ModalResult <> mrOk then begin
// MessageDlg('Você não se autenticou. A aplicação será encerrada!', mtWarning, [mbOK], 0);
// Application.Terminate;
// end;
end;
end.
|
unit RepositorioComanda;
interface
uses
DB,
Auditoria,
Repositorio;
type
TRepositorioComanda = class(TRepositorio)
protected
function Get (Dataset :TDataSet) :TObject; overload; override;
function GetNomeDaTabela :String; override;
function GetIdentificador(Objeto :TObject) :Variant; override;
function GetRepositorio :TRepositorio; override;
protected
function SQLGet :String; override;
function SQLSalvar :String; override;
function SQLGetAll :String; override;
function SQLRemover :String; override;
function SQLGetExiste(campo: String): String; override;
protected
function IsInsercao(Objeto :TObject) :Boolean; override;
protected
procedure SetParametros (Objeto :TObject ); override;
procedure SetIdentificador(Objeto :TObject; Identificador :Variant); override;
//==============================================================================
// Auditoria
//==============================================================================
protected
procedure SetCamposIncluidos(Auditoria :TAuditoria; Objeto :TObject); override;
procedure SetCamposAlterados(Auditoria :TAuditoria; AntigoObjeto, Objeto :TObject); override;
procedure SetCamposExcluidos(Auditoria :TAuditoria; Objeto :TObject); override;
end;
implementation
uses
SysUtils,
Comanda;
{ TRepositorioComanda }
function TRepositorioComanda.Get(Dataset: TDataSet): TObject;
var
Comanda :TComanda;
begin
Comanda := TComanda.Create;
Comanda.Codigo := self.FQuery.FieldByName('codigo').AsInteger;
Comanda.numero_comanda := self.FQuery.FieldByName('numero_comanda').AsInteger;
Comanda.ativa := ((self.FQuery.FieldByName('ativa').AsString = 'S')or(self.FQuery.FieldByName('ativa').AsString = ''));
Comanda.motivo := self.FQuery.FieldByName('motivo').AsString;
result := Comanda;
end;
function TRepositorioComanda.GetIdentificador(Objeto: TObject): Variant;
begin
result := TComanda(Objeto).Codigo;
end;
function TRepositorioComanda.GetNomeDaTabela: String;
begin
result := 'ComandaS';
end;
function TRepositorioComanda.GetRepositorio: TRepositorio;
begin
result := TRepositorioComanda.Create;
end;
function TRepositorioComanda.IsInsercao(Objeto: TObject): Boolean;
begin
result := (TComanda(Objeto).Codigo <= 0);
end;
procedure TRepositorioComanda.SetCamposAlterados(Auditoria :TAuditoria; AntigoObjeto, Objeto :TObject);
var
ComandaAntigo :TComanda;
ComandaNovo :TComanda;
begin
ComandaAntigo := (AntigoObjeto as TComanda);
ComandaNovo := (Objeto as TComanda);
if (ComandaAntigo.numero_comanda <> ComandaNovo.numero_comanda) then
Auditoria.AdicionaCampoAlterado('numero_comanda', IntToStr(ComandaAntigo.numero_comanda), IntToStr(ComandaNovo.numero_comanda));
if (ComandaAntigo.ativa <> ComandaNovo.ativa) and ComandaAntigo.ativa then
Auditoria.AdicionaCampoAlterado('ativa', 'S', 'N')
else if (ComandaAntigo.ativa <> ComandaNovo.ativa) and (not ComandaAntigo.ativa) then
Auditoria.AdicionaCampoAlterado('ativa', 'N', 'S');
if (ComandaAntigo.motivo <> ComandaNovo.motivo) then
Auditoria.AdicionaCampoAlterado('motivo', ComandaAntigo.motivo, ComandaNovo.motivo);
end;
procedure TRepositorioComanda.SetCamposExcluidos(Auditoria :TAuditoria; Objeto :TObject);
var
Comanda :TComanda;
begin
Comanda := (Objeto as TComanda);
Auditoria.AdicionaCampoExcluido('codigo', IntToStr(Comanda.Codigo));
Auditoria.AdicionaCampoExcluido('numero_comanda', IntToStr(Comanda.numero_comanda));
if Comanda.ativa then Auditoria.AdicionaCampoExcluido('ativa', 'S')
else Auditoria.AdicionaCampoExcluido('ativa', 'N');
Auditoria.AdicionaCampoExcluido('motivo', Comanda.motivo);
end;
procedure TRepositorioComanda.SetCamposIncluidos(Auditoria :TAuditoria; Objeto :TObject);
var
Comanda :TComanda;
begin
Comanda := (Objeto as TComanda);
Auditoria.AdicionaCampoIncluido('codigo', IntToStr(Comanda.codigo));
Auditoria.AdicionaCampoIncluido('numero_comanda', IntToStr(Comanda.numero_comanda));
if Comanda.ativa then Auditoria.AdicionaCampoIncluido('ativa', 'S')
else Auditoria.AdicionaCampoIncluido('ativa', 'N');
Auditoria.AdicionaCampoIncluido('motivo', Comanda.motivo);
end;
procedure TRepositorioComanda.SetIdentificador(Objeto: TObject;
Identificador: Variant);
begin
TComanda(Objeto).Codigo := Integer(Identificador);
end;
procedure TRepositorioComanda.SetParametros(Objeto: TObject);
var
Comanda :TComanda;
begin
Comanda := (Objeto as TComanda);
self.FQuery.ParamByName('codigo').AsInteger := Comanda.Codigo;
self.FQuery.ParamByName('numero_comanda').AsInteger := Comanda.numero_comanda;
if Comanda.ativa then inherited SetParametro('ativa', 'S')
else inherited SetParametro('ativa', 'N');
self.FQuery.ParamByName('motivo').AsString := Comanda.motivo;
end;
function TRepositorioComanda.SQLGet: String;
begin
result := 'select * from Comandas where codigo = :ncod';
end;
function TRepositorioComanda.SQLGetAll: String;
begin
result := 'select * from Comandas';
end;
function TRepositorioComanda.SQLGetExiste(campo: String): String;
begin
result := 'select '+ campo +' from Comandas where '+ campo +' = :ncampo';
end;
function TRepositorioComanda.SQLRemover: String;
begin
result := ' delete from Comandas where codigo = :codigo ';
end;
function TRepositorioComanda.SQLSalvar: String;
begin
result := 'update or insert into Comandas (codigo, numero_comanda, ativa, motivo) '+
' values (:codigo, :numero_comanda, :ativa, :motivo) ';
end;
end.
|
unit crypt_h;
// Name: uxml_crypt.pas
// Copyright: SoftWest group.
// Author: Maxim Mihaluk
// Date: 28.03.06
// Description: містить функції шифрування
interface
uses Windows, SysUtils, kernel_h, Controls, Classes, Math, Winsock;
const
KEY_FILE_NAME = 'softwest';
HEX_DIGITS = 8;
DATE_FORMAT = 'ddmmyyyy';
CURENT_DATE_FORMAT = 'dd.mm.yyyy'; //формат представлення дати поточний для системи
DEATH_DATE_LENGTH = 8;
DEFAULT_DISK_SN = '123ABC456DEF';
function CryptStr(const s: string): string;
function UncryptStr(const s: string): string;
procedure LoadCryptedFileToStream(const a_crypted_file_name: string; a_stream: TStream);
function UncryptFile(const a_crypted_file_name: string): string;
//function CryptStream(stream: TFileStream): Boolean;
//function UncryptStream(stream: TFileStream): Boolean;
//вертає серійний номер жорсткого диска.
function GetIDEDiskSerialNumber: string;
//вертає контрольну суму.
function CRC32(const iniCRC:Integer; source: AnsiString): Integer;
//доволі простий симетричний алгоритм шифрування даних (строки).
function EncodeMin(const data: String): String;
function DecodeMin(const data: String): String;
//вертає системну змінну.
function GetEnvVar(const varName: string): string;
//шукає файли у каталозі aDir (без вкладених підкаталогів) та вертає
//найбільшу дату файлу. Якщо щось не так вертає MinDouble;
//тобто найкращий спосіб отримати поточну дату викликати функцію так:
//GetCurDate(GetEnvVar('windir')).
function GetCurDate(aDir: string): TDate;
function GetLocalIP: String;
function GetLocalHostAddress: string;
function my_ip_address: string;
implementation
uses Dialogs;
const
STR_OFFSET_START_VALUE = 1;
STR_OFFSET_MAX_VALUE = 3;
STR_OFFSET_STEP = 1;
BIN_OFFSET_START_VALUE = 1;
BIN_OFFSET_MAX_VALUE = 10;
BIN_OFFSET_STEP = 2;
//функція шифрування строки;
//алгоритм дуже простий;
function CryptStr(const s: string): string;
var
temp: string;
i: Integer;
offset: Integer;
begin
temp:=s;
offset:=STR_OFFSET_START_VALUE;
for i:=1 to Length(temp) do
begin
temp[i]:=chr(ord(temp[i]) - offset);
Inc(offset, STR_OFFSET_STEP);
if offset > STR_OFFSET_MAX_VALUE then offset:=STR_OFFSET_START_VALUE;
end;
Result:=temp;
end;
//функція дешифрування строки;
function UncryptStr(const s: string): string;
var
temp: string;
i: Integer;
offset: Integer;
begin
temp:=s;
offset:=STR_OFFSET_START_VALUE;
for i:=1 to Length(temp) do
begin
temp[i]:=chr(ord(temp[i]) + offset);
Inc(offset, STR_OFFSET_STEP);
if offset > STR_OFFSET_MAX_VALUE then offset:=STR_OFFSET_START_VALUE;
end;
Result:=temp;
end;
//загружає в потік a_stream зашифрований файл конфігурації a_crypted_file_name;
//загружає у розшифрованому вигляді придатному для зчитування TECXMLParser-ом;
procedure LoadCryptedFileToStream(const a_crypted_file_name: string; a_stream: TStream);
var
s: string;
f: TextFile;
s_list: TStringList;
begin
AssignFile(f, a_crypted_file_name);
s_list:=TStringList.Create;
try
Reset(f);
while not EOF(f) do
begin
ReadLn(f, s);
s:=UncryptStr(s);
s_list.Add(s);
end;
s_list.SaveToStream(a_stream);
finally
CloseFile(f);
s_list.Free;
end;
end;
//розшифровує зашифрований файл конфігурації a_crypted_file_name та
//зберігає його в xml файл (з тим самим ім'ям і в тій самій папці);
//вертає ім'я xml файла якщо все нормально, або пусту строку якщо сталася якась
//помилка;
function UncryptFile(const a_crypted_file_name: string): string;
var
s: string;
f: TextFile;
s_list: TStringList;
begin
Result:='';
AssignFile(f, a_crypted_file_name);
s_list:=TStringList.Create;
try
Reset(f);
while not EOF(f) do
begin
ReadLn(f, s);
s:=UncryptStr(s);
s_list.Add(s);
end;
Result:=ChangeFileExt(a_crypted_file_name, xml_EXTENTION);
s_list.SaveToFile(Result);
finally
CloseFile(f);
s_list.Free;
end;
end;
{
function CryptStream(stream: TFileStream): Boolean;
var
p: Pointer;
i: Integer;
offset: Byte;
begin
Result:=false;
GetMem(p, 1);
try
offset:=BIN_OFFSET_START_VALUE;
for i:=0 to stream.Size - 1 do
begin
stream.Seek(i, soFromBeginning);
if stream.Read(p^, 1) > 0 then
begin
Byte(p^):=Byte(p^) - offset;
Inc(offset, BIN_OFFSET_STEP);
if offset > BIN_OFFSET_MAX_VALUE then offset:=BIN_OFFSET_START_VALUE;
stream.Seek(i, soFromBeginning);
stream.Write(p^, 1);
end
else begin
raise Exception.Create('Помилка зчитування даних (процедура CryptStream)');
end;
end;
finally
FreeMem(p, 1);
end;
Result:=true;
end;
function UncryptStream(stream: TFileStream): Boolean;
var
p: Pointer;
i: Integer;
offset: Byte;
begin
Result:=false;
GetMem(p, 1);
try
offset:=BIN_OFFSET_START_VALUE;
for i:=0 to stream.Size - 1 do
begin
stream.Seek(i, soFromBeginning);
if stream.Read(p^, 1) > 0 then
begin
Byte(p^):=Byte(p^) + offset;
Inc(offset, BIN_OFFSET_STEP);
if offset > BIN_OFFSET_MAX_VALUE then offset:=BIN_OFFSET_START_VALUE;
stream.Seek(i, soFromBeginning);
stream.Write(p^, 1);
end
else begin
raise Exception.Create('Помилка зчитування даних (процедура UncryptStream)');
end;
end;
finally
FreeMem(p, 1);
end;
Result:=true;
end;
}
function GetIDEDiskSerialNumber: string;
type
TSrbIoControl = packed record
HeaderLength : ULONG;
Signature : Array[0..7] of Char;
Timeout : ULONG;
ControlCode : ULONG;
ReturnCode : ULONG;
Length : ULONG;
end;
SRB_IO_CONTROL = TSrbIoControl;
PSrbIoControl = ^TSrbIoControl;
TIDERegs = packed record
bFeaturesReg : Byte; // Used for specifying SMART "commands".
bSectorCountReg : Byte; // IDE sector count register
bSectorNumberReg : Byte; // IDE sector number register
bCylLowReg : Byte; // IDE low order cylinder value
bCylHighReg : Byte; // IDE high order cylinder value
bDriveHeadReg : Byte; // IDE drive/head register
bCommandReg : Byte; // Actual IDE command.
bReserved : Byte; // reserved for future use. Must be zero.
end;
IDEREGS = TIDERegs;
PIDERegs = ^TIDERegs;
TSendCmdInParams = packed record
cBufferSize : DWORD; // Buffer size in bytes
irDriveRegs : TIDERegs; // Structure with drive register values.
bDriveNumber : Byte; // Physical drive number to send command to (0,1,2,3).
bReserved : Array[0..2] of Byte; // Reserved for future expansion.
dwReserved : Array[0..3] of DWORD; // For future use.
bBuffer : Array[0..0] of Byte; // Input buffer.
end;
SENDCMDINPARAMS = TSendCmdInParams;
PSendCmdInParams = ^TSendCmdInParams;
TIdSector = packed record
wGenConfig : Word;
wNumCyls : Word;
wReserved : Word;
wNumHeads : Word;
wBytesPerTrack : Word;
wBytesPerSector : Word;
wSectorsPerTrack : Word;
wVendorUnique : Array[0..2] of Word;
sSerialNumber : Array[0..19] of Char;
wBufferType : Word;
wBufferSize : Word;
wECCSize : Word;
sFirmwareRev : Array[0..7] of Char;
sModelNumber : Array[0..39] of Char;
wMoreVendorUnique : Word;
wDoubleWordIO : Word;
wCapabilities : Word;
wReserved1 : Word;
wPIOTiming : Word;
wDMATiming : Word;
wBS : Word;
wNumCurrentCyls : Word;
wNumCurrentHeads : Word;
wNumCurrentSectorsPerTrack : Word;
ulCurrentSectorCapacity : ULONG;
wMultSectorStuff : Word;
ulTotalAddressableSectors : ULONG;
wSingleWordDMA : Word;
wMultiWordDMA : Word;
bReserved : Array[0..127] of Byte;
end;
PIdSector = ^TIdSector;
const
IDE_ID_FUNCTION = $EC;
IDENTIFY_BUFFER_SIZE = 512;
DFP_RECEIVE_DRIVE_DATA = $0007c088;
IOCTL_SCSI_MINIPORT = $0004d008;
IOCTL_SCSI_MINIPORT_IDENTIFY = $001b0501;
DataSize = sizeof(TSendCmdInParams)-1+IDENTIFY_BUFFER_SIZE;
BufferSize = SizeOf(SRB_IO_CONTROL)+DataSize;
W9xBufferSize = IDENTIFY_BUFFER_SIZE+16;
var
hDevice : THandle;
cbBytesReturned : DWORD;
pInData : PSendCmdInParams;
pOutData : Pointer; // PSendCmdInParams;
Buffer : Array[0..BufferSize-1] of Byte;
srbControl : TSrbIoControl absolute Buffer;
procedure ChangeByteOrder( var Data; Size : Integer );
var ptr : PChar;
i : Integer;
c : Char;
begin
ptr := @Data;
for i := 0 to (Size shr 1)-1 do
begin
c := ptr^;
ptr^ := (ptr+1)^;
(ptr+1)^ := c;
Inc(ptr,2);
end;
end;
begin//GetIDEDiskSerialNumber
Result := '';
FillChar(Buffer,BufferSize,#0);
if Win32Platform=VER_PLATFORM_WIN32_NT then
begin // Windows NT, Windows 2000
// Get SCSI port handle
hDevice := CreateFile( '\\.\Scsi0:', GENERIC_READ or GENERIC_WRITE,
FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, 0, 0 );
if hDevice=INVALID_HANDLE_VALUE then Exit;
try
srbControl.HeaderLength := SizeOf(SRB_IO_CONTROL);
System.Move('SCSIDISK',srbControl.Signature,8);
srbControl.Timeout := 2;
srbControl.Length := DataSize;
srbControl.ControlCode := IOCTL_SCSI_MINIPORT_IDENTIFY;
pInData := PSendCmdInParams(PChar(@Buffer)+SizeOf(SRB_IO_CONTROL));
pOutData := pInData;
with pInData^ do
begin
cBufferSize := IDENTIFY_BUFFER_SIZE;
bDriveNumber := 0;
with irDriveRegs do
begin
bFeaturesReg := 0;
bSectorCountReg := 1;
bSectorNumberReg := 1;
bCylLowReg := 0;
bCylHighReg := 0;
bDriveHeadReg := $A0;
bCommandReg := IDE_ID_FUNCTION;
end;
end;
if not DeviceIoControl( hDevice, IOCTL_SCSI_MINIPORT, @Buffer,
BufferSize, @Buffer, BufferSize, cbBytesReturned, nil ) then Exit;
finally
CloseHandle(hDevice);
end;
end
else
begin // Windows 95 OSR2, Windows 98
hDevice := CreateFile( '\\.\SMARTVSD', 0, 0, nil, CREATE_NEW, 0, 0 );
if hDevice=INVALID_HANDLE_VALUE then Exit;
try
pInData := PSendCmdInParams(@Buffer);
pOutData := PChar(@pInData^.bBuffer);
with pInData^ do
begin
cBufferSize := IDENTIFY_BUFFER_SIZE;
bDriveNumber := 0;
with irDriveRegs do
begin
bFeaturesReg := 0;
bSectorCountReg := 1;
bSectorNumberReg := 1;
bCylLowReg := 0;
bCylHighReg := 0;
bDriveHeadReg := $A0;
bCommandReg := IDE_ID_FUNCTION;
end;
end;
if not DeviceIoControl( hDevice, DFP_RECEIVE_DRIVE_DATA, pInData,
SizeOf(TSendCmdInParams)-1, pOutData, W9xBufferSize,
cbBytesReturned, nil ) then Exit;
finally
CloseHandle(hDevice);
end;
end;
with PIdSector(PChar(pOutData)+16)^ do
begin
ChangeByteOrder(sSerialNumber,SizeOf(sSerialNumber));
SetString(Result,sSerialNumber,SizeOf(sSerialNumber));
end;
end;//GetIDEDiskSerialNumber
function CRC32(const IniCRC:Integer;Source:AnsiString):Integer;
asm
Push EBX
Push ESI
Push EDI
Or EDX,EDX
Jz @Done
Mov ESI,EDX
Mov ECX,[EDX-4]
Jecxz @Done
Lea EDI,@CRCTbl
Mov EDX,EAX
xor EAX,EAX
Cld
@L1:
Lodsb
Mov EBX,EDX
xor EBX,EAX
And EBX,$FF
Shl EBX,2
Shr EDX,8
And EDX,$FFFFFF
xor EDX,[EDI+EBX]
Dec ECX
Jnz @L1
Mov EAX,EDX
@Done:
Pop EDI
Pop ESI
Pop EBX
Ret
@CRCTbl:
DD $00000000, $77073096, $ee0e612c, $990951ba
DD $076dc419, $706af48f, $e963a535, $9e6495a3
DD $0edb8832, $79dcb8a4, $e0d5e91e, $97d2d988
DD $09b64c2b, $7eb17cbd, $e7b82d07, $90bf1d91
DD $1db71064, $6ab020f2, $f3b97148, $84be41de
DD $1adad47d, $6ddde4eb, $f4d4b551, $83d385c7
DD $136c9856, $646ba8c0, $fd62f97a, $8a65c9ec
DD $14015c4f, $63066cd9, $fa0f3d63, $8d080df5
DD $3b6e20c8, $4c69105e, $d56041e4, $a2677172
DD $3c03e4d1, $4b04d447, $d20d85fd, $a50ab56b
DD $35b5a8fa, $42b2986c, $dbbbc9d6, $acbcf940
DD $32d86ce3, $45df5c75, $dcd60dcf, $abd13d59
DD $26d930ac, $51de003a, $c8d75180, $bfd06116
DD $21b4f4b5, $56b3c423, $cfba9599, $b8bda50f
DD $2802b89e, $5f058808, $c60cd9b2, $b10be924
DD $2f6f7c87, $58684c11, $c1611dab, $b6662d3d
DD $76dc4190, $01db7106, $98d220bc, $efd5102a
DD $71b18589, $06b6b51f, $9fbfe4a5, $e8b8d433
DD $7807c9a2, $0f00f934, $9609a88e, $e10e9818
DD $7f6a0dbb, $086d3d2d, $91646c97, $e6635c01
DD $6b6b51f4, $1c6c6162, $856530d8, $f262004e
DD $6c0695ed, $1b01a57b, $8208f4c1, $f50fc457
DD $65b0d9c6, $12b7e950, $8bbeb8ea, $fcb9887c
DD $62dd1ddf, $15da2d49, $8cd37cf3, $fbd44c65
DD $4db26158, $3ab551ce, $a3bc0074, $d4bb30e2
DD $4adfa541, $3dd895d7, $a4d1c46d, $d3d6f4fb
DD $4369e96a, $346ed9fc, $ad678846, $da60b8d0
DD $44042d73, $33031de5, $aa0a4c5f, $dd0d7cc9
DD $5005713c, $270241aa, $be0b1010, $c90c2086
DD $5768b525, $206f85b3, $b966d409, $ce61e49f
DD $5edef90e, $29d9c998, $b0d09822, $c7d7a8b4
DD $59b33d17, $2eb40d81, $b7bd5c3b, $c0ba6cad
DD $edb88320, $9abfb3b6, $03b6e20c, $74b1d29a
DD $ead54739, $9dd277af, $04db2615, $73dc1683
DD $e3630b12, $94643b84, $0d6d6a3e, $7a6a5aa8
DD $e40ecf0b, $9309ff9d, $0a00ae27, $7d079eb1
DD $f00f9344, $8708a3d2, $1e01f268, $6906c2fe
DD $f762575d, $806567cb, $196c3671, $6e6b06e7
DD $fed41b76, $89d32be0, $10da7a5a, $67dd4acc
DD $f9b9df6f, $8ebeeff9, $17b7be43, $60b08ed5
DD $d6d6a3e8, $a1d1937e, $38d8c2c4, $4fdff252
DD $d1bb67f1, $a6bc5767, $3fb506dd, $48b2364b
DD $d80d2bda, $af0a1b4c, $36034af6, $41047a60
DD $df60efc3, $a867df55, $316e8eef, $4669be79
DD $cb61b38c, $bc66831a, $256fd2a0, $5268e236
DD $cc0c7795, $bb0b4703, $220216b9, $5505262f
DD $c5ba3bbe, $b2bd0b28, $2bb45a92, $5cb36a04
DD $c2d7ffa7, $b5d0cf31, $2cd99e8b, $5bdeae1d
DD $9b64c2b0, $ec63f226, $756aa39c, $026d930a
DD $9c0906a9, $eb0e363f, $72076785, $05005713
DD $95bf4a82, $e2b87a14, $7bb12bae, $0cb61b38
DD $92d28e9b, $e5d5be0d, $7cdcefb7, $0bdbdf21
DD $86d3d2d4, $f1d4e242, $68ddb3f8, $1fda836e
DD $81be16cd, $f6b9265b, $6fb077e1, $18b74777
DD $88085ae6, $ff0f6a70, $66063bca, $11010b5c
DD $8f659eff, $f862ae69, $616bffd3, $166ccf45
DD $a00ae278, $d70dd2ee, $4e048354, $3903b3c2
DD $a7672661, $d06016f7, $4969474d, $3e6e77db
DD $aed16a4a, $d9d65adc, $40df0b66, $37d83bf0
DD $a9bcae53, $debb9ec5, $47b2cf7f, $30b5ffe9
DD $bdbdf21c, $cabac28a, $53b39330, $24b4a3a6
DD $bad03605, $cdd70693, $54de5729, $23d967bf
DD $b3667a2e, $c4614ab8, $5d681b02, $2a6f2b94
DD $b40bbe37, $c30c8ea1, $5a05df1b, $2d02ef8d
end;
function EncodeMin(const data: String): String;
var
step: Integer;
cur_index: Integer;
temp_char: Char;
begin
Result:=data;
if Length(Result) <= 1 then Exit;
if Pos('_', Result) > 0 then
Result[Pos('_', Result)]:='G';
step:=1;
while (step + 1) <= Length(Result) do
begin
cur_index:=1;
while (cur_index + step) <= Length(Result) do
begin
temp_char:=Result[cur_index];
Result[cur_index]:=Result[cur_index + step];
Result[cur_index + step]:=temp_char;
cur_index:=cur_index + step + 1;
end;
Inc(step);
end;
Result:=Result;
end;
function DecodeMin(const data: String): String;
var
step: Integer;
cur_index: Integer;
temp_char: Char;
begin
Result:=data;
if Length(Result) <= 1 then Exit;
step:=Length(Result) - 1;
while step >= 1 do
begin
cur_index:=1;
while (cur_index + step) <= Length(Result) do
begin
temp_char:=Result[cur_index];
Result[cur_index]:=Result[cur_index + step];
Result[cur_index + step]:=temp_char;
cur_index:=cur_index + step + 1;
end;
Dec(step);
end;
if Pos('G', Result) > 0 then
Result[Pos('G', Result)]:='_';
Result:=Result;
end;
function GetEnvVar(const varName: string): string;
var
i: Integer;
begin
Result:='';
try
i:=GetEnvironmentVariable(PChar(varName), nil, 0);
if i > 0 then
begin
SetLength(Result, i);
GetEnvironmentVariable(PChar(varName), PChar(Result), i);
end;
except
Result:='';
end;
end;
//шукає файли лише у каталозі aDir (без вкладених підкаталогів) та вертає
//найбільшу дату файлу. Якщо щось не так вертає MinDouble.
function GetCurDate(aDir: string): TDate;
function FileTime2DateTime(FT:_FileTime): TDateTime;
var
FileTime: _SystemTime;
begin
FileTimeToLocalFileTime(FT, FT);
FileTimeToSystemTime(FT,FileTime);
Result:=EncodeDate(FileTime.wYear, FileTime.wMonth, FileTime.wDay)+
EncodeTime(FileTime.wHour, FileTime.wMinute, FileTime.wSecond, FileTime.wMilliseconds);
end;
var
searchRec: TSearchRec;
tempDate: TDate;
maxDate: TDate;
begin
Result:=0;
if aDir = '' then Exit;
maxDate:=MinDouble;
if aDir <> '' then
if aDir[length(aDir)] <> '\' then aDir:=aDir + '\';
if FindFirst(aDir + '*.*', faAnyFile, searchRec) = 0 then
begin
repeat
tempDate:=FileTime2DateTime(searchRec.FindData.ftLastAccessTime);
if tempDate > maxDate then
maxDate:=tempDate;
until FindNext(searchRec) <> 0;
end;
SysUtils.FindClose(searchRec);
Result:=maxDate;
end;
function GetLocalIP: String;
var
WSAData:
TWSAData;
SockAddrIn: TSockAddrIn;
Host: PHostEnt; // Эти переменные объявлены в Winsock.pas
comp_name: PChar;
name_size: Cardinal;
begin
Result:='';
if WSAStartup($101, WSAData) = 0 then
begin
// Host:=GetHostByName(@Localname[1]);
name_size:=MAX_COMPUTERNAME_LENGTH + 1;
GetMem(comp_name, name_size);
try
if GetComputerName(comp_name, name_size) then
begin
Host:=GetHostByName(comp_name);
if Host<>nil then
begin
SockAddrIn.sin_addr.S_addr:=longint(plongint(Host^.h_addr_list^)^);
Result:=inet_ntoa(SockAddrIn.sin_addr);
end;
WSACleanUp;
end;
finally
FreeMem(comp_name, name_size);
end;
end;
end;
function GetLocalHostAddress: string;
var
SockAddrIn: TSockAddrIn;
HostEnt: PHostEnt;
szHostName: array[0..128] of Char;
begin
if GetHostName(szHostName, 128) = 0 then
begin
HostEnt:=GetHostByName(szHostName);
if HostEnt = nil then
Result:= ''
else begin
SockAddrIn.sin_addr.S_addr:=longint(plongint(HostEnt^.h_addr_list^)^);
Result:=inet_ntoa(SockAddrIn.sin_addr);
end;
end
else begin
//Error handle
end;
end;
function my_ip_address: string;
const
BUF_SIZE = 255;
var
buf: Pointer;
HostEnt : PHostEnt;//Не освобождайте это!
SockAddrIn: TSockAddrIn;
ipInt: Longint;
begin
buf:=nil;
try
GetMem(buf, BUF_SIZE);
Winsock.GetHostname(buf, BUF_SIZE);//это может работать и без сети
HostEnt:=Winsock.GetHostByName(buf);
if HostEnt = nil then
begin
ipInt:=Winsock.htonl($07000001)// 127.0.0.1
end
else begin
ipInt:=Longint(PLongint(HostEnt^.h_addr_list^)^);
end;
SockAddrIn.sin_addr.S_addr:=ipInt;
finally
if buf <> nil then FreeMem(buf, BUF_SIZE);
end;
Result:=Winsock.inet_ntoa(SockAddrIn.sin_addr);
end;
end.
|
// ************************************************************************ //
// The types declared in this file were generated from data read from the
// WSDL File described below:
// WSDL : http://www.appraisalsentry.com/appraisalsentryservice.asmx?wsdl
// Encoding : utf-8
// Version : 1.0
// (9/12/2007 10:59:30 PM - 1.33.2.5)
// ************************************************************************ //
unit appraisalsentryservice;
interface
uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns;
type
// ************************************************************************ //
// The following types, referred to in the WSDL document are not being represented
// in this file. They are either aliases[@] of other types represented or were referred
// to but never[!] declared in the document. The types from the latter category
// typically map to predefined/known XML or Borland types; however, they could also
// indicate incorrect WSDL documents that failed to declare or import a schema type.
// ************************************************************************ //
// !:string - "http://www.w3.org/2001/XMLSchema"
// !:decimal - "http://www.w3.org/2001/XMLSchema"
// !:base64Binary - "http://www.w3.org/2001/XMLSchema"
// !:int - "http://www.w3.org/2001/XMLSchema"
// !:short - "http://www.w3.org/2001/XMLSchema"
// !:boolean - "http://www.w3.org/2001/XMLSchema"
// !:dateTime - "http://www.w3.org/2001/XMLSchema"
PropertyInfo = class; { "http://www.appraisalsentry.com/" }
IdentityInfo = class; { "http://www.appraisalsentry.com/" }
ASDataRec = class; { "http://www.appraisalsentry.com/" }
Customer = class; { "http://www.appraisalsentry.com/" }
CustomerSubscription = class; { "http://www.appraisalsentry.com/" }
// ************************************************************************ //
// Namespace : http://www.appraisalsentry.com/
// ************************************************************************ //
PropertyInfo = class(TRemotable)
private
FAddress: WideString;
FCity: WideString;
FState: WideString;
FZip: WideString;
FTotalBedBathRooms: WideString;
FGrossLivingArea: WideString;
FEstimatedMarketValue: WideString;
FEffectiveAppraisalDate: WideString;
FLenderName: WideString;
FBorrowerName: WideString;
FReportSignedOn: WideString;
FReportPages: WideString;
published
property Address: WideString read FAddress write FAddress;
property City: WideString read FCity write FCity;
property State: WideString read FState write FState;
property Zip: WideString read FZip write FZip;
property TotalBedBathRooms: WideString read FTotalBedBathRooms write FTotalBedBathRooms;
property GrossLivingArea: WideString read FGrossLivingArea write FGrossLivingArea;
property EstimatedMarketValue: WideString read FEstimatedMarketValue write FEstimatedMarketValue;
property EffectiveAppraisalDate: WideString read FEffectiveAppraisalDate write FEffectiveAppraisalDate;
property LenderName: WideString read FLenderName write FLenderName;
property BorrowerName: WideString read FBorrowerName write FBorrowerName;
property ReportSignedOn: WideString read FReportSignedOn write FReportSignedOn;
property ReportPages: WideString read FReportPages write FReportPages;
end;
// ************************************************************************ //
// Namespace : http://www.appraisalsentry.com/
// ************************************************************************ //
IdentityInfo = class(TRemotable)
private
FAppraiserName: WideString;
FCompanyName: WideString;
FAddress: WideString;
FCity: WideString;
FState: WideString;
FZip: WideString;
FAppraiserLicNo: WideString;
FAppraiserCertNo: WideString;
FLicCertExpirationDate: WideString;
FLicCertIssuingState: WideString;
published
property AppraiserName: WideString read FAppraiserName write FAppraiserName;
property CompanyName: WideString read FCompanyName write FCompanyName;
property Address: WideString read FAddress write FAddress;
property City: WideString read FCity write FCity;
property State: WideString read FState write FState;
property Zip: WideString read FZip write FZip;
property AppraiserLicNo: WideString read FAppraiserLicNo write FAppraiserLicNo;
property AppraiserCertNo: WideString read FAppraiserCertNo write FAppraiserCertNo;
property LicCertExpirationDate: WideString read FLicCertExpirationDate write FLicCertExpirationDate;
property LicCertIssuingState: WideString read FLicCertIssuingState write FLicCertIssuingState;
end;
// ************************************************************************ //
// Namespace : http://www.appraisalsentry.com/
// ************************************************************************ //
ASDataRec = class(TRemotable)
private
FFileNo: WideString;
FPropertyFacts: PropertyInfo;
FAppraiserIdentity: IdentityInfo;
FEmailTo: WideString;
public
destructor Destroy; override;
published
property FileNo: WideString read FFileNo write FFileNo;
property PropertyFacts: PropertyInfo read FPropertyFacts write FPropertyFacts;
property AppraiserIdentity: IdentityInfo read FAppraiserIdentity write FAppraiserIdentity;
property EmailTo: WideString read FEmailTo write FEmailTo;
end;
// ************************************************************************ //
// Namespace : http://www.appraisalsentry.com/
// ************************************************************************ //
Customer = class(TRemotable)
private
FCustomerID: Integer;
FRefCustomerID: WideString;
FCustomerTypeID: Smallint;
FPartnerID: Integer;
FUserID: WideString;
FPassword: WideString;
FFirstName: WideString;
FLastName: WideString;
FMI: WideString;
FCompany: WideString;
FAddress: WideString;
FCity: WideString;
FState: WideString;
FZip: WideString;
FPhone: WideString;
FFax: WideString;
FEmail: WideString;
FSecretQuestion: WideString;
FSecretAnswer: WideString;
published
property CustomerID: Integer read FCustomerID write FCustomerID;
property RefCustomerID: WideString read FRefCustomerID write FRefCustomerID;
property CustomerTypeID: Smallint read FCustomerTypeID write FCustomerTypeID;
property PartnerID: Integer read FPartnerID write FPartnerID;
property UserID: WideString read FUserID write FUserID;
property Password: WideString read FPassword write FPassword;
property FirstName: WideString read FFirstName write FFirstName;
property LastName: WideString read FLastName write FLastName;
property MI: WideString read FMI write FMI;
property Company: WideString read FCompany write FCompany;
property Address: WideString read FAddress write FAddress;
property City: WideString read FCity write FCity;
property State: WideString read FState write FState;
property Zip: WideString read FZip write FZip;
property Phone: WideString read FPhone write FPhone;
property Fax: WideString read FFax write FFax;
property Email: WideString read FEmail write FEmail;
property SecretQuestion: WideString read FSecretQuestion write FSecretQuestion;
property SecretAnswer: WideString read FSecretAnswer write FSecretAnswer;
end;
// ************************************************************************ //
// Namespace : http://www.appraisalsentry.com/
// ************************************************************************ //
CustomerSubscription = class(TRemotable)
private
FRefCustomerID: WideString;
FPartnerID: Integer;
FProductID: WideString;
FInvoiceID: WideString;
FSubsStartsOn: TXSDateTime;
FSubsExpiresOn: TXSDateTime;
FSubsUnits: Integer;
FCreatedOn: TXSDateTime;
FCreatedBy: Integer;
FisActive: Boolean;
public
destructor Destroy; override;
published
property RefCustomerID: WideString read FRefCustomerID write FRefCustomerID;
property PartnerID: Integer read FPartnerID write FPartnerID;
property ProductID: WideString read FProductID write FProductID;
property InvoiceID: WideString read FInvoiceID write FInvoiceID;
property SubsStartsOn: TXSDateTime read FSubsStartsOn write FSubsStartsOn;
property SubsExpiresOn: TXSDateTime read FSubsExpiresOn write FSubsExpiresOn;
property SubsUnits: Integer read FSubsUnits write FSubsUnits;
property CreatedOn: TXSDateTime read FCreatedOn write FCreatedOn;
property CreatedBy: Integer read FCreatedBy write FCreatedBy;
property isActive: Boolean read FisActive write FisActive;
end;
// ************************************************************************ //
// Namespace : http://www.appraisalsentry.com/
// soapAction: http://www.appraisalsentry.com/%operationName%
// transport : http://schemas.xmlsoap.org/soap/http
// binding : AppraisalSentryServiceSoap
// service : AppraisalSentryService
// port : AppraisalSentryServiceSoap
// URL : http://www.appraisalsentry.com/appraisalsentryservice.asmx
// ************************************************************************ //
AppraisalSentryServiceSoap = interface(IInvokable)
['{BB87B7A4-49EB-CE47-9174-6B8B896687CC}']
procedure GetSecurityToken(const ipUserName: WideString; const ipPassword: WideString; out GetSecurityTokenResult: WideString; out opOverageFee: TXSDecimal; out opMessage: WideString); stdcall;
procedure RegisterReport(const ipSecurityToken: WideString; const ipUserName: WideString; const ipPassword: WideString; const strFileName: WideString; const ipReportFile: TByteDynArray; const ipLicFile: TByteDynArray; const ASData: ASDataRec; out RegisterReportResult: TByteDynArray; out opMessage: WideString
); stdcall;
procedure ValidateReport(const ipUserName: WideString; const ipPassword: WideString; const ipReportFile: TByteDynArray; out ValidateReportResult: ASDataRec; out opMessage: WideString); stdcall;
procedure CreateCustomer(const customerRec: Customer; out CreateCustomerResult: Boolean; out opMessage: WideString); stdcall;
procedure CreateNewSubscriptionForCustomer(const customerSubscription: CustomerSubscription; out CreateNewSubscriptionForCustomerResult: Boolean; out opMessage: WideString); stdcall;
procedure ResetSubscriptionUsedUnitsForCustomer(const refCustomerID: WideString; const partnerID: Integer; const productID: WideString; const resetToUnits: Integer; const rollOver: Boolean; out ResetSubscriptionUsedUnitsForCustomerResult: Boolean; out opMessage: WideString); stdcall;
procedure ResetAuthenticationForCustomer(const refCustomerID: WideString; const partnerID: Integer; out ResetAuthenticationForCustomerResult: Boolean; out opMessage: WideString); stdcall;
end;
function GetAppraisalSentryServiceSoap(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): AppraisalSentryServiceSoap;
implementation
function GetAppraisalSentryServiceSoap(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): AppraisalSentryServiceSoap;
const
defWSDL = 'http://www.appraisalsentry.com/appraisalsentryservice.asmx?wsdl';
defURL = 'http://www.appraisalsentry.com/appraisalsentryservice.asmx';
defSvc = 'AppraisalSentryService';
defPrt = 'AppraisalSentryServiceSoap';
var
RIO: THTTPRIO;
begin
Result := nil;
if (Addr = '') then
begin
if UseWSDL then
Addr := defWSDL
else
Addr := defURL;
end;
if HTTPRIO = nil then
RIO := THTTPRIO.Create(nil)
else
RIO := HTTPRIO;
try
Result := (RIO as AppraisalSentryServiceSoap);
if UseWSDL then
begin
RIO.WSDLLocation := Addr;
RIO.Service := defSvc;
RIO.Port := defPrt;
end else
RIO.URL := Addr;
finally
if (Result = nil) and (HTTPRIO = nil) then
RIO.Free;
end;
end;
destructor ASDataRec.Destroy;
begin
if Assigned(FPropertyFacts) then
FPropertyFacts.Free;
if Assigned(FAppraiserIdentity) then
FAppraiserIdentity.Free;
inherited Destroy;
end;
destructor CustomerSubscription.Destroy;
begin
if Assigned(FSubsStartsOn) then
FSubsStartsOn.Free;
if Assigned(FSubsExpiresOn) then
FSubsExpiresOn.Free;
if Assigned(FCreatedOn) then
FCreatedOn.Free;
inherited Destroy;
end;
initialization
InvRegistry.RegisterInterface(TypeInfo(AppraisalSentryServiceSoap), 'http://www.appraisalsentry.com/', 'utf-8');
InvRegistry.RegisterDefaultSOAPAction(TypeInfo(AppraisalSentryServiceSoap), 'http://www.appraisalsentry.com/%operationName%');
InvRegistry.RegisterInvokeOptions(TypeInfo(AppraisalSentryServiceSoap), ioDocument); //Dr Bobs solution
RemClassRegistry.RegisterXSClass(PropertyInfo, 'http://www.appraisalsentry.com/', 'PropertyInfo');
RemClassRegistry.RegisterXSClass(IdentityInfo, 'http://www.appraisalsentry.com/', 'IdentityInfo');
RemClassRegistry.RegisterXSClass(ASDataRec, 'http://www.appraisalsentry.com/', 'ASDataRec');
RemClassRegistry.RegisterXSClass(Customer, 'http://www.appraisalsentry.com/', 'Customer');
RemClassRegistry.RegisterXSClass(CustomerSubscription, 'http://www.appraisalsentry.com/', 'CustomerSubscription');
end. |
unit core_forward_shaders;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,core_shader_program,dglOpenGL,core_camera,core_lights,core_types,
VectorGeometry;
type
//forward mode shaders
{ TShaderForwardLighting }
TShaderForwardLighting = class (TProgram)
unifMVP:glint;
m_WVPLocation,
m_WorldMatrixLocation,
m_samplerLocation,
m_eyeWorldPosLocation,
m_matSpecularIntensityLocation,
m_matSpecularPowerLocation,
m_numPointLightsLocation,
m_numSpotLightsLocation:GLint;
m_dirLightLocation : record
Color,
AmbientIntensity,
DiffuseIntensity,
Direction:glint;
end;
m_pointLightsLocation: array [0..MAX_POINT_LIGHTS-1] of record
Color,
AmbientIntensity,
DiffuseIntensity,
Position:glint;
Atten : record
Constant,
Linear,
Exp:glint;
end;
end;
m_spotLightsLocation: array [0..MAX_SPOT_LIGHTS-1] of record
Color,
AmbientIntensity,
DiffuseIntensity,
Position,
Direction,
Cutoff:glint;
Atten : record
Constant,
Linear,
Exp:glint;
end;
end;
procedure use;
procedure init(prg:gluint);
procedure resize;
procedure setDirectionalLight(light:pDirLight);
procedure SetEyeWorldPos(const EyeWorldPos:taffinevector);
procedure SetMatSpecularIntensity(Intensity:single);
procedure SetMatSpecularPower(Power:single);
procedure SetPointLights(NumLights:cardinal; pLights:pPointLights);
procedure SetSpotLights(NumLights:cardinal; pLights:pSpotLights);
procedure SetWorldMatrix(mat:Pmatrix);
end;
implementation
{ TShaderForwardLighting }
procedure TShaderForwardLighting.use;
begin
glUseProgram(id);
//glUniformMatrix4fv(unifWorldToCameraMatrix, 1, bytebool(GL_FALSE), @camera.WorldToCameraMatrix);
end;
procedure TShaderForwardLighting.init(prg: gluint);
var
i:cardinal;
name:string;
begin
glUseProgram(prg);
id:=prg;
unifMVP:=GetUniformLocation(prg,'mvp');
m_WorldMatrixLocation := GetUniformLocation(id,'gWorld');
m_eyeWorldPosLocation := GetUniformLocation(id,'gEyeWorldPos');
m_dirLightLocation.Color := GetUniformLocation(id,'gDirectionalLight.Base.Color');
m_dirLightLocation.AmbientIntensity := GetUniformLocation(id,'gDirectionalLight.Base.AmbientIntensity');
m_dirLightLocation.Direction := GetUniformLocation(id,'gDirectionalLight.Direction');
m_dirLightLocation.DiffuseIntensity := GetUniformLocation(id,'gDirectionalLight.Base.DiffuseIntensity');
m_matSpecularIntensityLocation := GetUniformLocation(id,'gMatSpecularIntensity');
m_matSpecularPowerLocation := GetUniformLocation(id,'gSpecularPower');
m_numPointLightsLocation := GetUniformLocation(id,'gNumPointLights');
m_numSpotLightsLocation := GetUniformLocation(id,'gNumSpotLights');
for i:=0 to length(m_pointLightsLocation)-1 do begin
name:=format('gPointLights[%d].Base.Color',[i]);
m_pointLightsLocation[i].Color := GetUniformLocation(id,name);
name:=format('gPointLights[%d].Base.AmbientIntensity', [i]);
m_pointLightsLocation[i].AmbientIntensity := GetUniformLocation(id,Name);
name:=format('gPointLights[%d].Position', [i]);
m_pointLightsLocation[i].Position := GetUniformLocation(id,Name);
name:=format('gPointLights[%d].Base.DiffuseIntensity', [i]);
m_pointLightsLocation[i].DiffuseIntensity := GetUniformLocation(id,Name);
name:=format('gPointLights[%d].Atten.Constant', [i]);
m_pointLightsLocation[i].Atten.Constant := GetUniformLocation(id,Name);
name:=format('gPointLights[%d].Atten.Linear', [i]);
m_pointLightsLocation[i].Atten.Linear := GetUniformLocation(id,Name);
name:=format('gPointLights[%d].Atten.Exp', [i]);
m_pointLightsLocation[i].Atten.Exp := GetUniformLocation(id,Name);
end;
for i:=0 to length(m_spotLightsLocation)-1 do begin
name:=format('gSpotLights[%d].Base.Base.Color', [i]);
m_spotLightsLocation[i].Color := GetUniformLocation(id,Name);
name:=format('gSpotLights[%d].Base.Base.AmbientIntensity', [i]);
m_spotLightsLocation[i].AmbientIntensity := GetUniformLocation(Name);
name:=format('gSpotLights[%d].Base.Position', [i]);
m_spotLightsLocation[i].Position := GetUniformLocation(Name);
name:=format('gSpotLights[%d].Direction', [i]);
m_spotLightsLocation[i].Direction := GetUniformLocation(Name);
name:=format('gSpotLights[%d].Cutoff', [i]);
m_spotLightsLocation[i].Cutoff := GetUniformLocation(Name);
name:=format('gSpotLights[%d].Base.Base.DiffuseIntensity', [i]);
m_spotLightsLocation[i].DiffuseIntensity := GetUniformLocation(Name);
name:=format('gSpotLights[%d].Base.Atten.Constant', [i]);
m_spotLightsLocation[i].Atten.Constant := GetUniformLocation(Name);
name:=format('gSpotLights[%d].Base.Atten.Linear', [i]);
m_spotLightsLocation[i].Atten.Linear := GetUniformLocation(Name);
name:=format('gSpotLights[%d].Base.Atten.Exp', [i]);
m_spotLightsLocation[i].Atten.Exp := GetUniformLocation(Name);
end;
end;
procedure TShaderForwardLighting.resize;
begin
glUseProgram(id);
// glUniformMatrix4fv(unifCameraToClipMatrix, 1, bytebool(GL_FALSE), @camera.projectionMatrix);
end;
procedure TShaderForwardLighting.setDirectionalLight(light: pDirLight);
begin
glUniform3f(m_dirLightLocation.Color, Light^.Color[0], Light^.Color[1], Light^.Color[2]);
glUniform1f(m_dirLightLocation.AmbientIntensity, Light^.AmbientIntensity);
//Vector3f Direction = Light.Direction;
//Direction.Normalize();
glUniform3f(m_dirLightLocation.Direction, light^.Direction[0], light^.Direction[1], light^.Direction[2]);
glUniform1f(m_dirLightLocation.DiffuseIntensity, Light^.DiffuseIntensity);
end;
procedure TShaderForwardLighting.SetEyeWorldPos(const EyeWorldPos: taffinevector);
begin
glUniform3f(m_eyeWorldPosLocation, EyeWorldPos[0], EyeWorldPos[1], EyeWorldPos[2]);
end;
procedure TShaderForwardLighting.SetMatSpecularIntensity(Intensity: single);
begin
glUniform1f(m_matSpecularIntensityLocation, Intensity);
end;
procedure TShaderForwardLighting.SetMatSpecularPower(Power: single);
begin
glUniform1f(m_matSpecularPowerLocation, Power);
end;
procedure TShaderForwardLighting.SetPointLights(NumLights: cardinal;
pLights: pPointLights);
var
i:cardinal;
begin
glUniform1i(m_numPointLightsLocation, NumLights);
for i := 0 to NumLights-1 do begin
glUniform3f(m_pointLightsLocation[i].Color, pLights^[i].Color[0], pLights^[i].Color[1], pLights^[i].Color[2]);
glUniform1f(m_pointLightsLocation[i].AmbientIntensity, pLights^[i].AmbientIntensity);
glUniform1f(m_pointLightsLocation[i].DiffuseIntensity, pLights^[i].DiffuseIntensity);
glUniform3f(m_pointLightsLocation[i].Position, pLights^[i].Position[0], pLights^[i].Position[1], pLights^[i].Position[2]);
glUniform1f(m_pointLightsLocation[i].Atten.Constant, pLights^[i].Attenuation.Constant);
glUniform1f(m_pointLightsLocation[i].Atten.Linear, pLights^[i].Attenuation.Linear);
glUniform1f(m_pointLightsLocation[i].Atten.Exp, pLights^[i].Attenuation.Exp);
end;
end;
procedure TShaderForwardLighting.SetSpotLights(NumLights: cardinal;
pLights: pSpotLights);
var
i:cardinal;
begin
glUniform1i(m_numSpotLightsLocation, NumLights);
for i:=0 to NumLights-1 do begin
glUniform3f(m_spotLightsLocation[i].Color, pLights^[i].Color[0], pLights^[i].Color[1], pLights^[i].Color[2]);
glUniform1f(m_spotLightsLocation[i].AmbientIntensity, pLights^[i].AmbientIntensity);
glUniform1f(m_spotLightsLocation[i].DiffuseIntensity, pLights^[i].DiffuseIntensity);
glUniform3f(m_spotLightsLocation[i].Position, pLights^[i].Position[0], pLights^[i].Position[1], pLights^[i].Position[2]);
//Vector3f Direction = pLights^[i].Direction;
//Direction.Normalize();
glUniform3f(m_spotLightsLocation[i].Direction, pLights^[i].Direction[0], pLights^[i].Direction[1], pLights^[i].Direction[2]);
glUniform1f(m_spotLightsLocation[i].Cutoff, cos(degtorad(pLights^[i].Cutoff)));
glUniform1f(m_spotLightsLocation[i].Atten.Constant, pLights^[i].Attenuation.Constant);
glUniform1f(m_spotLightsLocation[i].Atten.Linear, pLights^[i].Attenuation.Linear);
glUniform1f(m_spotLightsLocation[i].Atten.Exp, pLights^[i].Attenuation.Exp);
end;
end;
procedure TShaderForwardLighting.SetWorldMatrix(mat: Pmatrix);
begin
glUniformMatrix4fv(m_WorldMatrixLocation, 1, bytebool(GL_TRUE), @mat);
end;
end.
|
unit uConfigINI;
interface
uses Classes, SysUtils, IniFiles;
type
TConfigIni = Class;
TConfigIniBase = Class(TObject)
private
FOwner :TConfigIni;
public
constructor Create(AOwner :TConfigIni);
property Owner :TconfigIni read FOwner;
end;
TConfigIniAcessoBanco = class(TConfigIniBase)
private
function getPathDB: String;
procedure setPathDB(const Value: String);
function getUsername: String;
procedure setUsername(const Value: String);
function getPassword: String;
procedure setPassword(const Value: String);
function getServidor: String;
procedure setServidor(const Value: String);
function getURL_API: String;
procedure setURL_API(const Value: String);
function getOperador: String;
procedure setOperador(const Value: String);
function getOperadorCodigo: Integer;
procedure setOperadorCodigo(const Value: Integer);
public
published
property URL_API :String read getURL_API write setURL_API;
property Servidor :String read getServidor write setServidor;
property Caminho :String read getPathDB write setPathDB;
property Usuario :String read getUsername write setUsername;
{ TODO : Encrypt get and setter }
property Senha :String read getPassword write setPassword;
property OperadorNome :String read getOperador write setOperador;
property OperadorCodigo :Integer read getOperadorCodigo write setOperadorCodigo;
end;
TConfigIni = Class(TIniFile)
private
FAcessoBanco :TConfigIniAcessoBanco;
function getAcessoBanco: TConfigIniAcessoBanco;
public
published
property AcessoBanco :TConfigIniAcessoBanco read getAcessoBanco;
end;
var ConfigINI :TConfigIni;
implementation
uses System.IOUtils;
{ TConfigIniBase }
constructor TConfigIniBase.Create(AOwner: TConfigIni);
begin
FOwner := AOwner;
end;
{ TConfigIniAcessoBanco }
function TConfigIniAcessoBanco.getOperador: String;
begin
Result := Owner.ReadString('AcessoBanco', 'OperadorNome', '');
end;
function TConfigIniAcessoBanco.getOperadorCodigo: Integer;
begin
Result := Owner.ReadInteger('AcessoBanco', 'OperadorCodigo', 0);
end;
function TConfigIniAcessoBanco.getPassword: String;
begin
Result := Owner.ReadString('AcessoBanco', 'Password', '');
end;
function TConfigIniAcessoBanco.getPathDB: String;
begin
Result := Owner.ReadString('AcessoBanco', 'PathDB', '');
end;
function TConfigIniAcessoBanco.getServidor: String;
begin
Result := Owner.ReadString('AcessoBanco', 'Servidor', '');
end;
function TConfigIniAcessoBanco.getURL_API: String;
begin
Result := Owner.ReadString('AcessoBanco', 'URL_API', '');
end;
function TConfigIniAcessoBanco.getUsername: String;
begin
Result := Owner.ReadString('AcessoBanco', 'Username', '');
end;
procedure TConfigIniAcessoBanco.setOperador(const Value: String);
begin
Owner.WriteString('AcessoBanco', 'OperadorNome', Value);
end;
procedure TConfigIniAcessoBanco.setOperadorCodigo(const Value: Integer);
begin
Owner.WriteInteger('AcessoBanco', 'OperadorCodigo', Value);
end;
procedure TConfigIniAcessoBanco.setPassword(const Value: String);
begin
Owner.WriteString('AcessoBanco', 'Password', Value);
end;
procedure TConfigIniAcessoBanco.setPathDB(const Value: String);
begin
Owner.WriteString('AcessoBanco', 'PathDB', Value);
end;
procedure TConfigIniAcessoBanco.setServidor(const Value: String);
begin
Owner.WriteString('AcessoBanco', 'Servidor', Value);
end;
procedure TConfigIniAcessoBanco.setURL_API(const Value: String);
begin
Owner.WriteString('AcessoBanco', 'URL_API', Value);
end;
procedure TConfigIniAcessoBanco.setUsername(const Value: String);
begin
Owner.WriteString('AcessoBanco', 'Username', Value);
end;
{ TConfigIni }
function TConfigIni.getAcessoBanco: TConfigIniAcessoBanco;
begin
Result := TConfigIniAcessoBanco.Create(Self);
end;
initialization
{$IFDEF Android}
//ConfigINI := TConfigINI.Create(System.IOUtils.TPath.GetDocumentsPath + System.SysUtils.PathDelim + 'config.ini');
ConfigINI := TConfigINI.Create(TPath.Combine(TPath.GetDocumentsPath, 'config.ini'));
{$ELSE}
ConfigINI := TConfigINI.Create(ExtractFilePath(ParamStr(0)) + 'config.ini');
{$ENDIF}
//ConfigINI.AcessoBanco.URL_API := 'http://192.168.15.184:9000';
//ConfigINI.UpdateFile;
finalization
FreeAndNil(ConfigINI);
end.
|
unit NFe;
interface
uses
RetornoNFe,
Classes;
type
TNFe = class
private
FCodigoNotaFiscal :Integer;
FChaveAcesso :String;
FRetorno :TRetornoNFe;
FXML :TMemoryStream;
FXMLStringList :TStringList;
procedure SetXML(const Value: TMemoryStream);
private
function GetChaveAcesso :String;
function GetCodigoNotaFiscal :Integer;
function GetRetorno :TRetornoNFe;
function GetXML :TMemoryStream;
function GetXMLStringList :TStringList;
function GetXMLText :String;
private
property XMLStringList :TStringList read GetXMLStringList write FXMLStringList;
public
constructor Create(const CodigoNotaFiscal :Integer;
ChaveAcesso :String;
const XML :String = '');
destructor Destroy; override;
public
property CodigoNotaFiscal :Integer read GetCodigoNotaFiscal write FCodigoNotaFiscal;
property ChaveAcesso :String read GetChaveAcesso;
property Retorno :TRetornoNFe read GetRetorno;
property XML :TMemoryStream read GetXML write SetXML;
property XMLText :String read GetXMLText;
public
procedure AdicionarRetorno(Status, Motivo :String);
procedure AdicionarXML (XMLStream :TStringStream); overload;
procedure AdicionarXML (XMLStream :TMemoryStream); overload;
public
function ObtemValorPorTag(const NomeDaTag :String) :String;
end;
implementation
uses
ExcecaoParametroInvalido,
Funcoes,
Repositorio,
FabricaRepositorio,
SysUtils;
{ TNFe }
procedure TNFe.AdicionarRetorno(Status, Motivo :String);
begin
self.FRetorno := TRetornoNFe.Create(self.FCodigoNotaFiscal,
Status,
Motivo);
end;
procedure TNFe.AdicionarXML(XMLStream: TStringStream);
begin
FreeAndNil(self.FXML);
self.FXML := TMemoryStream.Create;
self.FXML.LoadFromStream(XMLStream);
self.FXMLStringList.LoadFromStream(XMLStream);
end;
procedure TNFe.AdicionarXML(XMLStream: TMemoryStream);
begin
FreeAndNil(self.FXML);
self.FXML := TMemoryStream.Create;
self.FXML.LoadFromStream(XMLStream);
self.FXMLStringList.LoadFromStream(XMLStream);
end;
constructor TNFe.Create(const CodigoNotaFiscal: Integer; ChaveAcesso: String; const XML :String);
const
NOME_METODO = 'Create(const CodigoNotaFiscal: Integer; ChaveAcesso: String)';
var
Chave :String;
begin
if (CodigoNotaFiscal <= 0) then
raise TExcecaoParametroInvalido.Create(self.ClassName, NOME_METODO, 'CodigoNotaFiscal');
Chave := ApenasNumeros(ChaveAcesso);
if Chave.IsEmpty or (Length(Chave) <> 44) then
raise TExcecaoParametroInvalido.Create(self.ClassName, NOME_METODO, 'ChaveAcesso');
self.FCodigoNotaFiscal := CodigoNotaFiscal;
self.FChaveAcesso := Chave;
self.FRetorno := nil;
self.FXML := TMemoryStream.Create;
self.FXMLStringList := TStringList.Create;
self.FXMLStringList.Add(XML);
end;
destructor TNFe.Destroy;
begin
FreeAndNil(FRetorno);
FreeAndNil(FXML);
FreeAndNil(FXMLStringList);
inherited;
end;
function TNFe.GetChaveAcesso: String;
begin
result := Trim(self.FChaveAcesso);
end;
function TNFe.GetCodigoNotaFiscal: Integer;
begin
result := self.FCodigoNotaFiscal;
end;
function TNFe.GetRetorno: TRetornoNFe;
var
Repositorio :TRepositorio;
begin
Repositorio := nil;
try
if not Assigned(self.FRetorno) then begin
Repositorio := TFabricaRepositorio.GetRepositorio(TRetornoNFe.ClassName);
self.FRetorno := (Repositorio.Get(self.FCodigoNotaFiscal) as TRetornoNFe);
end;
finally
FreeAndNil(Repositorio);
end;
result := self.FRetorno;
end;
function TNFe.GetXML: TMemoryStream;
begin
result := self.FXML;
end;
function TNFe.GetXMLStringList: TStringList;
begin
if (FXMLStringList.Count <= 0) then
FXMLStringList.LoadFromStream(self.XML);
Result := FXMLStringList;
end;
function TNFe.GetXMLText: String;
begin
result := self.XMLStringList.Text;
end;
function TNFe.ObtemValorPorTag(const NomeDaTag: String): String;
var
nX :Integer;
PosicaoInicial :Integer;
PosicaoFinal :Integer;
QuantidadeDeCorte :Integer;
begin
result := '';
for nX := 0 to (XMLStringList.Count-1) do begin
PosicaoInicial := Pos('<'+NomeDaTag+'>', XMLStringList[nX]);
QuantidadeDeCorte := Length('<'+NomeDaTag+'>');
if (PosicaoInicial > 0) then begin
PosicaoFinal := Pos('</'+NomeDaTag+'>', XMLStringList[nX]);
result := Copy(XMLStringList[nX], (PosicaoInicial + QuantidadeDeCorte), (PosicaoFinal - (PosicaoInicial + QuantidadeDeCorte)));
exit;
end;
end;
end;
procedure TNFe.SetXML(const Value: TMemoryStream);
begin
self.FXML := Value;
end;
end.
|
unit DBAppConfig;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls, DBAppConfigArq, Vcl.ExtCtrls;
type
TFormConfig = class(TForm)
PageControl1: TPageControl;
TabSheet1: TTabSheet;
Label1: TLabel;
EditDiretorio: TEdit;
PanelStatus: TPanel;
procedure FormCreate(Sender: TObject);
procedure PanelStatusClick(Sender: TObject);
procedure EditDiretorioKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
private
ConfigArq : TDBAppConfigArq;
procedure AlertarUsuario(Alerta: string);
procedure InstruirUsuario(Instrucao: string);
public
procedure Salvar;
end;
var
FormConfig: TFormConfig;
implementation
{$R *.dfm}
uses DBAppProblemas;
procedure TFormConfig.AlertarUsuario(Alerta: string);
begin
PanelStatus.Font.Color := clRed;
PanelStatus.Caption := Alerta;
PanelStatus.Visible := true;
end;
procedure TFormConfig.InstruirUsuario(Instrucao: string);
begin
PanelStatus.Font.Color := clBlack;
PanelStatus.Caption := Instrucao;
PanelStatus.Visible := true;
end;
procedure TFormConfig.Salvar;
var
Problema : string;
begin
ConfigArq.DiretorioDeProjetos := Trim(EditDiretorio.Text);
InstruirUsuario('');
if (not ConfigArq.Salvar) then
begin
AlertarUsuario('Não foi possível salvar o arquivo de configuração.');
end;
end;
procedure TFormConfig.EditDiretorioKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
Salvar;
end;
procedure TFormConfig.FormCreate(Sender: TObject);
begin
ConfigArq := TDBAppConfigArq.Create;
EditDiretorio.Text := ConfigArq.DiretorioDeProjetos;
InstruirUsuario('');
if (EditDiretorio.Text = '') then InstruirUsuario('Informe o diretório de projetos.');
end;
procedure TFormConfig.PanelStatusClick(Sender: TObject);
begin
if (ConfigArq.ListaProblemas.Count>0) then
begin
Application.CreateForm(TFormProblemas, FormProblemas);
FormProblemas.DefProblemas(ConfigArq.ListaProblemas);
FormProblemas.ShowModal;
FormProblemas.Free;
end;
end;
end.
|
//WinDu.ScanThreadPool
//
//MIT License
//
//Copyright (c) 2020 ottigeda
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//SOFTWARE.
unit WinDu.ScanThreadPool;
interface
uses
Generics.Collections,
System.Classes,
System.SyncObjs,
System.SysUtils,
WinDu.DirectoryEntry;
type
////////////////////////////////////////////////////////////////////////////////
TScanDirectoryThreadPool = class(TObject)
private
FWork : TList<TDirectoryEntry>;
FWorkMutex : TMutex;
FWorkSema : TSemaphore;
FThreads : TList<TThread>;
public
constructor Create(AInitialWork : TDirectoryEntry);
destructor Destroy; override;
procedure AddWork(item : TDirectoryEntry);
function GetWork(var working : Boolean) : TDirectoryEntry;
procedure WaitWork;
function Working : Boolean;
procedure Stop;
end;
////////////////////////////////////////////////////////////////////////////////
implementation
uses
WinDu.ScanThread;
{ TScanDirectoryThreadPool }
////////////////////////////////////////////////////////////////////////////////
constructor TScanDirectoryThreadPool.Create(AInitialWork : TDirectoryEntry);
var
i : Integer;
begin
FWorkSema := TSemaphore.Create(nil, 0, High(Integer), '');
FWorkMutex := TMutex.Create;
FWork := TList<TDirectoryEntry>.Create;
FThreads := TList<TThread>.Create;
AddWork(AInitialWork);
for i := 0 to 7 do begin
FThreads.Add(TScanDirectoryThread.Create(Self));
end;
end;
////////////////////////////////////////////////////////////////////////////////
destructor TScanDirectoryThreadPool.Destroy;
begin
Stop;
FreeAndNil(FThreads);
FreeAndNil(FWork);
FreeAndNil(FWorkMutex);
FreeAndNil(FWorkSema);
end;
////////////////////////////////////////////////////////////////////////////////
procedure TScanDirectoryThreadPool.Stop;
var
thread : TThread;
begin
for thread in FThreads do begin
thread.Terminate;
end;
for thread in FThreads do begin
FWorkSema.Release;
end;
FThreads.Clear;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TScanDirectoryThreadPool.AddWork(item : TDirectoryEntry);
begin
FWorkMutex.Acquire;
FWork.Add(item);
FWorkMutex.Release;
FWorkSema.Release;
end;
////////////////////////////////////////////////////////////////////////////////
function TScanDirectoryThreadPool.GetWork(var working : Boolean): TDirectoryEntry;
begin
FWorkMutex.Acquire;
Result := nil;
if FWork.Count > 0 then begin
Result := FWork[0];
FWork.Delete(0);
end;
working := Assigned(Result);
FWorkMutex.Release;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TScanDirectoryThreadPool.WaitWork;
begin
FWorkSema.Acquire;
end;
////////////////////////////////////////////////////////////////////////////////
function TScanDirectoryThreadPool.Working: Boolean;
var
thread : TThread;
begin
Result := False;
for thread in FThreads do begin
if (thread as TScanDirectoryThread).Working then begin
Result := True;
end;
end;
end;
////////////////////////////////////////////////////////////////////////////////
end.
|
unit UAppInstances;
interface
uses
Windows, Messages, SysUtils, Classes, Forms;
function HasMultipleInstances(AllowOnlyOne: Boolean): Boolean;
procedure FreeMultipleInstanceCheck;
var
Mutex: THandle;
implementation
Uses
UGlobals;
(*
--- Used Mutex instead checking Windows, Dual Processors will allow two instances
function CheckAllWindows(Handle: HWND; temp: LongInt): Bool; StdCall;
var
WName, CName: array[0..MAX_PATH] of char;
begin
if (GetClassName(Handle, CName, SizeOf(CName)) > 0) and
(StrComp(AppClassName, CName) = 0) and
(GetWindowText(Handle, WName, SizeOf(WName)) > 0) and
(StrComp(AppName, WName) = 0) then
begin
Inc(NumInstances);
if Handle <> Application.Handle then
OtherInstance := Handle;
end;
result := True;
end;
*)
procedure SendParametersTo(AppInstance: HWND);
var
S: String;
i: Integer;
Atom: TAtom;
begin
S := '';
for i := 0 to ParamCount do
begin
S := S + '"' + ParamStr(i) + '"' + ' ';
if POS('.EXE', UpperCase(S))>0 then S := ''; //remove the exe from params
end;
if S = '' then Exit; //nothing to do
Atom := GlobalAddAtom(Pchar(S));
SendMessage(AppInstance, CLK_PARAMSTR, Atom, 0);
GlobalDeleteAtom(Atom);
end;
//Used Mutex instead checking Windows, Dual Processors will allow two instances
function HasMultipleInstances(AllowOnlyOne: Boolean): Boolean;
var
lastPopup: HWND;
OtherInstance: HWND;
ExistingWindowName: string;
begin
result := False;
if not AllowOnlyOne then exit; //can have many, so don't check
//this allows ClickFORMS to run, but not multiple instances.
if AppIsClickForms then
begin
Mutex := CreateMutex(nil,True,'ClickForms_Instance');
if GetLastError = ERROR_ALREADY_EXISTS then
begin
ExistingWindowName := AppTitleClickFORMS;
result := True;
end;
end;
if result then
begin
Application.Title := 'Not Me';
OtherInstance := FindWindow('TApplication', PAnsiChar(ExistingWindowName));
if OtherInstance <> 0 then
begin
SetForegroundWindow(OtherInstance);
if IsIconic(OtherInstance) then
SendMessage(OtherInstance, WM_SYSCOMMAND, SC_RESTORE, 0);
//lastPopup := FindWindow('TMain', PAnsiChar(ExistingWindowName));
lastPopup := GetLastActivePopup(OtherInstance);
SendParametersTo(lastPopup);
end;
end;
end;
procedure FreeMultipleInstanceCheck;
begin
if Mutex <> 0 then
CloseHandle(Mutex);
end;
initialization
Mutex := 0;
end.
|
unit Translator;
interface
type
TKeyData = record
key : String;
value : String;
end;
TTranslator = class(TObject)
public
constructor Create;
function translate(key:String) : String;
procedure add(key:String; value:String);
private
keys : Array of TKeyData;
end;
implementation
constructor TTranslator.Create;
begin
setlength(Self.keys, 1);
end;
function TTranslator.translate(key:String) : String;
var
returnValue : String;
run : Integer;
begin
returnValue := 'undefined';
for run := 0 to high(Self.keys) do
begin
if (Self.keys[run].key = key) then
begin
returnValue := Self.keys[run].value;
end;
end;
Result := returnValue;
end;
procedure TTranslator.add(key:String; value:String);
var
count : Integer;
begin
count := high(Self.keys) + 2;
setlength(Self.keys, count);
Self.keys[count-1].key := key;
Self.keys[count-1].value := value;
end;
end.
|
unit UUADContractFinAssist;
{ ClickForms Application }
{ Bradford Technologies, Inc. }
{ All Rights Reserved }
{ Source Code Copyrighted © 1998-2011 by Bradford Technologies, Inc. }
interface
uses
Windows, ad3Spell, ad3RichEdit, Classes, ComCtrls, Controls, Forms, ExtCtrls, Mask,
RzEdit, StdCtrls, UCell, UContainer, UForms, UGlobals, UUADUtils, Clipbrd, Math, Menus;
type
/// summary: A dialog for editing UAD data points (Contract Financial Assistance).
TdlgUADContractFinAssist = class(TAdvancedForm)
memItemsToBePaid: TAddictRichEdit;
mnuRspCmnts: TPopupMenu;
pmnuCopy: TMenuItem;
pmnuCut: TMenuItem;
pmnuPaste: TMenuItem;
pmnuSelectAll: TMenuItem;
pmnuLine1: TMenuItem;
pmnuSaveCmnt: TMenuItem;
pmnuLine2: TMenuItem;
topPanel: TPanel;
YesAssistanceControl: TRadioButton;
NoAssistanceControl: TRadioButton;
AssistanceAmountControl: TRzNumericEdit;
lblAssistanceAmount: TLabel;
UnknownAssistanceControl: TCheckBox;
lblItemsToBePaid: TLabel;
lblCharsRemaining: TLabel;
stCharBal: TStaticText;
botPanel: TPanel;
bbtnClear: TButton;
bbtnSave: TButton;
bbtnCancel: TButton;
bbtnHelp: TButton;
procedure FormShow(Sender: TObject);
procedure BuildCmntMenu;
procedure OnSaveCommentExecute(Sender: TObject);
procedure AssistanceExistsControlClick(Sender: TObject);
procedure bbtnClearClick(Sender: TObject);
procedure bbtnHelpClick(Sender: TObject);
procedure bbtnSaveClick(Sender: TObject);
procedure memItemsToBePaidChange(Sender: TObject);
procedure mnuRspCmntsPopup(Sender: TObject);
procedure pmnuCopyClick(Sender: TObject);
procedure pmnuPasteClick(Sender: TObject);
procedure pmnuSelectAllClick(Sender: TObject);
procedure pmnuCutClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
FClearData : Boolean;
FUADCell: TBaseCell;
FDocument: TContainer;
FNoAssistanceCell: TChkBoxCell;
FPurchaseTransactionCell: TChkBoxCell;
FYesAssistanceCell: TChkBoxCell;
procedure OnInsertComment(Sender: TObject);
procedure EnableAssistanceControls(const Enable: Boolean);
function GetDisplayText(const Cmnts: String): String;
procedure AdjustDPISettings;
public
FCell: TBaseCell;
MainAddictSpell: TAddictSpell3;
procedure Clear;
procedure LoadForm;
procedure SaveToCell;
end;
var
StdPmnuCnt: Integer;
implementation
{$R *.dfm}
Uses
Messages, SysUtils, UPage, UStatus, UStdCmtsEdit, UStdRspUtil, UStrings, UUtil1;
procedure TdlgUADContractFinAssist.bbtnHelpClick(Sender: TObject);
begin
ShowUADHelp('FILE_HELP_UAD_FINANCIAL_ASSIST', Caption);
end;
procedure TdlgUADContractFinAssist.AdjustDPISettings;
begin
botPanel.Top := self.Height - botPanel.Height;
bbtnHelp.Left := botPanel.Width - bbtnHelp.Width - 5;
bbtnCancel.Left := bbtnHelp.Left - bbtnCancel.Width - 5;
bbtnSave.Left := bbtnCancel.Left - bbtnSave.Width - 5;
bbtnClear.Left := 10;
end;
procedure TdlgUADContractFinAssist.FormShow(Sender: TObject);
begin
AdjustDPISettings;
if appPref_UADContractFinAssistDlgWidth > Constraints.MinWidth then
if appPref_UADContractFinAssistDlgWidth > Screen.WorkAreaWidth then
Width := Screen.WorkAreaWidth
else
Width := appPref_UADContractFinAssistDlgWidth;
if appPref_UADContractFinAssistDlgHeight > Constraints.MinHeight then
if appPref_UADContractFinAssistDlgHeight > Screen.WorkAreaHeight then
Height := Screen.WorkAreaHeight
else
Height := appPref_UADContractFinAssistDlgHeight;
LoadForm;
memItemsToBePaid.AddictSpell := MainAddictSpell;
// saved comment responses
StdPmnuCnt := mnuRspCmnts.Items.Count;
BuildCmntMenu;
end;
/// Builds the comment response into the memo.
procedure TdlgUADContractFinAssist.BuildCmntMenu;
var
CommentGroup: TCommentGroup;
Index: Integer;
begin
CommentGroup := AppComments[FCell.FResponseID];
CommentGroup.BulidPopupCommentMenu(mnuRspCmnts);
for Index := Max(StdPmnuCnt, 0) to mnuRspCmnts.Items.Count - 1 do
mnuRspCmnts.Items[Index].OnClick := OnInsertComment;
end;
/// summary: Inserts text from a saved comment response into the memo.
procedure TdlgUADContractFinAssist.OnInsertComment(Sender: TObject);
var
Edit: TAddictRichEdit;
Index: Integer;
Item: TMenuItem;
Text: String;
begin
if (Sender is TMenuItem) and (ActiveControl is TAddictRichEdit) then
begin
Item := Sender as TMenuItem;
Edit := ActiveControl as TAddictRichEdit;
Text := AppComments[FCell.FResponseID].GetComment(Item.Tag);
for Index := 1 to Length(Text) do
SendMessage(Edit.Handle, WM_CHAR, Integer(Text[Index]), 0);
end;
end;
/// summary: Saves text to the saved comments list.
procedure TdlgUADContractFinAssist.OnSaveCommentExecute(Sender: TObject);
var
Edit: TAddictRichEdit;
EditCommentsForm: TEditCmts;
ModalResult: TModalResult;
Text: String;
Index: Integer;
begin
if (ActiveControl is TAddictRichEdit) then
begin
Edit := ActiveControl as TAddictRichEdit;
Text := Edit.SelText;
if (Text = '') then
Text := Edit.Text;
EditCommentsForm := TEditCmts.Create(Self);
try
EditCommentsForm.LoadCommentGroup(FCell.FResponseID);
EditCommentsForm.LoadCurComment(Text);
ModalResult := EditCommentsForm.ShowModal;
if (ModalResult = mrOK) and (EditCommentsForm.Modified) then
EditCommentsForm.SaveCommentGroup;
finally
FreeAndNil(EditCommentsForm);
end;
end;
for Index := mnuRspCmnts.Items.Count - 1 downto Max(StdPmnuCnt, 0) do
mnuRspCmnts.Items.Delete(Index);
BuildCmntMenu;
end;
/// summary: Sets whether assistance controls are enabled.
procedure TdlgUADContractFinAssist.AssistanceExistsControlClick(Sender: TObject);
begin
EnableAssistanceControls(YesAssistanceControl.Checked);
end;
/// summary: Clears all the data from the form.
procedure TdlgUADContractFinAssist.bbtnClearClick(Sender: TObject);
begin
if WarnOK2Continue(msgUAGClearDialog) then
begin
Clear;
FClearData := True;
SaveToCell;
ModalResult := mrOK;
end;
end;
/// summary: Validates the form and saves data to the cell.
procedure TdlgUADContractFinAssist.bbtnSaveClick(Sender: TObject);
begin
if YesAssistanceControl.Checked then
begin
if not UnknownAssistanceControl.Checked and ((AssistanceAmountControl.Text = '') or (AssistanceAmountControl.Value < 1)) then
begin
ShowAlert(atWarnAlert, 'The financial assistance amount must be > $0 when ALL assistance amounts are known.');
AssistanceAmountControl.SetFocus;
Abort;
end
else if UnknownAssistanceControl.Checked and ((AssistanceAmountControl.Text <> '') and (AssistanceAmountControl.Value < 1)) then
begin
ShowAlert(atWarnAlert, 'The financial assistance amount must be > $0 when some assistance amounts are unknown or blank if ALL assistance amounts are unknown.');
AssistanceAmountControl.SetFocus;
Abort;
end
else if (Trim(memItemsToBePaid.Text) = '') then
begin
ShowAlert(atWarnAlert, 'The consession items to be paid must be entered.');
memItemsToBePaid.SetFocus;
Abort;
end
end
else if (FPurchaseTransactionCell.Text = 'X') and (not NoAssistanceControl.Checked) then
begin
ShowAlert(atWarnAlert, 'For purchase transactions, you must indicate whether there is any financial assistance.');
Abort;
end
else if NoAssistanceControl.Checked and ((AssistanceAmountControl.Text <> '') and (AssistanceAmountControl.Text <> '$0')) then
begin
ShowAlert(atWarnAlert, 'The financial assistance amount must be blank or zero when no assistance is selected.');
AssistanceAmountControl.SetFocus;
Abort;
end;
SaveToCell;
ModalResult := mrOK;
end;
/// summary: Enables or disables controls on the assistance panel.
procedure TdlgUADContractFinAssist.EnableAssistanceControls(const Enable: Boolean);
begin
if not Enable then
begin
AssistanceAmountControl.Text := '$0';
UnknownAssistanceControl.Checked := False;
UnknownAssistanceControl.Enabled := False;
end
else
UnknownAssistanceControl.Enabled := True;
end;
/// summary: Formats the display text for the cell using the comments provided.
function TdlgUADContractFinAssist.GetDisplayText(const Cmnts: String): String;
var
AssistanceAmountText: String;
UnknownAssistanceText: String;
begin
if (AssistanceAmountControl.Text <> '') then
AssistanceAmountText := '$' + IntToStr(Trunc(AssistanceAmountControl.Value));
if UnknownAssistanceControl.Checked then
UnknownAssistanceText := UADUnkFinAssistance
else
UnknownAssistanceText := '';
Result := Format('%s;%s;%s', [AssistanceAmountText, UnknownAssistanceText, Cmnts]);
if Trim(Result) = '' then
Result := ' ';
end;
/// summary: Clears all the data from the form.
procedure TdlgUADContractFinAssist.Clear;
begin
NoAssistanceControl.Checked := False;
YesAssistanceControl.Checked := False;
memItemsToBePaid.Clear;
AssistanceAmountControl.Text := '';
UnknownAssistanceControl.Checked := False;
end;
procedure TdlgUADContractFinAssist.LoadForm;
const
CXID_AssignmentType_PurchaseTransaction = 2059;
var
Page: TDocPage;
TmpStr, UADText: String;
PosIdx: Integer;
begin
Clear;
FDocument := FCell.ParentPage.ParentForm.ParentDocument as TContainer;
Page := FCell.ParentPage as TDocPage;
FUADCell := Page.GetCellByID(StrToInt(memItemsToBePaid.Hint));
FNoAssistanceCell := Page.GetCellByID(StrToInt(NoAssistanceControl.Hint)) as TChkBoxCell;
FYesAssistanceCell := Page.GetCellByID(StrToInt(YesAssistanceControl.Hint)) as TChkBoxCell;
FPurchaseTransactionCell := Page.GetCellByID(CXID_AssignmentType_PurchaseTransaction) as TChkBoxCell;
NoAssistanceControl.Checked := (FNoAssistanceCell.Text = 'X');
YesAssistanceControl.Checked := (FYesAssistanceCell.Text = 'X');
// Step 1: pick out the UAD text from the cell
PosIdx := Pos(';See comments -', FCell.Text);
if PosIdx = 0 then
UADText := ''
else
UADText := Copy(FCell.Text, 1, PosIdx);
// Step 2: get the linked comments
TmpStr := GetUADLinkedComments(FDocument, FUADCell);
// Restore paragraph breaks when retrieving text from a UAD comment page cell
TmpStr := StringReplace(TmpStr, #10, #13#10, [rfReplaceAll]);
// Step 3: get comments from the data point if no linked comments
if TmpStr = '' then
begin
if Length(UADText) = 0 then
memItemsToBePaid.Text := FUADCell.GSEDataPoint['2057']
else
TmpStr := UADText + FUADCell.GSEDataPoint['2057'];
end;
// Step 4: prepend the UAD text if it was not retrieved in the prior steps
if Length(TmpStr) > 0 then
begin
PosIdx := Pos(UADText, TmpStr);
if PosIdx = 0 then
TmpStr := UADText + TmpStr;
end;
// Step 5: parse the text into its component parts
if Length(TmpStr) > 0 then
begin
PosIdx := Pos(';', TmpStr);
if PosIdx > 0 then
begin
if PosIdx > 1 then
AssistanceAmountControl.Text := '$' + IntToStr(GetValidInteger(Copy(TmpStr, 1, Pred(PosIdx))));
TmpStr := Copy(TmpStr, Succ(PosIdx), Length(TmpStr));
PosIdx := Pos(';', TmpStr);
if PosIdx > 0 then
begin
if (Copy(TmpStr, 1, Pred(PosIdx)) = UADUnkFinAssistance) and YesAssistanceControl.Checked then
UnknownAssistanceControl.Checked := True;
memItemsToBePaid.Text := Copy(TmpStr, Succ(PosIdx), Length(TmpStr));
end
else
memItemsToBePaid.Text := TmpStr;
end
else
memItemsToBePaid.Text := TmpStr;
end;
// Strip any extra CfLf pair from the end of the text.
if (Length(memItemsToBePaid.Text) > 1) and (Copy(memItemsToBePaid.Text, Pred(Length(memItemsToBePaid.Text)), 2) = #13#10) then
memItemsToBePaid.Text := Copy(memItemsToBePaid.Text, 1, (Length(memItemsToBePaid.Text) - 2));
end;
procedure TdlgUADContractFinAssist.SaveToCell;
var
Page: TDocPage;
DisplayText: String;
TestCell: TBaseCell;
procedure SetCheckmark(XIDStr: String; IsChecked: Boolean);
var
TmpCell: TBaseCell;
begin
TmpCell := Page.GetCellByID(StrToInt(XIDStr));
if (TmpCell is TChkBoxCell) then
begin
if IsChecked then
TmpCell.DoSetText('X')
else
TmpCell.DoSetText(' ');
FDocument.Switch2NewCell(TmpCell, False);
FDocument.Switch2NewCell(FCell, False);
end;
end;
begin
Page := FCell.ParentPage as TDocPage;
SetCheckmark(YesAssistanceControl.Hint, YesAssistanceControl.Checked);
SetCheckmark(NoAssistanceControl.Hint, NoAssistanceControl.Checked);
// Remove any legacy data - no longer used
FUADCell.GSEData := '';
// If the text will NOT overflow then null any prior overflow section
// by setting the LinkedCommentCell to a null GUID. If it WILL overflow
// then leave the section so it can be reused and the text replaced.
DisplayText := GetDisplayText(memItemsToBePaid.Text);
TestCell := FUADCell;
if not UADTextWillOverflow(TestCell, DisplayText) then
(FUADCell as TTextBaseCell).LinkedCommentCell := GUID_NULL;
// If the focus is one of the check boxes switch to the comment cell
// to trigger overflow operations.
if FCell.FCellXID <> FUADCell.FCellXID then
FDocument.Switch2NewCell(FUADCell, False);
// Save the cleared or formatted text
if FClearData then // clear ALL GSE data and blank the cell
begin
// SetCheckmark(YesAssistanceControl.Hint, False);
// SetCheckmark(NoAssistanceControl.Hint, False);
FUADCell.Text := '';
end
else
begin
// SetCheckmark(YesAssistanceControl.Hint, YesAssistanceControl.Checked);
// SetCheckmark(NoAssistanceControl.Hint, NoAssistanceControl.Checked);
FUADCell.Text := DisplayText;
end;
end;
procedure TdlgUADContractFinAssist.memItemsToBePaidChange(Sender: TObject);
begin
stCharBal.Caption := IntToStr(memItemsToBePaid.MaxLength - Length(memItemsToBePaid.Text));
end;
procedure TdlgUADContractFinAssist.mnuRspCmntsPopup(Sender: TObject);
begin
pmnuCopy.Enabled := ((memItemsToBePaid.SelLength > 0) and IsBitSet(appPref_AddEM2PUpPref, bAddEMCopy));
pmnuCut.Enabled := ((memItemsToBePaid.SelLength > 0) and IsBitSet(appPref_AddEM2PUpPref, bAddEMCut));
pmnuPaste.Enabled := ((Length(ClipBoard.AsText) > 0) and IsBitSet(appPref_AddEM2PUpPref, bAddEMPaste));
pmnuSelectAll.Enabled := (Length(memItemsToBePaid.Text) > 0);
pmnuSaveCmnt.Enabled := (memItemsToBePaid.SelLength > 0);
end;
procedure TdlgUADContractFinAssist.pmnuCopyClick(Sender: TObject);
begin
memItemsToBePaid.CopyToClipboard;
end;
procedure TdlgUADContractFinAssist.pmnuPasteClick(Sender: TObject);
begin
memItemsToBePaid.PasteFromClipboard;
end;
procedure TdlgUADContractFinAssist.pmnuSelectAllClick(Sender: TObject);
begin
memItemsToBePaid.SelectAll;
end;
procedure TdlgUADContractFinAssist.pmnuCutClick(Sender: TObject);
begin
if memItemsToBePaid.SelText <> '' then
begin
memItemsToBePaid.CopyToClipboard;
memItemsToBePaid.SelText := '';
end;
end;
procedure TdlgUADContractFinAssist.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
appPref_UADContractFinAssistDlgWidth := Width;
appPref_UADContractFinAssistDlgHeight := Height;
end;
end.
|
{ AudioSDL.pas - Sound subsystem of VesaSDL
Copyright (c) 2015-2017 NFS_MONSTR(Maxim Belyaev)
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions :
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgement in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
}
unit AudioSDL;
interface
uses
SDL2_mixer;
const
// channels for initaudio
mono = 1;
stereo = 2;
// channel for playEffect
all = -1;
procedure InitAudio (channels : word);
procedure DoneAudio;
function LoadMusic (path : ansistring) : pointer;{WAVE,MOD,MIDI,OGG,MP3,FLAC}
function LoadSound (path : ansistring) : pointer;{WAVE AIFF RIFF OGG VOC}
procedure PlayMusic (p : pointer; countplays : word);
function PlayingMusic : boolean;
procedure PauseMusic;
function PausedMusic : boolean;
procedure ResumeMusic;
procedure StopMusic;
procedure PlaySound (p : pointer; channel : integer; countplays : word);
procedure SetVolumeAll (c : integer);
procedure SetMusicPosition (c : double);
implementation
procedure InitAudio (channels : word);
begin
if (mix_openaudio(44100, MIX_DEFAULT_FORMAT, channels, 2048) < 0) then
writeln('Error while initializing audio');
end;
procedure DoneAudio;
begin
mix_closeaudio;
end;
function loadmusic (path : ansistring) : pointer;
var
p : pointer;
begin
p := mix_loadmus(pchar(path));
if (p = nil) then
writeln('Error while loading ' + path);
loadmusic := p;
end;
function loadsound (path : ansistring) : pointer;
begin
loadsound := mix_loadwav(pchar(path));
end;
procedure PlayMusic(p : pointer; countplays : word);
begin
mix_playmusic(p, countplays);
end;
function PlayingMusic : boolean;
begin
playingmusic := boolean(mix_playingmusic);
end;
procedure PauseMusic;
begin
Mix_PauseMusic;
end;
function PausedMusic : boolean;
begin
pausedmusic := boolean(mix_pausedmusic);
end;
procedure ResumeMusic;
begin
mix_resumemusic;
end;
procedure StopMusic;
begin
Mix_haltMusic;
end;
procedure Playsound (p : pointer; channel : integer; countplays : word);
begin
mix_playchannel(channel, p, countplays);
end;
procedure SetVolumeAll (c : integer);
begin
if (c > mix_max_volume) then
c := mix_max_volume;
if (c < 0) then
c := 0;
mix_volume(all, c);
mix_volumemusic(c);
end;
procedure SetMusicPosition (c : double);
begin
mix_rewindmusic;
if (mix_setmusicposition(c) <> 0) then
writeln(mix_geterror);
end;
begin
end.
|
unit changeEvent;
interface
uses Generics.Collections;
type
// databaze funkci k zavolani pri urcite udalosti (napr. pri obsazeni useku se vola uzavreni prejezdu do jizdni cesty)
TChangeEventFunc = procedure(Sender:TObject; data:Integer) of object;
TChangeEvent = record
func:TChangeEventFunc;
data:Integer;
end;
TChangeEvents = TList<TChangeEvent>;
function CreateChangeEvent(func:TChangeEventFunc; data:Integer):TChangeEvent;
implementation
function CreateChangeEvent(func:TChangeEventFunc; data:Integer):TChangeEvent;
begin
Result.func := func;
Result.data := data;
end;
end.
|
unit UBank;
interface
uses USimulation;
type
// Класс TClient - процесс, моделирующий клиента банка
TClient = class(TProcess)
protected
procedure RunProcess; override;
end;
// Класс TClientGenerator - процесс, порождающий клиентов банка
TClientGenerator = class(TProcess)
protected
procedure RunProcess; override;
end;
// Класс TCashman - процесс, моделирующий работу кассира
TCashman = class(TProcess)
protected
procedure RunProcess; override;
end;
// Класс TBankSimulation - моделирование работы банка
TBankSimulation = class(TSimulation)
public
// Кассир
Cashman : TCashman;
// Генератор клиентов
Generator : TClientGenerator;
// Очередь ожидания
Queue : TList;
// Статистика и гистограмма по времени пребывания
// клиентов в банке
InBankTime : TStatistics;
InBankHist : THistogram;
// Статистика по занятости кассира
CashStat : TServiceStatistics;
// Счетчик клиентов, обслуженных без ожидания
NotWaited : Integer;
destructor Destroy; override;
procedure StopStat; override;
protected
procedure RunSimulation; override;
procedure Init; override;
end;
var
// Датчики случайных чисел
rndClient : TRandom;
rndCashman : TRandom;
// Количество обслуживаемых клиентов
MaxClientCount : Integer = 100;
// Средний интервал между прибытием клиентов
MeanClientInterval : Double = 5;
// Границы времени обслуживания
MinCashTime : Double = 2;
MaxCashTime : Double = 6;
// Параметры гистограммы
HistMin : Double = 2;
HistStep : Double = 2;
HistStepCount : Integer = 20;
// Временной шаг визулизации имитации
VisTimeStep : Double = 0.5;
implementation
{ TClient }
procedure TClient.RunProcess;
var
par : TBankSimulation;
begin
par := Parent as TBankSimulation;
// Активировать кассу
par.Cashman.ActivateDelay(0);
// Встать в очередь и ждать обслуживания
Wait(par.Queue);
// Встать в очередь завершенных процессов
Finish;
end;
{ TClientGenerator }
procedure TClientGenerator.RunProcess;
var
i : Integer;
begin
for i := 1 to MaxClientCount do
begin
ClearFinished;
TClient.Create.ActivateDelay(0);
Hold(rndClient.Exponential(MeanClientInterval));
end;
end;
{ TCashman }
procedure TCashman.RunProcess;
var
Client : TClient;
InTime : Double;
par : TBankSimulation;
begin
par := Parent as TBankSimulation;
while True do
begin
// Если очередь пуста, ждать прибытия клиента
while par.Queue.Empty do
Passivate;
// Извлечь первого клиента из очереди
Client := par.Queue.First as TClient;
Client.StartRunning;
// Если клиент не ждал, учесть его
if Client.StartingTime = SimTime then
Inc(par.NotWaited);
// Выполнить обслуживание
par.CashStat.Start(SimTime);
Hold(rndCashman.Uniform(MinCashTime, MaxCashTime));
par.CashStat.Finish(SimTime);
// Учесть полное время пребывания в банке
InTime := SimTime - Client.StartingTime;
par.InBankTime.AddData(InTime);
par.InBankHist.AddData(InTime);
// Возобновить клиента, дав ему возможность
// закончить работу
Client.ActivateDelay(0);
// Если все клиенты обслужены, завершить работу
if par.CashStat.Finished = MaxClientCount then
par.ActivateDelay(0);
end;
end;
{ TBankSimulation }
destructor TBankSimulation.Destroy;
begin
Cashman.Free;
Generator.Free;
InBankTime.Free;
InBankHist.Free;
CashStat.Free;
Queue.Free;
inherited;
end;
procedure TBankSimulation.Init;
begin
inherited;
Queue := TList.Create;
Cashman := TCashman.Create;
Generator := TClientGenerator.Create;
InBankTime := TStatistics.Create;
CashStat := TServiceStatistics.Create(1);
InBankHist := TUniformHistogram.Create(HistMin, HistStep, HistStepCount);
NotWaited := 0;
MakeVisualizator(VisTimeStep);
end;
procedure TBankSimulation.RunSimulation;
begin
// Запустить процесс создания клиентов
Generator.ActivateDelay(0);
// Ждать конца имитации
Passivate;
StopStat;
end;
procedure TBankSimulation.StopStat;
begin
inherited;
Queue.StopStat(SimTime);
CashStat.StopStat(SimTime);
end;
end.
|
unit TestSpringParser;
interface
uses
Classes,
SysUtils,
TestFramework,
DelphiAST.Classes,
FindUnit.Header,
FindUnit.PasParser,
Generics.Collections;
type
TestTSpringParser = class(TTestCase)
strict private
FPasFileParser: TPasFileParser;
private
FFilePath: string;
function CompareListWithText(List: TStrings; ExpectItems: TArray<string>): Boolean;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestParse;
end;
implementation
uses
FindUnit.Utils;
const
TEST_FILE_NAME = 'Spring';
{ TestTSpringParser }
function TestTSpringParser.CompareListWithText(List: TStrings; ExpectItems: TArray<string>): Boolean;
var
I: Integer;
begin
Result := List.Count = Length(ExpectItems);
if not Result then
Exit;
for I := 0 to Length(ExpectItems) -1 do
if List.IndexOf(ExpectItems[I]) = -1 then
Exit(False);
end;
procedure TestTSpringParser.SetUp;
begin
FFilePath := ExtractFilePath(ParamStr(0));
FFilePath := Fetch(FFilePath, '\Test\');
FFilePath := FFilePath + '\Test\TestPasParser\' + TEST_FILE_NAME + '.pas';
FPasFileParser := TPasFileParser.Create(FFilePath);
end;
procedure TestTSpringParser.TearDown;
begin
FPasFileParser.Free;
FPasFileParser := nil;
end;
procedure TestTSpringParser.TestParse;
var
PasResult: TPasFile;
begin
PasResult := FPasFileParser.Process;
Assert(PasResult.FilePath = FFilePath, 'Wrong file path');
Assert(PasResult.OriginUnitName = TEST_FILE_NAME, 'Wrong file path');
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTSpringParser.Suite);
end.
|
{******************************************************************************}
{ }
{ WiRL: RESTful Library for Delphi }
{ }
{ Copyright (c) 2015-2019 WiRL Team }
{ }
{ https://github.com/delphi-blocks/WiRL }
{ }
{******************************************************************************}
unit WiRL.Tests.Framework.Serialization;
interface
uses
System.SysUtils,
DUnitX.TestFramework,
WiRL.Core.JSON,
Neon.Core.Persistence.JSON;
type
TBasicObject = class
private
FName: string;
FAge: Integer;
public
property Name: string read FName write FName;
property Age: Integer read FAge write FAge;
end;
TCompositeObject = class
private
FBasic: TBasicObject;
FValue: string;
public
property Basic: TBasicObject read FBasic write FBasic;
property Value: string read FValue write FValue;
end;
[TestFixture]
TTestSerialization = class(TObject)
public
[Setup]
procedure Setup;
[TearDown]
procedure TearDown;
[Test]
procedure TestBasicObjectSerialization;
[Test]
procedure TestBasicObjectDeserialization;
[Test]
procedure TestCompositeObjectSerialization;
end;
implementation
{ TTestSerialization }
procedure TTestSerialization.Setup;
begin
end;
procedure TTestSerialization.TearDown;
begin
end;
procedure TTestSerialization.TestBasicObjectDeserialization;
var
LBasicObject: TBasicObject;
begin
LBasicObject := TNeon.JsonToObject<TBasicObject>('{"Name": "Luca", "Age": 42}');
try
Assert.AreEqual('Luca', LBasicObject.Name);
Assert.AreEqual(42, LBasicObject.Age);
finally
LBasicObject.Free;
end;
end;
procedure TTestSerialization.TestBasicObjectSerialization;
var
LBasicObject: TBasicObject;
LJson: TJSONValue;
begin
LBasicObject := TBasicObject.Create;
try
LBasicObject.Name := 'Luca';
LBasicObject.Age := 42;
LJson := TNeon.ObjectToJSON(LBasicObject);
try
Assert.AreEqual('Luca', LJson.GetValue<string>('Name'));
Assert.AreEqual(42, LJson.GetValue<Integer>('Age'));
finally
LJson.Free;
end;
finally
LBasicObject.Free;
end;
end;
procedure TTestSerialization.TestCompositeObjectSerialization;
var
LCompositeObject: TCompositeObject;
LJson, LJsonBasic: TJSONValue;
begin
LCompositeObject := TCompositeObject.Create;
try
LCompositeObject.Basic := TBasicObject.Create;
try
LCompositeObject.Basic.Name := 'Luca';
LCompositeObject.Basic.Age := 42;
LJson := TNeon.ObjectToJSON(LCompositeObject);
try
LJsonBasic := LJson.GetValue<TJSONValue>('Basic');
Assert.AreEqual('Luca', LJsonBasic.GetValue<string>('Name'));
Assert.AreEqual(42, LJsonBasic.GetValue<Integer>('Age'));
finally
LJson.Free;
end;
finally
LCompositeObject.Basic.Free;
end;
finally
LCompositeObject.Free;
end;
end;
initialization
TDUnitX.RegisterTestFixture(TTestSerialization);
end.
|
unit PDBVendorEdit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
stdctrls, dbtables, extctrls, RxCtrls, dbctrls, db, SelectDlg, PLabelPanel
,buttons, LookupControls;
type
TPDBVendorEdit = class(TPLookupControl)
private
{ Private declarations }
FEdit: TDBEdit;
//FDataLink: TDataLink;
FFieldLink: TFieldDataLink;
{FKeyFieldCaption: string;
FListFieldCaption: string;}
FPartialKey: Boolean;
//FParentFont: Boolean;
protected
{ Protected declarations }
function FindCurrent(var LabelText: string):Boolean;override;
function GetDataField: String;
function GetDataSource: TDataSource;
{function GetEditFont:TFont;
function GetEditWidth:integer;}
function GetReadOnly: Boolean;
function GetRdOnly:Boolean; override;
function GetText:string;override;
{procedure BtnHelpClick(Sender: TObject);
//procedure CMFocusChanged(var Message: TCMFocusChanged); message CM_FOCUSCHANGED;
procedure ControlChange(Sender: TObject);override;
procedure ControlClick(Sender: TObject);override;
procedure ControlEnter(Sender: TObject);override;
procedure ControlDblClick(Sender: TObject); override;
procedure ControlExit(Sender: TObject);override;
procedure DataChange(Sender: TObject; Field: TField);
procedure EditKeyPress(Sender: TObject; var Key: Char); override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;}
procedure SetActive(Value: Boolean);override;
//procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
procedure SetDatabaseName(Value: string);override;
{procedure SetEditFont(Value: TFont);
procedure SetEditWidth(Value: integer);}
procedure SetDataField(Value: String);
procedure SetDataSource(Value: TDataSource);
procedure SetLookField(Value: string);override;
procedure SetLookSubField(Value: string);override;
procedure SetRdOnly(Value: Boolean);
procedure SetReadOnly(Value: Boolean);
//procedure SetParentFont(Value: Boolean);override;
procedure SetText(Value : string);override;
//procedure Paint;override;
procedure CreateEditCtrl; override;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy;override;
property CheckResult;
{procedure HideHelpButton;
procedure ShowHelpButton;}
published
property Active;
property Caption;
property DatabaseName;
property DataField: string read GetDataField write SetDataField;
property DataSource :TDataSource read GetDataSource write SetDataSource;
{property EditFont:TFont read GetEditFont write SetEditFont;
property EditWidth:integer read GetEditWidth write SetEditWidth;}
property Filter;
property LabelStyle;
property ListFieldControl;
//property ParentFont : Boolean read FParentFont write SetParentFont;
property PartialKey:Boolean read FPartialKey write FPartialKey;
property ReadOnly: Boolean read GetReadOnly Write SetReadOnly;
property RdOnly: Boolean read GetRdOnly write SetRdOnly;
property TabOrder;
property TabStop;
{property OnChange;
property OnEnter ;
property OnExit ;
property OnClick;
property OnDblClick;}
end;
procedure Register;
implementation
function TPDBVendorEdit.GetRdOnly:Boolean;
begin
Result := FEdit.ReadOnly;
end;
procedure TPDBVendorEdit.SetRdOnly(Value: Boolean);
begin
FEdit.ReadOnly := Value;
if Value then
FEdit.Color := clSilver
else
FEdit.Color := clWhite;
end;
{
function TPDBVendorEdit.GetEditWidth:integer;
begin
Result := FEdit.Width;
end;
procedure TPDBVendorEdit.SetEditWidth(Value: integer);
begin
FEdit.Width := Value;
FEdit.Left := Width-Value;
FLabel.Width := FEdit.Left;
end;
function TPDBVendorEdit.GetEditFont:TFont;
begin
Result := FEdit.Font;
end;
procedure TPDBVendorEdit.SetEditFont(Value: TFont);
begin
FEdit.Font.Assign(Value);
FLabel.Font.Assign(Value);
FLabel.Height := FEdit.Height;
Height := FEdit.Height;
SetLabelStyle(LabelStyle);
end;
}
procedure TPDBVendorEdit.SetDatabaseName(Value: string);
begin
inherited;
if csLoading in ComponentState then
begin
FDatabaseName := Value;
TableName := 'tbVendor';//设置表名
KeyField := 'Vendor';
ListField := 'name';
KeyFieldCaption := '厂商号';
ListFieldCaption := '名称';
end
else
if Active then
begin
raise EOperationInvalid.Create('Can''t change TableName while Active is True.');
exit;
end
else
begin
FDatabaseName := Value;
TableName := 'tbVendor';//设置表名
KeyField := 'Vendor';
ListField := 'cname';
end;
end;
{
procedure TPDBVendorEdit.Paint;
begin
FLabel.Height := Height;
FEdit.Height := Height;
FLabel.Width := Width-FEdit.Width -FHelp.Width - 2;
FEdit.Left := FLabel.Width;
FHelp.Left := FLabel.Width + FEdit.Width + 2;
SetLabelStyle(LabelStyle);
inherited Paint;
end;
}
procedure TPDBVendorEdit.SetActive(Value: Boolean);
begin
if csLoading in ComponentState then
FActive := Value
else
if Value <> FActive then
begin
if Value then
OpenQuery;
FActive := Value;
end;
end;
procedure TPDBVendorEdit.SetText(Value : string);
begin
if FEdit.Text <> Value then
begin
FEdit.Text := Value;
DataSource.Edit;
DataSource.DataSet.FieldByName( FEdit.Field.FieldName).AsString := FEdit.Text;
controlchange(self);
end;
end;
function TPDBVendorEdit.GetText: string;
begin
Result := FEdit.Text;
end;
procedure TPDBVendorEdit.SetLookField(Value: string);
begin
if FKeyField <> Value then
FKeyField := Value;
end;
procedure TPDBVendorEdit.SetLookSubField(Value: string);
begin
if FListField <> Value then
FListField := Value;
end;
function TPDBVendorEdit.FindCurrent(var LabelText: string):Boolean;
var tmpQuery: TQuery;
begin
Result := False;
LabelText := '';
if FEdit.Text = '' then Exit;
if PartialKey and (FQuery.FieldByName(FKeyField).DataType in [ftString]) then
begin
try
tmpQuery := TQuery.Create(Self);
tmpQuery.DatabaseName := FDatabaseName;
tmpQuery.SQL.Add('Select * from '+FTableName);
{tmpQuery.SQL.Add(' where '+FKeyField+' LIKE :Param1');
tmpQuery.ParamByName('Param1').AsString := FEdit.Text+'%';}
tmpQuery.SQL.Add(format(' where %s LIKE ''%s'' ',[FKeyField,FEdit.Text+'%']));
tmpQuery.Filter := Filter;
tmpQuery.Filtered := True;
tmpQuery.Open;
if tmpQuery.RecordCount < 1 then
begin
Result := False;
LabelText := '';
end
else
if tmpQuery.RecordCount =1 then
begin
tmpQuery.First;
Result := True;
if FListField <> '' then
begin
LabelText := tmpQuery.FieldByName(FListField).AsString;
FEdit.Field.Value := LabelText;
end
else
LabelText := '';
end
else
begin
Result := True;
LabelText := '';
end;
tmpQuery.Free;
except
on Exception do
begin
Result := False;
LabelText := '';
tmpQuery.Free;
Exit;
end;
end;
end
else
begin
try
if FQuery.Locate(FKeyField, FEdit.Text,[]) then
begin
Result := True;
if FListField <> '' then
LabelText := FQuery.FieldByName(FListField).AsString
else
LabelText := '';
Exit;
end;
except
on Exception do;
end;
end;
end;
constructor TPDBVendorEdit.Create(AOwner: TComponent);
var tmpBitmap: TBitmap;
begin
inherited Create(AOwner);
//FDataLink := TDataLink.Create;
FFieldLink := TFieldDataLink.Create;
FFieldLink.OnDataChange := DataChange;
FEdit.DataSource := DataSource;
{FEdit := TDBEdit.Create(Self);
FEdit.Parent := Self;
FEdit.Visible := True;
FEdit.DataSource := DataSource;
FEdit.Font.Size := 9;
FEdit.Font.Name := '宋体';
FEdit.OnEnter := ControlEnter;
FEdit.OnExit := ControlExit;
FEdit.OnClick := ControlClick;
FEdit.OnDblClick := ControlDblClick;
FEdit.OnKeyPress := EditKeyPress;
FEdit.OnChange := ControlChange;
FHelp := TBitBtn.Create (Self);
FHelp.parent := Self;
FHelp.Enabled := True;}
//FHelp.OnClick := BtnHelpClick;
{FHelp.TabStop := False;
FLabel.FocusControl := FEdit;
Height := 24;
FLabel.Height := Height;
FEdit.Height := Height;
FHelp.Height := Height;
FLabel.Width := 50;
FEdit.Width := 96;
FHelp.Width := 24;
Width := FLabel.Width + FEdit.Width + FHelp.Width + 2;
FEdit.Left := FLabel.Width;
FHelp.Left := FLabel.Width + FEdit.Width + 2;
FHelp.left := fhelp.left;
TabStop := True;
ParentFont := False;
}
if not (csDesigning in ComponentState) then
begin
tmpBitmap := TBitmap.Create;
try
tmpBitmap.LoadFromResourceName(HInstance,'Lookuphelp');
except
end;
FHelp.Glyph := tmpBitmap;
tmpBitmap.Free;
end
else
try
FHelp.Glyph.LoadFromFile('help.bmp');
except
showmessage('不能装载help.bmp');
end;
end;
destructor TPDBVendorEdit.Destroy ;
begin
{FEdit.OnChange := nil;
FEdit.OnEnter := nil;
FEdit.OnExit := nil;
FEdit.Free;
FHelp.Free;
}
FFieldLink.OnDataChange := nil;
//FDataLink.Free ;
FFieldLink.Free;
inherited Destroy;
end;
{
procedure TPDBVendorEdit.ControlChange(Sender: TObject);
begin
if FEdit.Text <> '' then inherited ControlChange(Sender);
if Assigned(FOnChange) then
FOnChange(Self);
end;
procedure TPDBVendorEdit.BtnHelpClick(Sender: TObject);
begin
FEdit.SetFocus;
ControlDblClick(self);
end;
procedure TPDBVendorEdit.ControlEnter(Sender: TObject);
begin
inherited ControlEnter(Sender);
if Assigned(FOnEnter) then
FOnEnter(Self);
end;
procedure TPDBVendorEdit.ControlClick(Sender: TObject);
begin
inherited ControlEnter(Sender);
if Assigned(FOnClick) then
FOnClick(Self);
end;
procedure TPDBVendorEdit.ControlDblClick(Sender: TObject);
var
SltDlg: TfrmSelectDlg;
begin
if Assigned(FOnDblClick) then
FOnDblClick(Self);
if (not RdOnly) and (not FQuery.IsEmpty) then
begin
SltDlg := TfrmSelectDlg.Create(Self);
with SltDlg do
begin
SelectDataSource.DataSet := FQuery;
grdSelect.Columns.Clear;
if FListField <> '' then
begin
grdSelect.Columns.Add;//添加第一列
grdSelect.Columns.Items[0].FieldName := FKeyField;
if FKeyFieldCaption = '' then
grdSelect.Columns.Items[0].Title.Caption := grdSelect.Columns.Items[0].FieldName
else
grdSelect.Columns.Items[0].Title.Caption := FKeyFieldCaption;
grdSelect.Columns.Items[0].Title.Font.Size := 10;
grdSelect.Columns.Items[0].Width := (Width - 40) div 2;
grdSelect.Columns.Add; //添加第二列
grdSelect.Columns.Items[1].FieldName := FListField;
if FListFieldCaption = '' then
grdSelect.Columns.Items[1].Title.Caption := grdSelect.Columns.Items[1].FieldName
else
grdSelect.Columns.Items[1].Title.Caption := FListFieldCaption;
grdSelect.Columns.Items[1].Title.Font.Size := 10;
grdSelect.Columns.Items[1].Width := (Width - 40) div 2;
if FKeyFieldCaption = '' then
SltDlg.FindKey.Items.Add(grdSelect.Columns.Items[0].FieldName)
else
SltDlg.FindKey.Items.Add(FKeyFieldCaption);
if FListFieldCaption = '' then
SltDlg.FindKey.Items.Add(grdSelect.Columns.Items[1].FieldName)
else
SltDlg.FindKey.Items.Add(FListFieldCaption);
end
else
begin
grdSelect.Columns.Add;
grdSelect.Columns.Items[0].FieldName := FKeyField;
if FKeyFieldCaption = '' then
grdSelect.Columns.Items[0].Title.Caption := grdSelect.Columns.Items[0].FieldName
else
grdSelect.Columns.Items[0].Title.Caption := FKeyFieldCaption;
grdSelect.columns.Items[0].Width := grdSelect.Width-10;
grdSelect.Columns.Items[0].Title.Font.Size := 40;
if FKeyFieldCaption = '' then
SltDlg.FindKey.Items.Add(grdSelect.Columns.Items[0].FieldName)
else
SltDlg.FindKey.Items.Add(FKeyFieldCaption);
end;
end;
SltDlg.FindKey.ItemIndex := 0;
if SltDlg.ShowModal=mrOK then
begin
DataSource.Edit;
FEdit.Text := FQuery.FieldByName(KeyField).AsString;
ControlChange(Self);
end;
SltDlg.Free;
OpenQuery;
end;
end;
procedure TPDBVendorEdit.EditKeyPress(Sender: TObject; var Key: Char);
begin
inherited ;
if Key = #13 then
ControlChange(Self);
end;
procedure TPDBVendorEdit.ControlExit(Sender: TObject);
begin
ControlChange(Self);
inherited ControlExit(Sender);
if Assigned(FOnExit) then
FOnExit(Self);
end; }
function TPDBVendorEdit.GetDataSource: TDataSource;
begin
Result := FFieldLink.DataSource ;
end;
procedure TPDBVendorEdit.SetDataSource(Value: TDataSource);
begin
{FDataLink.DataSource := Value;
FDataLink.DataSource.OnDataChange := DataChange;}
FFieldLink.DataSource := Value;
if Value <> nil then
Value.FreeNotification(Self);
if FEdit.DataSource <> Value then
begin
FEdit.DataSource := Value;
end;
end;
function TPDBVendorEdit.GetDataField: String;
begin
Result := FFieldLink.FieldName ;
end;
procedure TPDBVendorEdit.SetDataField(Value: String);
begin
FFieldLink.FieldName := Value;
if FEdit.datafield <> Value then
FEdit.DataField := Value;
end;
{
procedure TPDBVendorEdit.DataChange(Sender: TObject; Field: TField);
begin
inherited;
ControlChange(Self);
end; }
{
procedure TPDBVendorEdit.HideHelpButton;
begin
FHelp.Visible := False;
end;
procedure TPDBVendorEdit.ShowHelpButton;
begin
FHelp.Visible := True;
end;
}
{
procedure TPDBVendorEdit.SetParentFont(Value: Boolean);
begin
inherited;
FEdit.ParentFont := Value;
Flabel.ParentFont := Value;
FParentFont := Value;
end; }
function TPDBVendorEdit.GetReadOnly: Boolean;
begin
Result := FEdit.ReadOnly ;
end;
procedure TPDBVendorEdit.SetReadOnly(Value: Boolean);
begin
FEdit.ReadOnly := Value;
end;
{
procedure TPDBVendorEdit.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
begin
if AHeight < 20 then
AHeight := 20;
if AHeight >50 then
AHeight := 50;
inherited;
FEdit.Height := AHeight;
FLabel.Height := AHeight;
FHelp.Height := AHeight;
FEdit.Width := FEdit.Width + FHelp.Width -FHelp.Height;
FHelp.Width := FHelp.Height;
FLabel.Width := AWidth-FEdit.Width -FHelp.Width - 2;
FEdit.Left := FLabel.Width;
FHelp.Left := FLabel.Width + FEdit.Width + 2;
end;
}
{
procedure TPDBVendorEdit.Notification(AComponent: TComponent; Operation: TOperation);
begin
if (Operation = opRemove) and (Acomponent = FSubFieldControl) then
FSubFieldControl := nil;
end; }
{
procedure TPDBVendorEdit.CMFocusChanged(var Message: TCMFocusChanged);
begin
if Message.Sender.name = self.Name then
FEdit.SetFocus ;
end;
}
procedure Register;
begin
RegisterComponents('PosControl', [TPDBVendorEdit]);
end;
procedure TPDBVendorEdit.CreateEditCtrl;
begin
FEdit := TDBEdit.Create(Self);
FEdit.OnChange := ControlChange;
FEditCtrl:=FEdit;
end;
end.
|
unit PKindEdit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
stdctrls, dbtables, extctrls, RxCtrls, dbctrls, db, SelectDlg, PLabelPanel,
MaxMin,LookupControls;
type
TPKindEdit = class(TCustomControl)
private
{ Private declarations }
FCancut: boolean;
FCheck: Boolean;
FDatabaseName: string;
FDisplayLevel: integer;
FEdit: TEdit;
FKindGrade: integer;
FLabel: TRxLabel;
FLabelStyle: TLabelStyle;
FLookField: string;
FLookFieldCaption: string;
FLookSubField: string;
FLookSubFieldCaption: string;
//FParentFont: Boolean;
FQuery: TQuery;
FRealLevel: integer;
FSubFieldControl: TPLabelPanel;
FTableName: string;
protected
{ Protected declarations }
function FindCurrent(var LabelText: string):Boolean;
function GetCaption:TCaption;
function GetEditFont:TFont;
function GetEditWidth:integer;
function GetLabelFont: TFont;
function GetRdOnly:Boolean;
function GetText:string;
procedure ControlExit(Sender: TObject);
procedure ControlDblClick(Sender: TObject);
procedure EditKeyPress(Sender: TObject; var Key: Char);
procedure Paint;override;
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
procedure SetCaption(Value: TCaption);
procedure SetDisplayLevel(Value:integer);
procedure SetEditFont(Value: TFont);
procedure SetEditWidth(Value: integer);
procedure SetKindGrade(Value:integer);
procedure SetLabelFont(Value: TFont);
procedure SetLabelStyle(Value: TLabelStyle);
//procedure SetParentFont(Value: Boolean);
procedure SetRdOnly(Value: Boolean);
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy;override;
property Text:string read GetText;
published
{ Published declarations }
property Caption:TCaption read GetCaption write SetCaption;
property Cancut:boolean read FCancut write FCancut;
property Check: Boolean read FCheck write FCheck;
property DatabaseName: string read FDatabaseName write FDatabaseName;
property DisplayLevel:integer read FDisplayLevel write SetDisplayLevel stored False;
property EditFont:TFont read GetEditFont write SetEditFont;
property EditWidth:integer read GetEditWidth write SetEditWidth;
property KindGrade:integer read FKindGrade write SetKindGrade default 1;
property LabelFont: TFont read GetLabelFont write SetLabelFont;
property LabelStyle: TLabelStyle read FLabelStyle write SetLabelStyle default Normal;
property LookFieldCaption:string read FLookFieldCaption write FLookFieldCaption;
property LookSubFieldCaption:string read FLookSubFieldCaption write FLookSubFieldCaption;
//property ParentFont : Boolean read FParentFont write SetParentFont;
property RdOnly: Boolean read GetRdOnly write SetRdOnly;
property SubFieldControl: TPLabelPanel read FSubFieldControl write FSubFieldControl;
end;
procedure Register;
implementation
function TPKindEdit.GetLabelFont: TFont;
begin
Result := FLabel.Font;
end;
procedure TPKindEdit.SetLabelFont(Value: TFont);
begin
FLabel.Font := Value;
end;
function TPKindEdit.GetCaption:TCaption;
begin
Result := FLabel.Caption;
end;
procedure TPKindEdit.SetCaption(Value: TCaption);
begin
FLabel.Caption := Value;
end;
procedure TPKindEdit.SetLabelStyle (Value: TLabelStyle);
begin
FLabelStyle := Value;
case Value of
Conditional: begin
FLabel.Font.Color := clBlack;
FLabel.Font.Style := [fsUnderline];
end;
Normal: begin
FLabel.Font.Color := clBlack;
FLabel.Font.Style := [];
end;
NotnilAndConditional: begin
FLabel.Font.Color := clTeal;
FLabel.Font.Style := [fsUnderline];
end;
Notnil: begin
FLabel.Font.Color := clTeal;
FLabel.Font.Style := [];
end;
end;
end;
function TPKindEdit.GetEditWidth:integer;
begin
Result := FEdit.Width;
end;
procedure TPKindEdit.SetEditWidth(Value: integer);
begin
FEdit.Width := Value;
FEdit.Left := Width-Value;
FLabel.Width := FEdit.Left;
end;
function TPKindEdit.GetEditFont:TFont;
begin
Result := FEdit.Font;
end;
procedure TPKindEdit.SetEditFont(Value: TFont);
begin
FEdit.Font.Assign(Value);
FLabel.Height := FEdit.Height;
Height := FEdit.Height;
end;
function TPKindEdit.GetRdOnly:Boolean;
begin
Result := FEdit.ReadOnly;
end;
procedure TPKindEdit.SetRdOnly(Value: Boolean);
begin
FEdit.ReadOnly := Value;
if Value then
FEdit.Color := clSilver
else
FEdit.Color := clWhite;
end;
procedure TPKindEdit.Paint;
begin
FLabel.Height := Height;
FEdit.Height := Height;
FLabel.Width := Width-FEdit.Width;
FEdit.Left := FLabel.Width;
SetLabelStyle(LabelStyle);
inherited Paint;
end;
constructor TPKindEdit.Create (AOwner: TComponent);
begin
inherited Create(AOwner);
FLabel := TRxLabel.Create(Self);
FLabel.Parent := Self;
FLabel.ShadowSize := 0;
FLabel.Layout := tlCenter;
FLabel.AutoSize := False;
FLabel.Visible := True;
FLabel.Font.Size := 11;
FLabel.Font.Name := '宋体';
FLabel.ParentFont := False;
FEdit := TEdit.Create(Self);
FEdit.Parent := Self;
FEdit.Visible := True;
FEdit.OnExit := ControlExit;
FEdit.Font.Size := 9;
FEdit.Font.Name := '宋体';
FEdit.ParentFont := False;
FEdit.OnDblClick := ControlDblClick;
FEdit.OnKeyPress := EditKeyPress;
FLabel.FocusControl := FEdit;
Height := 24;
FLabel.Height := Height;
FEdit.Height := Height;
Width := 200;
FEdit.Width := 140;
FLabel.Width := Width-FEdit.Width;
FEdit.Left := FLabel.Width;
FQuery := TQuery.Create(Self);
LabelStyle := Normal;
FTableName := 'tbKind';
FLookField := 'KIND';
FLookSubField := 'C_NAME';
KindGrade := 1;
DisplayLevel := 34;
ParentFont := False;
end;
{
procedure TPKindEdit.SetParentFont(Value: Boolean);
begin
inherited;
FEdit.ParentFont := Value;
Flabel.ParentFont := Value;
FParentFont := Value;
end; }
destructor TPKindEdit.Destroy;
begin
FEdit.Free;
FQuery.Free;
FLabel.Free;
inherited Destroy;
end;
procedure TPKindEdit.SetDisplayLevel(Value: integer);
begin
FDisplayLevel := Value;
FEdit.MaxLength := Min(FKindGrade,FDisplayLevel)*2;
FRealLevel := Min(FKindGrade,FDisplayLevel);
end;
procedure TPKindEdit.EditKeyPress(Sender: TObject; var Key: Char);
var LabelText: string;
fgError : boolean;
TextLen : integer;
begin
if Key = #13 then
begin
fgError := False;
LabelText := '';
TextLen := Length(FEdit.Text);
if Check then
begin
if (not Cancut) and (TextLen<>FRealLevel*2) then
fgError := True
else
if (TextLen=0) or ((TextLen mod 2)<>0) then
fgError := True
else
if not FindCurrent(LabelText) then
fgError := True;
end
else
begin
if (not Cancut) and (TextLen<>FRealLevel*2) then
fgError := True
else
if (TextLen=0) or ((TextLen mod 2)<>0) then
fgError := True;
FindCurrent(LabelText);
end;
if fgError then
begin
Application.MessageBox('输入不合法!','错误',MB_OK);
end;
if FSubFieldControl <> nil then
(FSubFieldControl as TPLabelPanel).Caption := LabelText;
end;
end;
procedure TPKindEdit.ControlExit;
var LabelText: string;
fgError: boolean;
TextLen: integer;
begin
fgError := False;
LabelText := '';
TextLen := Length(FEdit.Text);
if Check then
begin
if (not Cancut) and (TextLen<>FRealLevel*2) then
fgError := True
else
if (TextLen=0) or ((TextLen mod 2)<>0) then
fgError := True
else if not FindCurrent(LabelText) then
fgError := True;
end
else
begin
if (not Cancut) and (TextLen<>FRealLevel*2) then
fgError := True
else
if (TextLen=0) or ((TextLen mod 2)<>0) then
fgError := True;
FindCurrent(LabelText);
end;
if fgError then
begin
Application.MessageBox('输入不合法!','错误',MB_OK);
FEdit.SetFocus;
end;
if FSubFieldControl <> nil then
(FSubFieldControl as TPLabelPanel).Caption := LabelText;
end;
function TPKindEdit.GetText:string;
begin
Result := FEdit.Text;
end;
function TPKindEdit.FindCurrent(var LabelText: string):Boolean;
var TextLen: integer;
begin
FQuery.DatabaseName := FDatabaseName;
FQuery.SQL.Clear;
FQuery.SQL.Add('Select * from '+FTableName);
FQuery.Open;
if not FQuery.Locate(FLookField, FEdit.Text,[]) then
begin
Result := False;
LabelText := '';
end
else
begin
Result := True;
LabelText := FQuery.FieldByName(FLookSubField).AsString;
end;
FQuery.Close;
end;
procedure TPKindEdit.SetKindGrade(Value:integer);
begin
FKindGrade := Value;
FEdit.MaxLength := Min(FKindGrade,FDisplayLevel)*2;
FRealLevel := Min(FKindGrade,FDisplayLevel);
end;
procedure TPKindEdit.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
begin
if AHeight < 20 then
AHeight := 20;
if AHeight >50 then
AHeight := 50;
inherited;
FEdit.Height := AHeight;
FLabel.Height := AHeight;
end;
procedure TPKindEdit.ControlDblClick(Sender: TObject);
var SltDlg: TfrmSelectDlg;
begin
FQuery.DatabaseName := FDatabaseName;
FQuery.SQL.Clear;
FQuery.SQL.Add('Select * from '+FTableName);
FQuery.Open;
if (not RdOnly) and (not FQuery.IsEmpty) then
begin
SltDlg := TfrmSelectDlg.Create(Self);
with SltDlg do
begin
SelectDataSource.DataSet := FQuery;
grdSelect.Columns.Clear;
grdSelect.Columns.Add;
grdSelect.Columns.Items[0].FieldName := FLookField;
grdSelect.Columns.Items[0].Title.Caption := FLookFieldCaption;
grdSelect.Columns.Items[0].Title.Font.Size := 10;
grdSelect.Columns.Add;
grdSelect.Columns.Items[1].FieldName := FLookSubField;
grdSelect.Columns.Items[1].Title.Caption := FLookSubFieldCaption;
grdSelect.Columns.Items[1].Title.Font.Size := 10;
end;
if SltDlg.ShowModal=mrOK then
begin
FEdit.Text := FQuery.FieldByName(FLookField).AsString;
if FSubFieldControl<>nil then
(FSubFieldControl as TPLabelPanel).Caption := FQuery.FieldByName(FLookSubField).AsString;
end;
SltDlg.Free;
end;
FQuery.Close;
end;
procedure Register;
begin
RegisterComponents('PosControl2', [TPKindEdit]);
end;
end.
|
{ This is the Pasal implementation
of Euclid's algorithm for computing
the greatest common divisor of two integers.
}
{ a recursive version }
PROGRAM euclid (input, output);
VAR a,b : integer;
FUNCTION gcd_recursive(u, v : integer) : integer;
BEGIN
IF u mod v <> 0 THEN
gcd_recursive := gcd_recursive(v, u mod v)
ELSE
gcd_recursive := v
END;
{ an iterative version }
function gcd_iterative(u, v : integer) : integer;
var t : integer;
begin
while v <> 0 do
begin
t := u;
u := v;
v := t mod v
end;
gcd_iterative := u
end;
{ main program starts here }
BEGIN
readln(a,b);
writeln(gcd_recursive(a,b));
writeln(gcd_iterative(a,b))
END.
|
// ************************************************************************ //
// The types declared in this file were generated from data read from the
// WSDL File described below:
// WSDL : https://www.caisistemas.es/prueba/ado.dll/wsdl/IFunciones
// Encoding : utf-8
// Version : 1.0
// (23/09/2015 11:58:05 - - $Rev: 45757 $)
// ************************************************************************ //
unit uServicioWeb;
interface
uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns, SOAPHTTPTrans, System.Net.HttpClient;
type
TDummyClass = Class
class procedure HTTPRIOHTTPWebNodeBeforePost(const HTTPReqResp: THTTPReqResp; Client:THTTPClient);
End;
// ************************************************************************ //
// The following types, referred to in the WSDL document are not being represented
// in this file. They are either aliases[@] of other types represented or were referred
// to but never[!] declared in the document. The types from the latter category
// typically map to predefined/known XML or Embarcadero types; however, they could also
// indicate incorrect WSDL documents that failed to declare or import a schema type.
// ************************************************************************ //
// !:int - "http://www.w3.org/2001/XMLSchema"[]
// !:string - "http://www.w3.org/2001/XMLSchema"[]
// ************************************************************************ //
// Namespace : urn:FuncionesIntf-IFunciones
// soapAction: urn:FuncionesIntf-IFunciones#%operationName%
// transport : http://schemas.xmlsoap.org/soap/http
// style : rpc
// use : encoded
// binding : IFuncionesbinding
// service : IFuncionesservice
// port : IFuncionesPort
// URL : https://www.caisistemas.es/prueba/ado.dll/soap/IFunciones
// ************************************************************************ //
IFunciones = interface(IInvokable)
['{4D59BE1D-9FE4-5C10-A615-B74769DDB6C7}']
function UnzipFile(const ruta: string; const destino: string): string; stdcall;
function EjecutaSQL(const Servidor: string; const RutaBD: string; const Sentencia: string): Integer; stdcall;
function EjecutaSQLConBlob(const Servidor: string; const RutaBD: string; const Sentencia: string; const CampoBlob: string; const Blob: string): Integer; stdcall;
end;
function GetIFunciones(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): IFunciones;
implementation
uses SysUtils;
function GetIFunciones(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): IFunciones;
const
defWSDL = 'https://www.caisistemas.es/prueba/ado.dll/wsdl/IFunciones';
defURL = 'https://www.caisistemas.es/prueba/ado.dll/soap/IFunciones';
defSvc = 'IFuncionesservice';
defPrt = 'IFuncionesPort';
var
RIO: THTTPRIO;
begin
Result := nil;
if (Addr = '') then
begin
if UseWSDL then
Addr := defWSDL
else
Addr := defURL;
end;
if HTTPRIO = nil then
RIO := THTTPRIO.Create(nil)
else
RIO := HTTPRIO;
try
Result := (RIO as IFunciones);
if UseWSDL then
begin
RIO.WSDLLocation := Addr;
RIO.Service := defSvc;
RIO.Port := defPrt;
end else
RIO.URL := Addr;
RIO.HTTPWebNode.OnBeforePost:=TDummyClass.HTTPRIOHTTPWebNodeBeforePost;
finally
if (Result = nil) and (HTTPRIO = nil) then
RIO.Free;
end;
end;
{ TDummyClass }
class procedure TDummyClass.HTTPRIOHTTPWebNodeBeforePost(
const HTTPReqResp: THTTPReqResp; Client:THTTPClient);
var
TimeOut: Integer;
begin
// Sets the receive timeout. i.e. how long to wait to 'receive' the response
TimeOut := (30*1000);
try
Client.ConnectionTimeout:=TimeOut;
Client.ResponseTimeout:=TimeOut;
except on E:Exception do
raise Exception.Create(Format('Unhandled Exception:[%s] while setting timeout to [%d] - ',[E.ClassName, TimeOut, e.Message]));
end;
end;
initialization
{ IFunciones }
InvRegistry.RegisterInterface(TypeInfo(IFunciones), 'urn:FuncionesIntf-IFunciones', 'utf-8');
InvRegistry.RegisterDefaultSOAPAction(TypeInfo(IFunciones), 'urn:FuncionesIntf-IFunciones#%operationName%');
end.
|
unit PTEndpointBloky;
{
Endpoint PTserveru /blok/.
}
interface
uses IdContext, IdCustomHTTPServer, JsonDataObjects, PTEndpoint, SysUtils,
Generics.Collections;
type
TPTEndpointBloky = class(TPTEndpoint)
private const
_ENDPOINT_MATCH_REGEX = '^/bloky/?$';
public
procedure OnGET(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo;
var respJson:TJsonObject); override;
function EndpointMatch(path:string):boolean; override;
end;
implementation
uses JclPCRE, TBloky, PTUtils, TOblRizeni, TOblsRizeni, TBlok;
////////////////////////////////////////////////////////////////////////////////
procedure TPTEndpointBloky.OnGET(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo;
var respJson:TJsonObject);
var params:TDictionary<string, string>;
stanice:TOR;
typ:Integer;
begin
stanice := nil;
typ := -1;
params := TDictionary<string, string>.Create();
try
PTUtils.HttpParametersToDict(ARequestInfo.Params, params);
if (params.ContainsKey('stanice')) then
begin
stanice := ORs.GetORById(params['stanice']);
if (stanice = nil) then
begin
PTUtils.PtErrorToJson(respJson.A['errors'].AddObject, '404', 'Oblast rizeni neexistuje', 'Oblast rizeni '+params['stanice']+' neexistuje');
Exit();
end;
end;
if (params.ContainsKey('typ')) then
typ := TBlk.BlkTypeFromStr(params['typ']);
Blky.GetPtData(respJson, params.ContainsKey('stav') and PTUtils.HttpParamToBool(params['stav']), stanice, typ);
finally
params.Free();
end;
end;
////////////////////////////////////////////////////////////////////////////////
function TPTEndpointBloky.EndpointMatch(path:string):boolean;
var re: TJclRegEx;
begin
re := TJclRegEx.Create();
re.Compile(_ENDPOINT_MATCH_REGEX, false);
Result := re.Match(path);
re.Free();
end;
////////////////////////////////////////////////////////////////////////////////
end.
|
unit FootageThread;
interface
uses
Classes,uDisPoseData, GzmClass,MySQLDataSet,SysUtils,StopWatch,uDataModule,math,DateUtils,
SyncObjs,windows, Winapi.ActiveX;
type
PAPStroke =^TStrokeData;
TStrokeData=packed record
StartTime:Tdatetime;
EndTime:TdateTime;
supportbh:integer;
Min_data:integer;
Max_data:Integer;
Now_time:TdateTime;
Now_data:integer;
MoveState:integer;
end;
PAPFootRec =^TFoot;
TFoot= packed record
Number:integer;
SecondTableid:integer;
EndTime:TdateTime;
end;
TFootAgeThread=class(TThread)
private
FDisPose:TDisposeData;
FuGzm:TGzm;
FAdoconn:TMySqlConnection;
FAdoDataSet1:TMyDataSet;
FAdoDataSet2:TMyDataSet;
FAdoCommand:TMyCommand;
DisposeType:String;
FSetting:TFormatSettings; //日期格式转换
dstroke:PAPStroke;
dFdd:PAPFootRec;
dFddList:TList;
//Flag:integer 写入标记 1 为 我外部录入进尺,2 自动计算进尺 3 修订后进尺
function InputFootage(uGBh:string;tDay: Tdatetime; DownDayFootage,
SumDownFootage, UpperDayFootage, SumUpperFootage: double;Flag:integer):Boolean;
function uAppointFootage(Fgzm,FSupbh:string):Boolean;//分配进尺 把进尺分到specondDP 中
{辅助分配进尺,主要处理Footage数据表的中标注数据}
function uselectTopFootAge(Fgzm,FSupbh:string;FootFlag:integer;
Var StTime,EdTime:TdateTime):Boolean;
{自动分配进尺,把realTimeFootage 中的数据插入到footage 数据表中}
function AutoCaluSupportStep(gzmid:integer):Boolean;
{考虑推移千斤顶数据不完整的解决方案}
function AutoCaluSupportStep_Pair(gzmid:integer):Boolean;
{收到录入进尺后,对原来通过推移千斤顶合并的进尺进行修订}
function AdjustFootage(gzmid:integer):Boolean;
function SelectDataTime(InputTime:TdateTime; var StartTime,EndTime:TdateTime):Boolean;
//=============================================
{ 以下 是 通过推移千斤顶 统计进尺数据 的函数}
function SelectStrokeData(Fgzm,FSupbh:string):Boolean; {主调函数}
{查找最大时间与最小时间函数}
function Select_StrokeMaxtime(Fgzm,FSupbh:string;Var Min_Time,Max_Time:TdateTime):Boolean;
{ 判断是 当前时刻 移动液压支架的函数}
function JudgeStrokeData(Fgzm,FSupbh:string; Min_Time,Max_Time:TdateTime):boolean;
{ 初始化记录类的函数}
procedure initStrokeRecord(dp:PAPStroke);
{ 保存数据与删除数据函数}
function SaveStrokeDataIntoRealFootage(Fgzm:string;DST:PAPStroke):Boolean;
protected
procedure Execute ;override;
public
destructor Destroy; override;
constructor Create(uObjusers:TDisposeData;BaseType:string);
end;
implementation
{ TThridhread }
{ TFootAgeThread }
function TFootAgeThread.AdjustFootage(gzmid: integer): Boolean;
var
StTime,EdTime,T1,T2:Tdatetime;
sql,Sql2:string;
FsumUpperFootage,FsumDownFootAge: double;
PSDF,PSUF,SDF,SUF:double;
MultDF,MultUF,AGVDF,AGVUF:double;
TempDF,TempUF:double;
FdayFootAge,FsumDayFootage:double;
OneFootAgeid,Twofootageid,tCout:integer;
begin
Result:=false;
//
EdTime:=1;
sql:=' select * from D_'+IntTostr(gzmid)+'_FootAge where processage=1 order by footday ' ;
FAdoDataSet1.Close ;
FAdoDataSet1.CommandText:=sql;
if FAdoDataSet1.Open then begin
FAdoDataSet1.First ;
while not FAdoDataSet1.Eof do begin
if FDisPose.AppointFootageStop then break;
OneFootAgeid:=FAdoDataSet1.FieldByName('id').AsInteger;
EdTime:=FAdoDataSet1.FieldByName('Footday').AsDateTime;
FsumUpperFootage:=FAdoDataSet1.FieldByName('SumUpperFootage').AsFloat;
FsumDownFootAge:=FAdoDataSet1.FieldByName('SumDownFootage').AsFloat;
// 特殊处理 推移千斤顶的数据
FAdoDataSet2.Close ;
Sql2:= ' select count(id) as Sid from D_'+ IntTostr(gzmid)+'_FootAge where processage=2 and ' +
' footday >= '''+ FormatDatetime('yyyy-mm-dd hh:nn:ss',EdTime) + ''' ' ;
FAdoDataSet2.CommandText:=sql2;
if FAdoDataSet2.Open then
if FAdoDataSet2.FieldByName('sid').AsInteger <1 then break;
//
FAdoDataSet2.Close ;
//找到已经校订过的 进尺最后记录
Sql2:= ' select SumDownfootage ,SumUpperfootage from D_'+
IntTostr(gzmid)+'_FootAge where processage=3 and ' +
' footday <= '''+ FormatDatetime('yyyy-mm-dd hh:nn:ss',EdTime) +
''' order by footday desc limit 1 ' ;
FAdoDataSet2.CommandText:=sql2;
if FAdoDataSet2.Open then begin
FAdoDataSet2.First;
if FAdoDataSet2.RecordCount>0 then begin
PSDF:= FAdoDataSet2.FieldByName('Sumdownfootage' ).AsFloat;
PSUF:= FAdoDataSet2.FieldByName('SumUpperfootage' ).AsFloat;
end else begin
PSDF:= 0;
PSUF:= 0;
end;
end;
FAdoDataSet2.Close ;
//
MultDF:=FsumDownFootAge-PSDF;
MultUF:=FsumUpperFootage-PSUF;
// 统计将要处理的 推移千斤顶 数据
Sql2:= ' select sum(downfootage) as SDF,sum(upperfootage) as SUF,Count(id) as Sid from D_'+
IntTostr(gzmid)+'_FootAge where processage=2 and ' +
' footday <= '''+ FormatDatetime('yyyy-mm-dd hh:nn:ss',EdTime) +
''' order by footday ' ;
FAdoDataSet2.CommandText:=sql2;
if FAdoDataSet2.Open then begin
SDF:=FAdoDataSet2.FieldByName('SDF').AsFloat ;
SUF:=FAdoDataSet2.FieldByName('SUF').AsFloat ;
end;
// tCout:=uAdoDataSet2.FieldByName('Sid').Asinteger ;
FAdoDataSet2.Close ;
//
if SDF>0 then AGVDF:=MultDF/SDF else AGVDF:=0;
if SUF>0 then AGVUF:=MultUF/SUF else AGVUF:=0;
// 更新数据记录
FAdoCommand.MysqlConnection.BeginTrans;
if (AGVDF >0 ) or (AGVUF>0 ) then begin //
Sql2:= ' select id,downfootage,upperfootage from D_'+
IntTostr(gzmid)+'_FootAge where processage=2 and ' +
' footday <= '''+ FormatDatetime('yyyy-mm-dd hh:nn:ss',EdTime) +
''' order by footday ' ;
FAdoDataSet2.CommandText:=sql2;
if FAdoDataSet2.Open then begin
TempDF:=PSDF;TempUF:=PSUF;
while not FAdoDataSet2.Eof do begin
Twofootageid:=FAdoDataSet2.FieldByName('id').AsInteger ;
TempDF:= TempDF+AGVDF*FAdoDataSet2.FieldByName('downfootage').AsFloat ;
TempUF:=TempUF+ AGVUF*FAdoDataSet2.FieldByName('Upperfootage').AsFloat ;
FAdoCommand.CommandText :=' update D_'+ IntTostr(gzmid)+'_FootAge set downfootage =' +
FormatFloat('0.00',AGVDF*FAdoDataSet2.FieldByName('downfootage').AsFloat) + ',SumDownFootage =' +
FormatFloat('0.00',TempDF) +', UpperFootAge= ' +
FormatFloat('0.00',AGVUF*FAdoDataSet2.FieldByName('Upperfootage').AsFloat) +', SumUpperFootage =' +
FormatFloat('0.00',TempUF) + ',processage=3 where id = ' +intToStr(Twofootageid);
FAdoCommand.Execute ;
FAdoDataSet2.Next;
end; //end while uAdoDataSet2.eof
end;
FAdoDataSet2.Close ;
end;
// 更新处理记录
FAdoCommand.CommandText :=' update D_'+ IntTostr(gzmid)+'_FootAge set processage=-1 '+
' where id = ' +intToStr(Onefootageid);
FAdoCommand.Execute ;
FAdoCommand.MysqlConnection.CommitTrans;
//吓一跳记录
FAdoDataSet1.Next ;
end; //end while uAdoDataSet1.Eof
end;
FAdoDataSet1.Close ;
Result:=true;
end;
function TFootAgeThread.AutoCaluSupportStep(gzmid: integer ): Boolean;
var
StartSupid,EndSupid: array [0..3] of integer;
AGVFootage: array [0..3] of double;
StartToEndSupNumber:integer;
inputTime,StartTime,EndTime:TdateTime;
i:integer;
StartsupNo,EndSupNo:integer;
begin
Result:=false;
//查找数据库中最小与最大支架编号
FADODataSet2.Close;
FADODataSet2.CommandText :=' select min(supportbh) as stbhNo,max(supportbh) as EndbhNo from D_'+
IntToStr(gzmid)+'_RealTimeFootage' +
' where process=0 ';
if FADODataSet2.Open then begin
StartsupNo:=FADODataSet2.FieldByName('stbhNo').AsInteger;
EndSupNo:=FADODataSet2.FieldByName('EndbhNo').AsInteger;
end;
FADODataSet2.Close;
if (EndSupNo =0) or (StartsupNo>=EndSupNo) then exit;
//分配不同区域支架编号 按照 区间分成三个区域, 根据支架排号方向的不同进行分别统计
if EndSupNo-StartsupNo+1 >60 then StartToEndSupNumber:=20
else StartToEndSupNumber:= round((EndSupNo-StartsupNo) /3);
if FuGzm.SupNumberDirection=0 then begin
StartSupid[0]:=StartsupNo;
EndSupid[0]:=StartsupNo+StartToEndSupNumber;
StartSupid[1]:=EndSupNo-StartToEndSupNumber;
EndSupid[1]:=EndSupNo;
end else begin
StartSupid[0]:=EndSupNo-StartToEndSupNumber;
EndSupid[0]:=EndSupNo;
StartSupid[1]:=StartsupNo;
EndSupid[1]:=StartsupNo+StartToEndSupNumber;
end;
//进入正式循环
while True do begin
if FDisPose.AppointFootageStop then break; // 第一种退出循环的方式
FADODataSet2.Close;
FADODataSet2.CommandText :=' select min(Generatetime) as st from D_'+IntToStr(gzmid)+'_RealTimeFootage' +
' where process=0 ';
if FADODataSet2.Open then
inputTime:= FADODataSet2.FieldByName('st').AsDateTime;
FADODataSet2.Close;
//提取开始时间与结束时间节点
SelectDataTime(inputTime,StartTime,EndTime);
//如果后面没有记录,证明该阶段没有结束,不予计算
FADODataSet2.Close;
FADODataSet2.CommandText :=' select count(id) as Td from D_'+IntToStr(gzmid)+'_RealTimeFootage' +
' where process=0 and Generatetime > '''+
FormatDateTime('yyyy-mm-dd hh:nn:ss',EndTime) +'''';
if FADODataSet2.Open then
if FADODataSet2.FieldByName('Td').AsInteger < 10 then begin
FADODataSet2.Close;break; // 第2种退出循环的方式
end;
FADODataSet2.Close;
//
for I := 0 to 1 do begin
FADODataSet2.Close;
FADODataSet2.CommandText :=' select Sum(RealFootage) SumT from D_'+IntToStr(gzmid)+'_RealTimeFootage' +
' where process=0 and Generatetime >= '''+ FormatDateTime('yyyy-mm-dd hh:nn:ss',StartTime) +'''' +
' and Generatetime < '''+ FormatDateTime('yyyy-mm-dd hh:nn:ss',EndTime) +'''' +
' and supportbh>= '+IntTostr(StartSupid[i] ) +' and supportbh <= ' +
IntTostr(EndSupid[i] ) ;
if FADODataSet2.Open then
if FADODataSet2.FieldByName('SumT').AsFloat >=1 then begin
AGVFootage[i]:= FADODataSet2.FieldByName('SumT').AsFloat/(EndSupid[i]-StartSupid[i]+1) /1000;
end else begin
AGVFootage[i]:=0;
end;
end;
if InputFootage( IntToSTr(gzmid),EndTime,AGVFootage[0],0,AGVFootage[1],0,2) then begin
FAdoCommand.CommandText:=' update D_'+IntToStr(gzmid)+'_RealTimeFootage set process=1 ' +
' where Generatetime >= '''+ FormatDateTime('yyyy-mm-dd hh:nn:ss',StartTime) +'''' +
' and Generatetime < '''+ FormatDateTime('yyyy-mm-dd hh:nn:ss',EndTime) +'''';
FAdoCommand.Execute ;
end;
FADODataSet2.Close;
end; //end while
Result:=true;
end;
function TFootAgeThread.AutoCaluSupportStep_Pair(gzmid: integer): Boolean;
var
StartToEndSupNumber,HalfNumber:integer;
inputTime,StartTime,EndTime:TdateTime;
i,LegalNumber:integer;
StartsupNo,EndSupNo:integer;
LeftSumData,LeftAVGData,RightSumData,RightAVGData:double;
SupporbhStep:double;
MaxTime:TdateTime;
begin
Result:=false;
//查找数据库中最小与最大支架编号
FADODataSet2.Close;
FADODataSet2.CommandText :=' select min(supportbh) as stbhNo,max(supportbh) as EndbhNo,min(Generatetime) as st,' +
' max(Generatetime) as Mt from D_'+IntToStr(gzmid)+'_RealTimeFootage' +
' where process=0 ';
if FADODataSet2.Open then begin
if FADODataSet2.RecordCount >0 then begin
inputTime:= FADODataSet2.FieldByName('st').AsDateTime;
StartsupNo:=FADODataSet2.FieldByName('stbhNo').AsInteger;
EndSupNo:=FADODataSet2.FieldByName('EndbhNo').AsInteger;
maxTime:=FADODataSet2.FieldByName('Mt').AsDateTime;
end else begin
exit;
end;
end else begin
exit;
end;
FADODataSet2.Close;
if (EndSupNo =0) or (EndSupNo-StartsupNo <(FuGzm.SupEndUsedNumber-FuGzm.SupStartNumber)/2) then exit;
//下顺槽的进尺累计
while (inputTime < maxTime-1) do begin
if FDisPose.AppointFootageStop then break; // 第一种退出循环的方式
HalfNumber:=Round( (EndSupNo-StartsupNo+1)/2);
LegalNumber:=0; LeftSumData:=0; LeftAVGData:=0;
//提取开始时间与结束时间节点
SelectDataTime(inputTime,StartTime,EndTime);
for I := StartsupNo to EndSupNo do begin
if FDisPose.AppointFootageStop then break; // 第一种退出循环的方式
//如果后面没有记录,证明该阶段没有结束,不予计算
FADODataSet2.Close;
FADODataSet2.CommandText :=' select count(id) as Td from D_'+IntToStr(gzmid)+'_RealTimeFootage' +
' where process=0 and supportbh= '+ IntTostr(i)+' and Generatetime > '''+
FormatDateTime('yyyy-mm-dd hh:nn:ss',EndTime) +'''';
if FADODataSet2.Open then
if FADODataSet2.FieldByName('Td').AsInteger < 1 then continue;
FADODataSet2.Close;
FADODataSet2.CommandText :=' select Sum(RealFootage) SumT from D_'+IntToStr(gzmid)+'_RealTimeFootage' +
' where process=0 and Generatetime >= '''+ FormatDateTime('yyyy-mm-dd hh:nn:ss',StartTime) +'''' +
' and Generatetime < '''+ FormatDateTime('yyyy-mm-dd hh:nn:ss',EndTime) +'''' +
' and supportbh = '+IntTostr(i );
if FADODataSet2.Open then
SupporbhStep:=FADODataSet2.FieldByName('SumT').AsFloat;
FADODataSet2.Close;
if (SupporbhStep> 6000) or (SupporbhStep <=0 ) then continue; //不可能一小时一刀
if LegalNumber=0 then LeftAVGData:= SupporbhStep;
if SupporbhStep < LeftAVGData*3 then begin //把超乎异常的数据删除
// 开始计数
LegalNumber:=LegalNumber+1;
LeftSumData:= LeftSumData+SupporbhStep;
LeftAVGData:=LeftSumData/LegalNumber;
end;
if LegalNumber>= halfNumber/4 then break;
end;
if LegalNumber>0 then LeftAVGData:=LeftSumData/LegalNumber/1000
else LeftAVGData:=0;
//上顺槽的进尺累计
LegalNumber:=0; RightSumData:=0; RightAVGData:=0;
for I := EndsupNo downto StartSupNo do begin
if FDisPose.AppointFootageStop then break; // 第一种退出循环的方式
//如果后面没有记录,证明该阶段没有结束,不予计算
FADODataSet2.Close;
FADODataSet2.CommandText :=' select count(id) as Td from D_'+IntToStr(gzmid)+'_RealTimeFootage' +
' where process=0 and supportbh= '+ IntTostr(i)+' and Generatetime > '''+
FormatDateTime('yyyy-mm-dd hh:nn:ss',EndTime) +'''';
if FADODataSet2.Open then
if FADODataSet2.FieldByName('Td').AsInteger < 1 then continue;
FADODataSet2.Close;
FADODataSet2.CommandText :=' select Sum(RealFootage) SumT from D_'+IntToStr(gzmid)+'_RealTimeFootage' +
' where process=0 and Generatetime >= '''+ FormatDateTime('yyyy-mm-dd hh:nn:ss',StartTime) +'''' +
' and Generatetime < '''+ FormatDateTime('yyyy-mm-dd hh:nn:ss',EndTime) +'''' +
' and supportbh = '+IntTostr(i );
if FADODataSet2.Open then
SupporbhStep:=FADODataSet2.FieldByName('SumT').AsFloat;
FADODataSet2.Close;
if (SupporbhStep> 6000) or (SupporbhStep <=0 ) then continue; //不可能一小时一刀
if LegalNumber=0 then RightAVGData:= SupporbhStep;
if SupporbhStep < RightAVGData*3 then begin //把超乎异常的数据删除
// 开始计数
LegalNumber:=LegalNumber+1;
RightSumData:= RightSumData+SupporbhStep;
RightAVGData:=RightSumData/LegalNumber;
end;
if LegalNumber>= halfNumber/4 then break;
end;
if LegalNumber>0 then RightAVGData:=RightSumData/LegalNumber/1000
else RightAVGData:=0;
if (LeftAVGData>0) or (RightAVGData>0) then begin
if InputFootage( IntToSTr(gzmid),EndTime,LeftAVGData,0,RightAVGData,0,2) then begin
FAdoCommand.CommandText:=' update D_'+IntToStr(gzmid)+'_RealTimeFootage set process=1 ' +
' where Generatetime >= '''+ FormatDateTime('yyyy-mm-dd hh:nn:ss',StartTime) +'''' +
' and Generatetime < '''+ FormatDateTime('yyyy-mm-dd hh:nn:ss',EndTime) +'''';
FAdoCommand.Execute ;
end;
end else begin
FAdoCommand.CommandText:=' update D_'+IntToStr(gzmid)+'_RealTimeFootage set process=1 ' +
' where Generatetime >= '''+ FormatDateTime('yyyy-mm-dd hh:nn:ss',StartTime) +'''' +
' and Generatetime < '''+ FormatDateTime('yyyy-mm-dd hh:nn:ss',EndTime) +'''';
FAdoCommand.Execute ;
end;
inputTime:=inputTime+1/24*4;
end; //end while
Result:=true;
end;
constructor TFootAgeThread.Create(uObjusers: TDisposeData; BaseType: string);
var
v1,v2,v3,v4:integer;
begin
Inherited Create(true) ; //继承 创建后 不启动 只有发出Resum采启动
CoInitialize(Nil);
FreeOnTerminate := True;
FDisPose:=uObjusers;
FAdoconn:=TMySqlConnection.Create(nil);
FAdoconn.Open(uObjusers.FinDataModule.EXDataIP,uObjusers.FinDataModule.Port,uObjusers.FinDataModule.ExUser,
uObjusers.FinDataModule.EXPassword,uObjusers.FinDataModule.DataBaseName);
FAdoDataSet1:=TMyDataSet.Create(nil);
FAdoDataSet2:=TMyDataSet.Create(nil);
FAdoCommand:=TMyCommand.Create(nil);
FAdoDataSet1.MySqlConnection:=FAdoconn;
FAdoDataSet2.MySqlConnection:=FAdoconn;
FAdoCommand.MySqlConnection:=FAdoconn;
FuGzm:=TGzm.Create(FAdoconn) ;
DisposeType:=BaseType;
//
//日期格式转换
FSetting.ShortDateFormat:='yyyy-mm-ss' ;
FSetting.DateSeparator :='-';
FSetting.ShortTimeFormat :='hh:nn:ss';
FSetting.TimeSeparator :=':';
FSetting.DecimalSeparator :='.';
//
dFddList:=Tlist.Create;
new(dStroke);
end;
destructor TFootAgeThread.Destroy;
var
i:integer;
begin
freeandNil(FuGzm);
freeandNil(FAdoDataSet1);
freeandNil(FAdoDataSet2);
freeandNil(FAdoCommand);
freeandNil(FAdoconn);
//
for I := 0 to dFddList.Count - 1 do
if Assigned(dFddList[i]) then Dispose(PFDD(dFddList[i]));
freeandNil(dFddList);
//
if Assigned(dStroke) then Dispose(dStroke);
CoUninitialize;
inherited Destroy;
end;
procedure TFootAgeThread.Execute;
var
i,t:integer;
GzmList:TStringlist;
FGzmid:integer;
begin
inherited;
{ToDO:管理日志文件}
try
FAdoCommand.CommandText:=' delete from processlog where generatetime <='''+
FormatDatetime('yyyy-mm-dd hh:nn:ss',now-2) +'''' ;
FAdoCommand.Execute ;
//
GzmList:=TStringlist.Create ;
FAdoDataSet1.Close ;
FAdoDataSet1.CommandText:='select cqid from cqcsb where qyzt=1';
if FAdoDataSet1.Open then
while not FAdoDataSet1.Eof do begin
GzmList.Add(Trim(IntToStr(FAdoDataSet1.FieldByName('cqid').AsInteger)));
FAdoDataSet1.Next ;
end; //end while not DataSetGzm.Eof
FAdoDataSet1.Close ;
//
for t := 0 to GzmList.Count - 1 do begin
if FDisPose.AppointFootageStop then break;
FGzmid:=StrToInt(GzmList[t]);
if DisposeType='CountFootage' then begin
{ 该部分计算放在了 第一次处理的前面.主要是对 移架信息的判断 201711}
if not FuGzm.InputGzmData(FGzmid) then break;
for i :=FuGzm.SupStartNumber to FuGzm.SupEndUsedNumber do begin
if FDisPose.AppointFootageStop then break;
SelectStrokeData(IntTostr(FGzmid),IntToStr(i)) ;
end;
// AutoCaluSupportStep(FGzmid); //自动计算 通过千斤顶 累计后的数据
AutoCaluSupportStep_Pair(FGzmid);
AdjustFootage(FGzmid); // 通过手动录入的进尺,调整相关 累计的千斤顶数据
end else if DisposeType='AppointFootage' then begin
if not FuGzm.InputGzmData(FGzmid) then break;
if not FuGzm.FillDataType_SupportType(FGzmid) then break;
{ 该部分处理 需要 所有支架推移千斤顶 统计完成后,所以 在 调用该线程时,
做了不能有第一个线程运行的判定.
}
AutoCaluSupportStep_Pair(FGzmid);
AdjustFootage(FGzmid); // 通过手动录入的进尺,调整相关 累计的千斤顶数据
for i :=FuGzm.SupStartNumber to FuGzm.SupEndUsedNumber do begin
if FDisPose.AppointFootageStop then break;
uAppointFootage(IntTostr(FGzmid),IntToStr(i)) ;
end;
end;
end;
finally
FreeAndNil(GzmList) ;
end;
end;
procedure TFootAgeThread.initStrokeRecord(dp: PAPStroke);
begin
dp.StartTime:=-1;
dp.EndTime :=-1;
dp.supportbh :=0;
dp.Min_data :=100000;
dp.Max_data :=0;
dp.Now_time:=-1;
dp.Now_data:=0;
dp.MoveState:=0;
end;
function TFootAgeThread.InputFootage(uGBh: string; tDay: Tdatetime;
DownDayFootage, SumDownFootage, UpperDayFootage, SumUpperFootage: double;
Flag: integer): Boolean;
Var
CSql:String;
DownS,UpperS:double;
begin
if DownDayFootage<0 then DownDayFootage:=0.0;
if SumDownFootage<0 then SumDownFootage:=0.0;
if UpperDayFootage<0 then UpperDayFootage:=0.0;
if SumUpperFootage<0 then SumUpperFootage:=0.0;
Result:=false;
DownS:=0;UpperS:=0;
CSql:='select * from D_'+uGBh+'_Footage where footday <= '''
+ FormatDateTime( 'yyyy-mm-dd hh:nn',tDay) +''' order by footday desc limit 1';
FAdoDataSet1.Close ;
FAdoDataSet1.CommandText :=Csql;
if FAdoDataSet1.Open then
if FAdoDataSet1.RecordCount >0 then begin
DownS:=FAdoDataSet1.FieldByName('SumDownFootage').AsFloat ;
UpperS:=FAdoDataSet1.FieldByName('SumUpperFootage').AsFloat ;
end;
FAdoDataSet1.Close ;
if DownS<0 then DownS:=0; if UpperS<0 then UpperS:=0;
// insert
if SumDownFootage<=0 then SumDownFootage:= DownS+DownDayFootage;
if SumUpperFootage<=0 then SumUpperFootage:= UpperS+UpperDayFootage;
if (not isNaN(DownDayFootage) ) and (not isNaN(SumDownFootage) ) and
(not isNaN(SumUpperFootage)) and (not isNaN(UpperDayFootage)) then begin
CSql:='insert into d_'+uGBh+'_footage ( footday,downfootage,sumdownfootage,upperfootage, '+
'sumupperfootage,processage) values (' +
''''+ FormatDateTime( 'yyyy-mm-dd hh:nn',tDay)+''','+
FormatFloat('0.00',DownDayFootage)+','+ FormatFloat('0.00',SumDownFootage)+','+
FormatFloat('0.00',UpperDayFootage)+','+ FormatFloat('0.00',SumUpperFootage) +
', '+IntToStr(Flag)+')';
FAdoCommand.CommandText:=Csql;
FAdoCommand.Execute ;
end;
Result:=true;
end;
function TFootAgeThread.JudgeStrokeData(Fgzm, FSupbh: string; Min_Time,
Max_Time: TdateTime): boolean;
var
sql:string;
begin
Result:=false;
initStrokeRecord(dStroke);
dStroke.supportbh:=StrToInt(FSupbh);
sql:=' select * from D_'+ Fgzm+ '_StrokeData where Process =0 and supportbh='+ FSupbh +
' and GenerateTime>='''+ FormatDateTime( 'yyyy-mm-dd hh:nn:ss',Min_Time) +''' '+
' and GenerateTime<='''+ FormatDateTime( 'yyyy-mm-dd hh:nn:ss',Max_Time) +''' ' +
' order by GenerateTime';
FADODataSet2.Close ;
FADODataSet2.CommandText:=sql;
if FADODataSet2.Open then begin
dStroke.StartTime :=FADODataSet2.FieldByName('GenerateTime').AsDateTime ;
while not FADODataSet2.Eof do begin
dStroke.Now_data:=Round(FADODataSet2.FieldByName('DataValue').AsFloat);
dStroke.Now_time:= FADODataSet2.FieldByName('GenerateTime').AsDateTime ;
if dStroke.Min_data >= dStroke.Now_data then begin
dStroke.Min_data:= dStroke.Now_data;
dStroke.EndTime:= dStroke.Now_time;
end;
if dStroke.Max_data < dStroke.Now_data then begin
dStroke.Max_data:= dStroke.Now_data;
dStroke.StartTime := dStroke.Now_time;
end;
if dStroke.Now_data >300 then dStroke.MoveState:=1;
if (dStroke.MoveState >0 ) and (dStroke.Min_data < dStroke.Now_data ) and
(dStroke.Max_data > dStroke.Now_data ) and ( dStroke.Min_data <200) and
(dStroke.Now_data >200) and (dStroke.EndTime > dStroke.StartTime) then begin
Result:=true;
break;
end;
FADODataSet2.Next ;
end;
end;
FADODataSet2.Close ;
end;
function TFootAgeThread.SaveStrokeDataIntoRealFootage(Fgzm: string;
DST: PAPStroke): Boolean;
var
sql:string;
begin
Result:=True ;
FAdoconn.BeginTrans ;
Sql:=' insert into D_'+Fgzm+'_RealTimeFootage (gzmid,supportbh,Generatetime,RealFootage,Process,EditFootage,SumFootage) ' +
' values (' + FGzm +','+IntToStr(DST.supportbh )+ ',''' + FormatDateTime( 'yyyy-mm-dd hh:nn:ss',DST.EndTime) +''',' +
IntToStr(DST.Max_data -DST.Min_data ) +',0,0,0' + ')';
try
FAdoCommand.CommandText :=sql;
FAdoCommand.Execute ;
sql:=' delete from D_'+Fgzm+'_StrokeData where Supportbh = ' +IntToStr(DST.supportbh ) +
' and Generatetime <= '''+ FormatDateTime( 'yyyy-mm-dd hh:nn',DST.Now_time)+'''';
// sql:=' update D_'+Fgzm+'_StrokeData set process=1 where Supportbh = ' +IntToStr(DST.supportbh ) +
// ' and Generatetime < '''+ FormatDateTime( 'yyyy-mm-dd hh:nn:ss',DST.Now_time)+'''';
FAdoCommand.CommandText :=sql;
FAdoCommand.Execute ;
except
FAdoconn.RollbackTrans ;
Result:=False;
exit;
end;
FAdoconn.CommitTrans;
end;
function TFootAgeThread.SelectDataTime(InputTime: TdateTime; var StartTime,
EndTime: TdateTime): Boolean;
var
AYear, AMonth, ADay, AHour, AMinute, ASecond, AMilliSecond: Word;
i :integer;
begin
DecodeDateTime( InputTime, AYear, AMonth, ADay, AHour, AMinute, ASecond, AMilliSecond) ;
for I := 0 to 5 do begin
if (AHour >=i*4) and (AHour<(i+1)*4) then begin
StartTime:=StrToDateTime(FormatDateTime('yyyy-mm-dd',InputTime)+' '+IntTostr(i*4)+':00:00',FSetting);
if i=5 then begin
EndTime:=StrToDateTime(FormatDateTime('yyyy-mm-dd',InputTime+1)+' 00:00:00',FSetting);
end else begin
EndTime:=StrToDateTime(FormatDateTime('yyyy-mm-dd',InputTime)+' '+IntTostr((i+1)*4)+':00:00',FSetting);
end;
end;
end;
end;
//
function TFootAgeThread.SelectStrokeData(Fgzm, FSupbh: string): Boolean;
var
sql:string;
Min_Time,Max_time:TdateTime;
Flag:Boolean;
begin
Flag:=True;
while (Flag) and (Select_StrokeMaxtime(Fgzm, FSupbh,Min_Time,Max_time)) do begin
if FDisPose.AppointFootageStop then break;
Flag:=JudgeStrokeData(Fgzm, FSupbh,Min_Time,Max_time);
if Flag then begin
// 保存数据
Flag:=SaveStrokeDataIntoRealFootage(Fgzm,dStroke);
end;
end;
Result:=True ;
end;
function TFootAgeThread.Select_StrokeMaxtime(Fgzm, FSupbh: string; var Min_Time,
Max_Time: TdateTime): Boolean;
var
sql:string;
begin
Result:=false;
sql:=' select min(Generatetime) as Min_T, max(GenerateTime) as Max_t from D_'+
Fgzm+ '_StrokeData where Process =0 and supportbh='+ FSupbh ;
FADODataSet2.Close ;
FADODataSet2.CommandText:=sql;
if FADODataSet2.Open then
if FADODataSet2.RecordCount >0 then begin
Min_time:= FADODataSet2.FieldByName('Min_T').AsDateTime;
Max_Time:= FADODataSet2.FieldByName('Max_T').AsDateTime;
if Max_Time > Min_time then Result:=true ;
end;
FADODataSet2.Close ;
end;
function TFootAgeThread.uAppointFootage(Fgzm, FSupbh: string): Boolean;
var
StTime,EdTime,T1,T2:Tdatetime;
supbh:integer;
sql,Sql2:string;
FupperFootage,FdownFootage,FsumUpperFootage,FsumDownFootAge: double;
FdayFootAge,FsumDayFootage:double;
FootFlag,i:integer;
temp_dFdd:PAPFootRec;
Field_i:integer;
begin
Result:=false;
EdTime:=1;
FootFlag:=3;
try
while uselectTopFootAge(Fgzm,Fsupbh,FootFlag,stTime,EdTime) do begin // 把当天的记录 进行分配
if FDisPose.AppointFootageStop then break;
supbh:= StrToInt(Fsupbh);
sql:=' select * from D_'+Fgzm+'_FootAge where Processage >0 and '+
' Footday >='''+ FormatDatetime('yyyy-mm-dd hh:nn:ss',stTime) +
''' and Footday < '''+ FormatDatetime('yyyy-mm-dd hh:nn:ss',EdTime) +'''' ;
FADODataSet2.Close ;
FADODataSet2.CommandText :=sql;
if FADODataSet2.Open then begin
T1:=stTime;T2:=stTime;
if FADODataSet2.RecordCount<1 then begin
exit;
FADODataSet2.Close ;
end;
while not FADODataSet2.Eof do begin
T1:=T2;
if FADODataSet2.RecNo =FADODataSet2.RecordCount then
T2:=Edtime else T2:=FADODataSet2.FieldByName('Footday').AsDateTime;
FupperFootage:=FADODataSet2.FieldByName('UpperFootage').AsFloat ;
FdownFootage:= FADODataSet2.FieldByName('DownFootage').AsFloat ;
FsumUpperFootage:= FADODataSet2.FieldByName('SumUpperFootage').AsFloat ;
FsumDownFootAge:= FADODataSet2.FieldByName('SumDownFootage').AsFloat ;
FootFlag:= FADODataSet2.FieldByName('ProcessAge').Asinteger ;
FSumUpperFootage:=FSumUpperFootage-FUpperFootAge;
FsumDownFootAge:=FsumDownFootAge-FDownFootage;
if FuGzm.SupNumberDirection=0 then begin
FdayFootAge:=FupperFootage+(FDownFootage-FupperFootage)/(FuGzm.SupEndUsedNumber-FuGzm.SupStartNumber) *supbh;
FsumDayFootage:= FsumUpperFootage+(FsumDownFootage-FsumUpperFootage)/(FuGzm.SupEndUsedNumber-FuGzm.SupStartNumber) *supbh;
end else begin
FdayFootAge:=FupperFootage+(FDownFootage-FupperFootage)/(FuGzm.SupEndUsedNumber-FuGzm.SupStartNumber)
*(FuGzm.SupEndUsedNumber-supbh);
FsumDayFootage:= FsumUpperFootage+(FsumDownFootage-FsumUpperFootage)/(FuGzm.SupEndUsedNumber-FuGzm.SupStartNumber)
*(FuGzm.SupEndUsedNumber-supbh);
end;
// //清理内存
for Field_i := 0 to FuGzm.IsUesedsupFieldcount-1 do begin
for I := 0 to dFddList.Count - 1 do
if Assigned(dFddList[i]) then Dispose(PFDD(dFddList[i]));
dFDDList.Clear ;
sql2:='select id,Endtime,typedata from D_'+Fgzm+'_SecondDP where Endtime > '' '+FormatDatetime('yyyy-mm-dd hh:nn:ss',T1) +
''' and Endtime <= '''+ FormatDatetime('yyyy-mm-dd hh:nn:ss',T2) +''' and supportbh='+FSupbh+
' and typedata= '''+FuGzm.IsUesedsupFieldName[Field_i] +''' order by Endtime' ;
FAdoDataSet1.Close ;
FAdoDataSet1.CommandText:=sql2;
if FAdoDataSet1.Open then
if FAdoDataSet1.RecordCount >=1 then begin
//分进尺
FdayFootAge:=FdayFootAge/FAdoDataSet1.RecordCount ;
while not FAdoDataSet1.Eof do begin
new(dFDD);
dFDD.Number:=FAdoDataSet1.RecNo;
dFDD.EndTime :=FAdoDataSet1.FieldByName('Endtime').AsDateTime;
dFDD.SecondTableid:=FAdoDataSet1.FieldByName('id').AsInteger;
dFDDList.Add(dFDD);
FAdoDataSet1.Next ;
end; //end while ExQuery
FAdoDataSet1.Close ;
//----
FADoCommand.MysqlConnection.BeginTrans ;
for I := 0 to dFDDList.Count -1 do begin
temp_dFdd:=PAPFootRec(dFDDList.Items[i]);
FADoCommand.CommandText:=' update D_'+Fgzm+'_SecondDP set FootAge=' +
FloatToStr(FsumDayFootage+FdayFootAge*temp_dFdd.Number ) +
',FootAgeFlag = '+ IntToStr(FootFlag) +
' where id= '+ intToStr(temp_dFdd.SecondTableid) ;
FADoCommand.Execute ;
end;
FADoCommand.MysqlConnection.CommitTrans ;
end else begin// end if if uAdoQuery.RecordCount >=1 then begin
FAdoDataSet1.Close ;
end;
end;
FADODataSet2.Next;
end; //end while ExDataSet2
end;
FADODataSet2.Close ;
end; //while uselectTopFootAge(Fgzm,Fsupbh,stTime)
except
exit;
end;
Result:=true;
end;
function TFootAgeThread.uselectTopFootAge(Fgzm, FSupbh: string; FootFlag:integer;
var StTime,EdTime: TdateTime): Boolean;
var
max_Time,DTime:TdateTime;
sql:string;
begin
Result:=false;
//查找footage 标注3 的最大记录时间
sql:=' select max(footday) as max_time from D_'+Fgzm+'_FootAge where Processage =3 ';
FADODataSet2.Close ;
FADODataSet2.CommandText :=sql;
if FADODataSet2.Open then
max_Time:=FADODataSet2.FieldByName('max_time').AsDateTime;
FADODataSet2.Close ;
// 查找 _SecondDP 表中 数据标记小于 3的记录 进行 标注 标注 2 为 使用没有通过 修订的进尺进行的计算
// 标注3 为 通过使用的进尺进行计算 标注 1 为使用原始 录入进尺进行计算 标注 0 为没有进尺
sql:=' select max(Endtime) as edtime from D_'+Fgzm+'_SecondDP where ( footageFlag =2 ' +
' or footageFlag =1 ) and supportbh='+ FSupbh ;
FADODataSet2.Close ;
FADODataSet2.CommandText :=sql;
if FADODataSet2.Open then
EdTime:=FADODataSet2.FieldByName('edtime').AsDateTime;
FADODataSet2.Close ;
if EdTime < max_Time then begin // 进行数据的更新 与操作 两部分 修订进尺的2 与没有标注进尺的
sql:=' select max(Endtime) as edtime,min(endtime) as stTime from D_'+Fgzm+'_SecondDP where footageFlag < 3' +
' and supportbh='+ FSupbh ;
end else begin // 只进行没有标注进尺的
sql:=' select max(Endtime) as edtime,min(endtime) as stTime from D_'+Fgzm+'_SecondDP where footageFlag =0 ' +
' and supportbh='+ FSupbh ;
end;
FADODataSet2.CommandText :=sql;
if FADODataSet2.Open then begin
stTime:=FADODataSet2.FieldByName('stTime').AsDateTime;
EdTime:=FADODataSet2.FieldByName('edtime').AsDateTime;
end;
if EdTime > stTime then Result:=true;
FADODataSet2.Close ;
end;
end. // end unit
|
unit Tips_u;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, IniFiles, ExtCtrls, Advanced;
type
TdlgTips = class(TForm)
BtnNext: TBitBtn;
BtnClose: TBitBtn;
pnlMain: TPanel;
shpBar: TShape;
lbCaption: TLabel;
lbTip: TLabel;
ImgLamp: TImage;
procedure FormCreate(Sender: TObject);
procedure BtnNextClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
dlgTips: TdlgTips;
Count:LongInt;
TipNum:LongInt;
implementation
{$R *.dfm}
procedure ReadTips;
var Ini:TIniFile;
begin
Ini:=TIniFile.Create(ExtractFileDir(Application.Exename)+'\Tips.ini');
Count:=Ini.ReadInteger('Tips','Count',0);
dlgTips.lbCaption.Caption:=Ini.ReadString('Tips','Caption','Did you know that...');
dlgTips.BtnNext.Enabled:=(Count>1);
if Count>0 then
dlgTips.lbTip.Caption:=Ini.ReadString('Tips','Tip0','Tips not found!');
Ini.Free;
end;
procedure ReadTip;
var Ini:TIniFile;
begin
Ini:=TIniFile.Create(ExtractFileDir(Application.Exename)+'\Tips.ini');
dlgTips.lbTip.Caption:=Ini.ReadString('Tips','Tip'+IntToStr(TipNum),'Tip not found!');
Ini.Free;
end;
procedure TdlgTips.BtnNextClick(Sender: TObject);
begin
Inc(TipNum);
if TipNum>=Count then
TipNum:=0;
ReadTip;
end;
procedure TdlgTips.FormCreate(Sender: TObject);
begin
TipNum:=0;
Count:=0;
ReadTips;
Caption:=ReadFromLanguage('Windows','wndTips',Caption);
btnClose.Caption:=ReadFromLanguage('Buttons','btnClose',btnClose.Caption);
btnNext.Caption:=ReadFromLanguage('Buttons','btnNext',btnNext.Caption);
lbCaption.Caption:=ReadFromLanguage('Labels','lbTips',lbCaption.Caption);
//lbTip.Caption:=ReadFromLanguage('Labels','lbTipPlace',lbTip.Caption);
end;
end.
|
unit IdTestSimpleServer;
interface
uses
IdTest,
IdExceptionCore,
IdObjs,
IdSys,
IdGlobal,
IdSimpleServer;
type
TIdTestSimpleServer = class(TIdTest)
published
procedure TestListen;
end;
implementation
procedure TIdTestSimpleServer.TestListen;
var
aServer:TIdSimpleServer;
aOk:Boolean;
begin
aServer:=TIdSimpleServer.Create;
try
aServer.BoundPort:=22290;
try
aOk:=False;
aServer.Listen(1000);
except
on e:EIdAcceptTimeout do aOk:=True;
end;
Assert(aOk);
//add tests for normal operation
finally
Sys.FreeAndNil(aServer);
end;
end;
initialization
TIdTest.RegisterTest(TIdTestSimpleServer);
end.
|
unit Logging;
interface
uses
SysUtils, Classes, Contnrs;
type
TLog = class(TObject)
private
FList: TStrings;
public
constructor Create;
destructor Destroy; override;
procedure FileAdd(const Filename: string);
procedure DirAdd(const Dir: string);
procedure PathListAdd(const Kind, Dir: string);
procedure PackageAdd(const Filename: string);
procedure SaveToFile(const Filename: string);
end;
implementation
uses
Configuration;
{ TLog }
constructor TLog.Create;
begin
inherited Create;
FList := TStringList.Create;
FList.Add('Version:' + Config.Target.Name + ' ' + Config.Target.VersionStr);
FList.Add('Title:' + Config.Title);
end;
destructor TLog.Destroy;
begin
FList.Free;
inherited Destroy;
end;
procedure TLog.FileAdd(const Filename: string);
begin
FList.Add('FileAdd:' + Filename);
end;
procedure TLog.DirAdd(const Dir: string);
begin
FList.Add('DirAdd:' + Dir);
end;
procedure TLog.PathListAdd(const Kind, Dir: string);
begin
FList.Add('PathListAdd:' + Kind + ',' + Dir);
end;
procedure TLog.PackageAdd(const Filename: string);
begin
FList.Add('PackageAdd:' + Filename);
end;
procedure TLog.SaveToFile(const Filename: string);
var
Lines, SortedLines: TStrings;
i: Integer;
begin
if FileExists(Filename) then
begin
Lines := TStringList.Create;
SortedLines := TStringList.Create;
try
Lines.LoadFromFile(Filename);
SortedLines.Assign(Lines);
TStringList(SortedLines).Sorted := True;
for i := FList.Count - 1 downto 0 do
if SortedLines.IndexOf(FList[i]) >= 0 then
FList.Delete(i);
Lines.AddStrings(FList);
Lines.SaveToFile(Filename);
finally
Lines.Free;
end;
end
else
FList.SaveToFile(Filename);
end;
end.
|
unit LZMA_u;
interface
Uses SevenZipVCL,Classes,SysUtils,Advanced,Viewer_u;
Type T7ZipFileInfo=Packed Record
FileName,Pach:String;
Size:LongWord;
PackedSize:LongWord;
CRC:LongWord;
CreationTime,
ModifyTime,
AccessTime:TDateTime;
Attr:Word;
ID:LongWord;
End;
//Type TShowFileInfo=procedure (Sender:TObject;FileInfo:T7ZipFileInfo)Of Object;
Type TDecompressorProgress=procedure (Sender:TObject;FProgress,AProgress:Byte;Var Abort:Boolean) of object;
Type TOverWritePrompt=procedure (Sender:TObject;Var AFile:TFileHead;Var Mode:TReWriteMode)of object;
Type TOnGetPassword=procedure (Sender:TObject;Var Pass:ShortString)of object;
Type TSevenZipViewer=Class(TComponent)
Private
Core:TSevenZip;
aFileName:String;
aDirs:TStringList;
SplitDir:String;
aOnShowFileInfo:TSowFileInfo;
aFileSpec:TStringList;
aDestDir:String;
aOnBegin:TNotifyEvent;
aOnEnd:TNotifyEvent;
aOnProgress:TDecompressorProgress;
aMaxProgress:LongWord;
aOnOverWrite:TOverWritePrompt;
aPassword:ShortString;
Abort:Boolean;
Mode:TReWriteMode;
aOnGetPass:TOnGetPassword;
Procedure FillDirsList(Sender: TObject; Filename: WideString;
Fileindex, FileSizeU, FileSizeP, Fileattr, Filecrc: Cardinal;
Filemethod: WideString; FileTime: Double);
Procedure ShowInfo(Sender: TObject; Filename: WideString;
Fileindex, FileSizeU, FileSizeP, Fileattr, Filecrc: Cardinal;
Filemethod: WideString; FileTime: Double);
Procedure CorePreProgress(Sender: TObject; MaxProgress: Int64);
procedure CoreProgress(Sender: TObject; Filename: WideString;
FilePosArc, FilePosFile: Int64);
procedure CoreOverWrite(Sender: TObject;
FileName: WideString; var DoOverwrite: Boolean);
Procedure OnGetFileInfo(Sender: TObject; Filename: WideString;
Fileindex, FileSizeU, FileSizeP, Fileattr, Filecrc: Cardinal;
Filemethod: WideString; FileTime: Double);
Public
Constructor Create;
Property FileName:String read aFileName write aFileName;
Property Directories:TStringList read aDirs write aDirs;
Property OnShowFileInfo:TSowFileInfo read aOnShowFileInfo write aOnShowFileInfo;
Property FileSpec:TStringList read aFileSpec write aFileSpec;
Property DestDir:String read aDestDir write aDestDir;
Property OnBegin:TNotifyEvent read aOnBegin write aOnBegin;
Property OnEnd:TNotifyEvent read aOnEnd write aOnEnd;
Property OnProgress:TDecompressorProgress read aOnProgress write aOnProgress;
Property OnOverWrite:TOverWritePrompt read aOnOverWrite write aOnOverWrite;
Property OverWriteMode:TReWriteMode read Mode write Mode;
Property OnGetPaasword:TOnGetPassword read aOnGetPass write aOnGetPass;
Procedure Get7zArchiveInfo(Var Version,AComment:String;Var FileCount:LongWord;Var UnpackedSize,ArcSize:Int64);
Procedure Extract;
Procedure GetDirs;
Procedure GetFilesFromDir(Directory:String);
Procedure Free;
Destructor Destroy;
End;
implementation
var
Count:LongWord;
UnPackSize{,ASize}:Int64;
Constructor TSevenZipViewer.Create;
Begin
Core:=TSevenZip.Create(Self);
aDirs:=TStringList.Create;
aFileSpec:=TStringList.Create;
Abort:=False;
aPassword:='';
End;
Procedure TSevenZipViewer.GetDirs;
Begin
Core.OnListfile:=FillDirsList;
Core.SZFileName:=aFileName;
Core.List;
End;
Procedure TSevenZipViewer.GetFilesFromDir(Directory:String);
Begin
Core.OnListfile:=ShowInfo;
Core.SZFileName:=aFileName;
SplitDir:=Directory;
Core.List;
End;
Procedure TSevenZipViewer.Extract;
Var Index:LongWord;
Begin
If Assigned(aOnBegin)Then
aOnBegin(Self);
Core.SZFileName:=aFileName;
Core.ExtrBaseDir:=aDestDir;
Core.OnPreProgress:=CorePreProgress;
//Core.Password:=aPassword;
Core.OnProgress:=CoreProgress;
Core.OnExtractOverwrite:=CoreOverWrite;
Core.ExtractOptions:=[ExtractOverwrite];
Core.Files.Clear;
If aFileSpec.Count>0 Then
For Index:=0 To aFileSpec.Count-1 Do
Core.Files.AddString(aFileSpec.Strings[Index]);
Core.Extract();
If Assigned(aOnEnd)Then
aOnEnd(Self);
End;
Procedure TSevenZipViewer.Get7zArchiveInfo(Var Version,AComment:String;Var FileCount:LongWord;Var UnpackedSize,ArcSize:Int64);
Var FileStream:TFileStream;
Begin
FileStream:=TFileStream.Create(aFileName,fmOpenRead);
ArcSize:=FileStream.Size;
FileStream.Free;
Core.SZFileName:=aFileName;
AComment:=Core.SevenZipComment;
//Version:=Core.SFXModule;
Version:='7z';
UnPackSize:=0;
//ASize:=0;
Count:=0;
Core.OnListfile:=OnGetFileInfo;
Core.List;
//Count:=0;
FileCount:=Count;
UnpackedSize:=UnPackSize;
End;
Procedure TSevenZipViewer.OnGetFileInfo(Sender: TObject; Filename: WideString;
Fileindex, FileSizeU, FileSizeP, Fileattr, Filecrc: Cardinal;
Filemethod: WideString; FileTime: Double);
Begin
If (Fileattr Xor faDirectory<>0) Then
Begin
Inc(UnPackSize,FileSizeU);
Inc(Count);
End;
End;
Procedure TSevenZipViewer.CorePreProgress(Sender: TObject; MaxProgress: Int64);
Begin
If Maxprogress > 0 Then aMaxProgress := Maxprogress;
End;
procedure TSevenZipViewer.CoreProgress(Sender: TObject; Filename: WideString;
FilePosArc, FilePosFile: Int64);
begin
If Assigned(aOnProgress)Then
aOnProgress(Self,fileposfile,GetPercentDone(0,fileposArc,aMaxProgress),Abort);
If Abort Then
Core.Cancel;
{progressbar2.Position := fileposArc;
progressbar1.Position := fileposfile;
application.ProcessMessages; }
end;
procedure TSevenZipViewer.CoreOverWrite(Sender: TObject;
FileName: WideString; var DoOverwrite: Boolean);
Var AFile:TFileHead;
begin
//DOOverwrite := true
AFile.LongFileName:=FileName;
Afile.Attr:=FileGetAttr(FileName);
AFile.CRC:=0;
AFile.Size:=0;
AFile.PackedSize:=0;
AFile.FileCreateDate:=0;
AFile.FileModifyDate:=0;
AFile.FileOpenDate:=0;
If Mode=omOverwriteAll Then
Begin
DoOverwrite:=True;
Exit;
End;
If Mode=omSkipAll Then
Begin
DoOverwrite:=False;
Exit;
End;
If Assigned(aOnOverWrite) Then
Begin
aOnOverWrite(Self,AFile,Mode);
If Mode=omRewrite Then
DoOverwrite:=True Else
DoOverwrite:=False;
End;
end;
Procedure TSevenZipViewer.FillDirsList(Sender: TObject; Filename: WideString;
Fileindex, FileSizeU, FileSizeP, Fileattr, Filecrc: Cardinal;
Filemethod: WideString; FileTime: Double);
Var Root:String;
Begin
{If FileAttr=faDirectory Then
Begin}
Root:=Format(RootCaption,[ExtractFileName(aFileName)]);
If Not TextInList(Root+'\'+ExtractFileDir(FileName),aDirs) Then
aDirs.Add(Root+'\'+ExtractFileDir(FileName));
{End;}
End;
Procedure TSevenZipViewer.ShowInfo(Sender: TObject; Filename: WideString;
Fileindex, FileSizeU, FileSizeP, Fileattr, Filecrc: Cardinal;
Filemethod: WideString; FileTime: Double);
Var FileInfo:TFileHead;
Begin
If (SplitDir<>'%ALL%')And(ExtractFileDir(FileName)<>SplitDir) Then Exit;
If (Fileattr And faDirectory)=faDirectory Then Exit;
FileInfo.LongFileName:=(FileName);
FileInfo.Size:=FileSizeU;
FileInfo.PackedSize:=FileSizeP;
FileInfo.CRC:=Filecrc;
FileInfo.FileCreateDate:=FileTime;
FileInfo.FileModifyDate:=FileTime;
FileInfo.FileOpenDate:=FileTime;
FileInfo.Attr:=Fileattr;
If Assigned(aOnShowFileInfo) Then
aOnShowFileInfo(Self,FileInfo,FileIndex);
End;
Procedure TSevenZipViewer.Free;
Begin
If Self<>Nil Then
Destroy;
End;
Destructor TSevenZipViewer.Destroy;
Begin
Core.Free;
aDirs.Free;
aFileSpec.Free;
End;
end.
|
unit ItemDeletado;
interface
uses SysUtils, Contnrs;
type
TItemDeletado = class
private
Fcodigo :Integer;
Fcodigo_pedido :Integer;
Fcodigo_usuario :Integer;
Fcodigo_produto :Integer;
FQuantidade :Real;
Fhora_exclusao :TDateTime;
Fjustificativa :String;
public
property codigo :Integer read Fcodigo write Fcodigo;
property codigo_pedido :Integer read Fcodigo_pedido write Fcodigo_pedido;
property codigo_usuario :Integer read Fcodigo_usuario write Fcodigo_usuario;
property codigo_produto :Integer read Fcodigo_produto write Fcodigo_produto;
property quantidade :Real read Fquantidade write Fquantidade;
property hora_exclusao :TDateTime read Fhora_exclusao write Fhora_exclusao;
property justificativa :String read Fjustificativa write Fjustificativa;
end;
implementation
{ TItemDeletado }
end.
|
unit OBufferedStreams;
{
LICENSE
Author: Ondrej Pokorny, http://www.kluug.net
License: MPL / GPL / LGPL
}
{$I OBufferedStreams.inc}
{$IFDEF O_DELPHI_XE4}
{$ZEROBASEDSTRINGS OFF}
{$ENDIF}
interface
uses
SysUtils, Classes;
type
{$IFNDEF O_DELPHI_2009}
TBytes = Array of Byte;
{$ENDIF}
TOBufferedWriteStream = class(TStream)
private
fStream: TStream;
fStreamPosition: Int64;
fStreamSize: Int64;
fTempBuffer: TBytes;
fBufferSize: Cardinal;
protected
function GetSize: Int64; {$IFNDEF O_DELPHI_6}override;{$ENDIF}
public
constructor Create(const aStream: TStream; const aBufferSize: Cardinal = 10*1024 {10 KB});
destructor Destroy; override;
function Write(const Buffer; Count: Longint): Longint; override;
{$IFDEF O_DELPHI_XE3}
function Write(const Buffer: TBytes; Offset, Count: Longint): Longint; override;
{$ENDIF}
function Read(var {%H-}Buffer; {%H-}Count: Longint): Longint; override;
{$IFDEF O_DELPHI_XE3}
function Read(Buffer: TBytes; Offset, Count: Longint): Longint; override;
{$ENDIF}
function Seek(Offset: Longint; Origin: Word): Longint; override;
public
procedure EnsureEverythingWritten;
public
property BufferSize: Cardinal read fBufferSize write fBufferSize;
end;
TOBufferedReadStream = class(TStream)
private
fStream: TStream;
fStreamPosition: Int64;
fStreamSize: Int64;
fTempBuffer: TBytes;
fTempBufferPosition: Cardinal;
fBlockFlushTempStream: Integer;
fBufferSize: Cardinal;
procedure ClearTempBuffer;
procedure CheckTempBuffer(const aReadBytes: Int64);
protected
function GetSize: Int64; {$IFNDEF O_DELPHI_6}override;{$ENDIF}
public
constructor Create(const aStream: TStream; const aBufferSize: Cardinal = 10*1024 {10 KB});
destructor Destroy; override;
function Write(const {%H-}Buffer; {%H-}Count: Longint): Longint; override;
{$IFDEF O_DELPHI_XE3}
function Write(const Buffer: TBytes; Offset, Count: Longint): Longint; override;
{$ENDIF}
function Read(var Buffer; Count: Longint): Longint; override;
{$IFDEF O_DELPHI_XE3}
function Read(Buffer: TBytes; Offset, Count: Longint): Longint; override;
{$ENDIF}
function Seek(Offset: Longint; Origin: Word): Longint; override;
public
procedure BlockFlushTempStream;
procedure UnblockFlushTempStream;
public
property BufferSize: Cardinal read fBufferSize write fBufferSize;
end;
implementation
{ TOBufferedWriteStream }
constructor TOBufferedWriteStream.Create(const aStream: TStream;
const aBufferSize: Cardinal);
begin
inherited Create;
if not Assigned(aStream) then
raise Exception.Create('TOBufferedWriteStream.Create: nil aStream parameter!');
fStream := aStream;
fStreamPosition := fStream.Position;
fStreamSize := fStream.Size;
fBufferSize := aBufferSize;
SetLength(fTempBuffer, 0);
end;
destructor TOBufferedWriteStream.Destroy;
begin
EnsureEverythingWritten;
SetLength(fTempBuffer, 0);
inherited;
end;
procedure TOBufferedWriteStream.EnsureEverythingWritten;
var
xInc: Integer;
begin
if Length(fTempBuffer) > 0 then begin
xInc := fStream.Write(fTempBuffer[0], Length(fTempBuffer));
fStreamSize := fStreamSize + xInc;
fStreamPosition := fStreamPosition + xInc;
SetLength(fTempBuffer, 0);
end;
end;
function TOBufferedWriteStream.GetSize: Int64;
begin
Result := fStreamSize + Length(fTempBuffer);
end;
function TOBufferedWriteStream.Read(var Buffer; Count: Longint): Longint;
begin
{$IFDEF FPC}
Result := 0;//JUST TO OMIT WARNING MESSAGES
{$ENDIF}
raise Exception.Create('TOBufferedWriteStream.Read: You can''t read from TOBufferedWriteStream!');
end;
{$IFDEF O_DELPHI_XE3}
function TOBufferedWriteStream.Read(Buffer: TBytes; Offset,
Count: Longint): Longint;
begin
Result := Self.Read(Buffer[Offset], Count);
end;
{$ENDIF}
function TOBufferedWriteStream.Seek(Offset: Integer; Origin: Word): Longint;
begin
if (Origin = soFromCurrent) and (Offset = 0) then begin
Result := fStreamPosition + Length(fTempBuffer);
{$IFDEF DELPHI6_DOWN}
//BECAUSE OF GetSize function!!!
end else if (Origin = soFromEnd) and (Offset = 0) then begin
Result := GetSize;
end else if (Origin = soFromBeginning) and (Offset = fStreamPosition + Length(fTempBuffer)) then begin//CURRENT POSITION
Result := fStreamPosition + Length(fTempBuffer);
{$ENDIF}
end else begin
raise Exception.Create('TOBufferedWriteStream.Seek: You can''t use seek in TOBufferedWriteStream');
end;
end;
function TOBufferedWriteStream.Write(const Buffer; Count: Longint): Longint;
var
xOldTempLength: Int64;
begin
if Int64(Length(fTempBuffer)) > Int64(fBufferSize) then
EnsureEverythingWritten;//WRITE TEMP BUFFER
if Int64(Count) > Int64(fBufferSize) then begin
//count to write bigger then buffer -> write directly
fStream.Write(Buffer, Count);
end else if Count > 0 then begin
//store to temp!
xOldTempLength := Length(fTempBuffer);
SetLength(fTempBuffer, xOldTempLength + Count);
Move(Buffer, fTempBuffer[xOldTempLength], Count);
end;
Result := Count;
end;
{$IFDEF O_DELPHI_XE3}
function TOBufferedWriteStream.Write(const Buffer: TBytes; Offset,
Count: Longint): Longint;
begin
Result := Self.Write(Buffer[Offset], Count);
end;
{$ENDIF}
{ TOBufferedReadStream }
procedure TOBufferedReadStream.BlockFlushTempStream;
begin
Inc(fBlockFlushTempStream);
end;
procedure TOBufferedReadStream.CheckTempBuffer(const aReadBytes: Int64);
var
xLastLength, xReadBytes: Cardinal;
xInc: Integer;
begin
if fTempBufferPosition+aReadBytes > Length(fTempBuffer) then begin
//LOAD NEXT BUFFER INTO TEMP STREAM, LEAVE UNREAD TAIL
if fBlockFlushTempStream = 0 then
ClearTempBuffer;
if fStreamPosition < fStreamSize then begin
xLastLength := Length(fTempBuffer);
xReadBytes := fBufferSize;
//CHECK THAT WE HAVE ALL NECESSARY BYTES IN TEMP BUFFER
if Length(fTempBuffer)-Int64(fTempBufferPosition)+xReadBytes < Int64(aReadBytes) then
xReadBytes := aReadBytes - (Length(fTempBuffer)-Int64(fTempBufferPosition));
//CHECK THAT WE READ ONLY TO STREAM SIZE
if xReadBytes > fStreamSize-fStreamPosition then
xReadBytes := fStreamSize-fStreamPosition;
SetLength(fTempBuffer, xLastLength+xReadBytes);
xInc := fStream.Read(fTempBuffer[xLastLength], xReadBytes);
fStreamPosition := fStreamPosition + xInc;
end;
end;
end;
procedure TOBufferedReadStream.ClearTempBuffer;
var
xBuffer: TBytes;
xBufferLength: Int64;
begin
if fTempBufferPosition > fBufferSize then begin
xBufferLength := Length(fTempBuffer) - Int64(fTempBufferPosition);
if xBufferLength < 0 then
xBufferLength := 0;
SetLength(xBuffer, xBufferLength);
if xBufferLength > 0 then
Move(fTempBuffer[fTempBufferPosition], xBuffer[0], xBufferLength);
SetLength(fTempBuffer, xBufferLength);
if xBufferLength > 0 then
Move(xBuffer[0], fTempBuffer[0], xBufferLength);
fTempBufferPosition := 0;
end;
end;
constructor TOBufferedReadStream.Create(const aStream: TStream;
const aBufferSize: Cardinal);
begin
inherited Create;
if not Assigned(aStream) then
raise Exception.Create('TOBufferedReadStream.Create: nil aStream parameter!');
fStream := aStream;
fStreamPosition := fStream.Position;
fStreamSize := fStream.Size;
fBufferSize := aBufferSize;
SetLength(fTempBuffer, 0);
end;
destructor TOBufferedReadStream.Destroy;
begin
SetLength(fTempBuffer, 0);
inherited;
end;
function TOBufferedReadStream.GetSize: Int64;
begin
Result := fStreamSize;
end;
{$IFDEF O_DELPHI_XE3}
function TOBufferedReadStream.Read(Buffer: TBytes; Offset,
Count: Longint): Longint;
begin
Result := Self.Read(Buffer[Offset], Count);
end;
{$ENDIF}
function TOBufferedReadStream.Read(var Buffer; Count: Longint): Longint;
begin
CheckTempBuffer(Count);
if Count > Length(fTempBuffer) - Int64(fTempBufferPosition) then
Count := Length(fTempBuffer) - Int64(fTempBufferPosition);
if Count > 0 then begin
Move(fTempBuffer[fTempBufferPosition], Buffer, Count);
fTempBufferPosition := fTempBufferPosition + Cardinal(Count);
end;
Result := Count;
end;
function TOBufferedReadStream.Seek(Offset: Integer; Origin: Word): Longint;
var
xAbsolutePosition: Int64;
begin
if (Origin = soFromCurrent) and (Offset = 0) then begin
//CURRENT POSITION
Result := fStreamPosition - Length(fTempBuffer) + fTempBufferPosition;
end else begin
//SEEK TO POSITION AND CLEAR TEMP STREAM
case Origin of
soFromCurrent: xAbsolutePosition := fStreamPosition - Length(fTempBuffer) + fTempBufferPosition + Offset;
soFromEnd: xAbsolutePosition := fStreamSize + Offset;
else
//soFromBeginning
xAbsolutePosition := Offset;
end;
if (xAbsolutePosition > (fStreamPosition - Length(fTempBuffer))) and
(xAbsolutePosition > (fStreamPosition - Length(fTempBuffer)))
then begin
//WITHIN TEMP RANGE
fTempBufferPosition := xAbsolutePosition - (fStreamPosition - Length(fTempBuffer));
Result := fStreamPosition - Length(fTempBuffer) + fTempBufferPosition;
end else begin
//OUTSIDE TEMP RANGE, CLEAR TEMP STREAM
Result := fStream.Seek(soFromBeginning, xAbsolutePosition);
fStreamPosition := Result;
SetLength(fTempBuffer, 0);
fTempBufferPosition := 0;
end;
end;
end;
procedure TOBufferedReadStream.UnblockFlushTempStream;
begin
if fBlockFlushTempStream > 0 then
Dec(fBlockFlushTempStream);
end;
{$IFDEF O_DELPHI_XE3}
function TOBufferedReadStream.Write(const Buffer: TBytes; Offset,
Count: Longint): Longint;
begin
Result := Self.Write(Buffer[Offset], Count);
end;
{$ENDIF}
function TOBufferedReadStream.Write(const Buffer; Count: Longint): Longint;
begin
{$IFDEF FPC}
Result := 0;//JUST TO OMIT WARNING MESSAGES
{$ENDIF}
raise Exception.Create('TOBufferedReadStream.Write: You can''t write to TOBufferedReadStream!');
end;
end.
|
unit mnTestCaseWizard;
interface
uses ToolsAPI;
type
mnTTestCaseWizard = class(TNotifierObject,
IOTAWizard, IOTARepositoryWizard, IOTAFormWizard, IOTACreator, IOTAModuleCreator)
private
FModuleName: string;
FUnitName: string;
FFormName: string;
protected
// IOTAWizard methods
function GetIDString: string;
function GetName: string;
function GetState: TWizardState;
procedure Execute;
// IOTARepositoryWizard methods
function GetAuthor: string;
function GetComment: string;
function GetPage: string;
function GetGlyph: Cardinal;
// IOTACreator methods
function GetCreatorType: string;
function GetExisting: Boolean;
function GetFileSystem: string;
function GetOwner: IOTAModule;
function GetUnnamed: Boolean;
// IOTAModuleCreator methods
function GetAncestorName: string;
function GetImplFileName: string;
function GetIntfFileName: string;
function GetFormName: string;
function GetMainForm: Boolean;
function GetShowForm: Boolean;
function GetShowSource: Boolean;
function NewFormFile(const FormIdent, AncestorIdent: string): IOTAFile;
function NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile;
function NewIntfSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile;
procedure FormCreated(const FormEditor: IOTAFormEditor);
end;
implementation
uses Windows, SysUtils, Dialogs, mnWindows, mnDialog, mnSystem, mnString;
{$R ..\..\..\files\Strings\IOTA\mnTestCaseWizard\mnTestCaseWizard.res}
{$R ..\..\..\files\Icons\IOTA\mnTestCaseWizard.res}
type
TBaseFile = class(TInterfacedObject)
private
FModuleName: string;
FFormName: string;
FAncestorName: string;
public
constructor Create(const ModuleName, FormName, AncestorName: string);
end;
TUnitFile = class(TBaseFile, IOTAFile)
protected
function GetSource: string;
function GetAge: TDateTime;
end;
{ TBaseFile }
constructor TBaseFile.Create(const ModuleName, FormName, AncestorName: string);
begin
inherited Create;
FModuleName := ModuleName;
FFormName := FormName;
FAncestorName := AncestorName;
end;
{ TUnitFile }
function TUnitFile.GetSource: string;
begin
Result := mnReplaceStr(mnLoadResAsStr(HInstance, 'UTestCase'), FAncestorName, FModuleName);
end;
function TUnitFile.GetAge: TDateTime;
begin
Result := -1;
end;
{ mnTTestCaseWizard }
function mnTTestCaseWizard.GetIDString: string;
begin
Result := 'Moon.mnTTestCaseWizard';
end;
function mnTTestCaseWizard.GetName: string;
begin
Result := 'Test Case Unit';
end;
function mnTTestCaseWizard.GetState: TWizardState;
begin
Result := [wsEnabled];
end;
procedure mnTTestCaseWizard.Execute;
begin
FModuleName := 'TargetUnit';
mnEditDialog('TargetUnit Name', 'Please input a target unit name:', FModuleName, FModuleName, scNotEmpty);
FUnitName := FModuleName + 'TestCase';
FFormName := '';
(BorlandIDEServices as IOTAModuleServices).CreateModule(Self);
end;
function mnTTestCaseWizard.GetAuthor: string;
begin
Result := 'Milan Qiu';
end;
function mnTTestCaseWizard.GetComment: string;
begin
Result := 'Creates a new test case unit.';
end;
function mnTTestCaseWizard.GetPage: string;
begin
Result := 'Moon';
end;
function mnTTestCaseWizard.GetGlyph: Cardinal;
begin
Result := LoadImage(hInstance, 'mnTTestCaseWizard', IMAGE_ICON, 0, 0, LR_DEFAULTSIZE);
end;
function mnTTestCaseWizard.GetCreatorType: string;
begin
Result := '';
end;
function mnTTestCaseWizard.GetExisting: Boolean;
begin
Result := False;
end;
function mnTTestCaseWizard.GetFileSystem: string;
begin
Result := '';
end;
function mnTTestCaseWizard.GetOwner: IOTAModule;
var
i: Integer;
ModServ: IOTAModuleServices;
Module: IOTAModule;
ProjGrp: IOTAProjectGroup;
begin
Result := nil;
ModServ := BorlandIDEServices as IOTAModuleServices;
for i := 0 to ModServ.ModuleCount - 1 do
begin
Module := ModSErv.Modules[i];
// find current project group
if CompareText(ExtractFileExt(Module.FileName), '.bdsgroup') = 0 then
if Module.QueryInterface(IOTAProjectGroup, ProjGrp) = S_OK then
begin
// return active project of group
Result := ProjGrp.GetActiveProject;
Exit;
end;
end;
end;
function mnTTestCaseWizard.GetUnnamed: Boolean;
begin
Result := True;
end;
function mnTTestCaseWizard.GetAncestorName: string;
begin
Result := 'TargetUnit';
end;
function mnTTestCaseWizard.GetImplFileName: string;
begin
// Note: full path name required!
Result := Format('%s%s.pas', [ExtractFilePath(GetOwner.FileName), FUnitName]);
end;
function mnTTestCaseWizard.GetIntfFileName: string;
begin
Result := '';
end;
function mnTTestCaseWizard.GetFormName: string;
begin
Result := '';
end;
function mnTTestCaseWizard.GetMainForm: Boolean;
begin
Result := False;
end;
function mnTTestCaseWizard.GetShowForm: Boolean;
begin
Result := False;
end;
function mnTTestCaseWizard.GetShowSource: Boolean;
begin
Result := True;
end;
function mnTTestCaseWizard.NewFormFile(const FormIdent, AncestorIdent: string): IOTAFile;
begin
Result := nil;
end;
function mnTTestCaseWizard.NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile;
begin
Result := TUnitFile.Create(FModuleName, '', AncestorIdent);
end;
function mnTTestCaseWizard.NewIntfSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile;
begin
Result := nil;
end;
procedure mnTTestCaseWizard.FormCreated(const FormEditor: IOTAFormEditor);
begin
// do nothing
end;
initialization
RegisterPackageWizard(mnTTestCaseWizard.Create);
end.
|
unit Unit2;
interface
uses
SmartCL.System, SmartCL.Components, W3C.Console;
type
TComp = class(TW3CustomControl)
private
{ Private declarations }
procedure createInnerComponent;
protected
{ Protected declarations }
procedure InitializeObject; override;
procedure FinalizeObject; override;
public
{ Public declarations }
published
{ Published declarations }
end;
implementation
var
document external "document": variant;
function btnsRipple : boolean;
begin
console.log('button was clicked');
end;
procedure TComp.createInnerComponent;
begin
(*+--------------------------------------------------------------------------+
|Since the document fragment is in memory and not part of the main DOM |
|tree, appending children to it does not cause page reflow (computation of |
|elements position and geometry). Consequently, using documentfragments |
|often results in better performance. |
+--------------------------------------------------------------------------+*)
var docFragment := document.createDocumentFragment(); // contains all gathered nodes
var button := document.createElement('BUTTON');
button.setAttribute("class", "TW3Button");
docFragment.appendChild(button);
var text := document.createTextNode("button1");
button.appendChild(text);
button.addEventListener('click', @btnsRipple, false);
Self.Handle.appendChild( docFragment );
end;
procedure TComp.InitializeObject;
begin
inherited;
(*+--------------------------------------------------------------------------+
| this is a good place to initialize the component |
+--------------------------------------------------------------------------+*)
//createInnerComponent;
(*+--------------------------------------------------------------------------+
| make the control display itself correctly when its ready in the DOM |
+--------------------------------------------------------------------------+*)
Handle.ReadyExecute(procedure()
begin
(* call createInnerComponent *)
createInnerComponent;
(*+--------------------------------------------------------------------------+
| some basic style attributes after render |
+--------------------------------------------------------------------------+*)
Self.Handle.style["width"] := null;
Self.Handle.style["height"] := null;
end);
end;
procedure TComp.FinalizeObject;
begin
inherited;
end;
procedure InsertCSS;
begin
(*+--------------------------------------------------------------------------+
| Inserts a new style rule into the current stylesheet, dynamically |
| change classes, so style information can be kept in genuine |
| stylesheets "and avoid adding extra elements to the DOM"). |
+--------------------------------------------------------------------------+*)
end;
initialization
end.
|
unit JBitmapTools;
interface
uses
Androidapi.JNI.GraphicsContentViewText,
FMX.Helpers.Android, FMX.Graphics,
FMX.Surfaces;
function JBitmapToBitmap(const AImage: JBitmap): TBitmap;
function BitmapToJBitmap(Bmp: TBitmap): JBitmap;
implementation
// JBitmapתBitmap
function JBitmapToBitmap(const AImage: JBitmap): TBitmap;
var
bitmapSurface: TBitmapSurface;
begin
bitmapSurface := TBitmapSurface.Create;
try
if JBitmapToSurface(AImage, bitmapSurface) then
begin
Result.Assign(bitmapSurface);
end;
finally
bitmapSurface.Free;
end;
end;
// BitmapתJBitmap
function BitmapToJBitmap(Bmp: TBitmap): JBitmap;
var
mBitmap: JBitmap;
Surface: TBitmapSurface;
begin
Surface := TBitmapSurface.Create;
Surface.Assign(Bmp);
mBitmap := TJBitmap.JavaClass.createBitmap(Bmp.Width, Bmp.Height,
TJBitmap_Config.JavaClass.ARGB_8888);
if SurfaceToJBitmap(Surface, mBitmap) then
Result := mBitmap;
end;
end.
|
unit EditTableFieldFrame;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, StdCtrls, DbUnit, MdUnit;
type
{ TFrameEditTableField }
TFrameEditTableField = class(TFrame)
btnOK: TButton;
cbFieldType: TComboBox;
cbLinkedTable: TComboBox;
cbFieldIndexed: TCheckBox;
edFieldName: TEdit;
edFieldNameFull: TEdit;
lbFieldName: TLabel;
lbFieldNameFull: TLabel;
lbFieldLink: TLabel;
lbFieldType: TLabel;
procedure btnOKClick(Sender: TObject);
private
{ private declarations }
FDbFieldInfo: TDbFieldInfo;
FOnItemRename: TNotifyEvent;
procedure SetDbFieldInfo(AValue: TDbFieldInfo);
public
{ public declarations }
MdStorage: TMdStorage;
property DbFieldInfo: TDbFieldInfo read FDbFieldInfo write SetDbFieldInfo;
property OnItemRename: TNotifyEvent read FOnItemRename write FOnItemRename;
procedure ReadItem();
procedure WriteItem();
end;
implementation
{$R *.lfm}
{ TFrameEditTableField }
procedure TFrameEditTableField.btnOKClick(Sender: TObject);
begin
WriteItem();
end;
procedure TFrameEditTableField.SetDbFieldInfo(AValue: TDbFieldInfo);
begin
FDbFieldInfo := AValue;
ReadItem();
end;
procedure TFrameEditTableField.ReadItem();
var
sFt: string;
i: Integer;
TmpTableInfo: TDbTableInfo;
begin
if not Assigned(DbFieldInfo) then
Exit;
Self.Visible := False;
edFieldName.Text := DbFieldInfo.FieldName;
edFieldNameFull.Text := DbFieldInfo.FieldDescription;
lbFieldLink.Enabled := False;
cbLinkedTable.Enabled := False;
cbLinkedTable.Text := '';
// fill tables list
if Assigned(MdStorage) then
begin
for i := 0 to MdStorage.DbTableInfoList.Count - 1 do
begin
TmpTableInfo := (MdStorage.DbTableInfoList.Objects[i] as TDbTableInfo);
cbLinkedTable.AddItem(TmpTableInfo.TableName, TmpTableInfo);
end;
end;
// fill field types
cbFieldType.Items.Clear();
cbFieldType.Items.Append('Integer [I]');
cbFieldType.Items.Append('String [S]');
cbFieldType.Items.Append('Numeric [N]');
cbFieldType.Items.Append('Date, time [T]');
cbFieldType.Items.Append('Binary data [B]');
cbFieldType.Items.Append('Link [L]');
// set field type
sFt := Copy(DbFieldInfo.FieldType, 1, 1);
if sFt = 'I' then
cbFieldType.ItemIndex := 0
else if sFt = 'S' then
cbFieldType.ItemIndex := 1
else if sFt = 'N' then
cbFieldType.ItemIndex := 2
else if sFt = 'T' then
cbFieldType.ItemIndex := 3
else if sFt = 'B' then
cbFieldType.ItemIndex := 4
else if sFt = 'L' then
begin
cbFieldType.ItemIndex := 5;
lbFieldLink.Enabled := True;
cbLinkedTable.Enabled := True;
cbLinkedTable.Text := Copy(DbFieldInfo.FieldType, 3, 9999);
end;
cbFieldIndexed.Checked := DbFieldInfo.IsIndexed;
Self.Visible := True;
end;
procedure TFrameEditTableField.WriteItem();
var
sFt: string;
begin
if not Assigned(DbFieldInfo) then
Exit;
if Trim(edFieldName.Text) = '' then
Exit;
// set field type
sFt := '';
if cbFieldType.ItemIndex = 0 then
sFt := 'I'
else if cbFieldType.ItemIndex = 1 then
sFt := 'S'
else if cbFieldType.ItemIndex = 2 then
sFt := 'N'
else if cbFieldType.ItemIndex = 3 then
sFt := 'T'
else if cbFieldType.ItemIndex = 4 then
sFt := 'B'
else if cbFieldType.ItemIndex = 5 then
begin
sFt := 'L';
if Trim(cbLinkedTable.Text) <> '' then
sFt := sFt + '~' + Trim(cbLinkedTable.Text);
end;
//DbTableInfo.ModifyField(FieldIndex, Trim(edFieldName.Text), sFt);
DbFieldInfo.FieldName := Trim(edFieldName.Text);
DbFieldInfo.FieldDescription := Trim(edFieldNameFull.Text);
DbFieldInfo.FieldType := sFt;
DbFieldInfo.IsIndexed := cbFieldIndexed.Checked;
if Assigned(OnItemRename) then
OnItemRename(Self);
end;
end.
|
unit MargCals;
interface
uses FrogObj, ReadIn, NLO, FrogTrace, OutputCals, classes;
type
TMargCals = class(TFrogObject)
private
mForceMarginals: boolean;
public
SpecCals: TReadIn;
AutoCals: TReadIn;
SHGSpecCals: TReadIn;
property ForceMarginals: boolean read mForceMarginals write mForceMarginals;
procedure RunMarginals(pFrogI: TFrogTrace; pNLO: TNLOInteraction; pOutputCals: TOutputCals; pLog: TStrings);
constructor Create;
destructor Destroy; override;
end;
implementation
uses Func1D, MargGraph, Forms, WindowMgr, TestPlot;
constructor TMargCals.Create;
begin
inherited Create;
SpecCals := TReadIn.Create;
AutoCals := TReadIn.Create;
SHGSpecCals := TReadIn.Create;
ForceMarginals := False;
end;
destructor TMargCals.Destroy;
begin
SHGSpecCals.Free;
AutoCals.Free;
SpecCals.Free;
end;
procedure TMargCals.RunMarginals(pFrogI: TFrogTrace; pNLO: TNLOInteraction; pOutputCals: TOutputCals; pLog: TStrings);
var
HaveSpec, HaveAuto, HaveSHGSpec: Boolean;
xSpectrum, xSHGSpectrum: TSpectrum;
xAutocorrelation: TAutocorrelation;
Marginal, FrogMarginal: TMarginal;
//DelT, Lam0: double;
//test: TfrmTestPlot;
begin
xSpectrum := nil;
xAutocorrelation := nil;
xSHGSpectrum := nil;
Marginal := nil;
frmMargGraph := nil;
FrogMarginal := nil;
HaveSpec := (SpecCals.ReadInFile <> SpecCals.NullFile);
HaveAuto := (AutoCals.ReadInFile <> AutoCals.NullFile);
HaveSHGSpec := (SHGSpecCals.ReadInFile <> SHGSpecCals.NullFile);
if pNLO.NeedSpectrum and (not HaveSpec) then Exit;
if pNLO.NeedAutocorrelation and (not HaveAuto) then Exit;
if pNLO.NeedSHGSpectrum and (not HaveSHGSpec) then Exit;
// If we make it to here, then we are ready to marg it!
try
if pNLO.NeedSpectrum then
begin
xSpectrum := SpecCals.LoadSpectrum;
pLog.Add('Spectrum used for Marginal Calculation:' + SpecCals.ReadInFile);
end;
if pNLO.NeedAutocorrelation then
begin
xAutocorrelation := AutoCals.LoadAutocorrelation;
pLog.Add('Autocorrelation used for Marginal Calculation:' + AutoCals.ReadInFile);
end;
if pNLO.NeedSHGSpectrum then
begin
xSHGSpectrum := SHGSpecCals.LoadSpectrum;
pLog.Add('SHG Spectrum used for Marginal Calculation:' + SHGSpecCals.ReadInFile);
end;
// In NLO.CalculateMarginal, TReadIn.GridSpectrum is called. This takes into
// account that the data read in was constant wavelenght, and puts it onto
// a constant frequency grid (just like the FROG trace).
Marginal := pNLO.CalculateMarginal(xSpectrum, xAutocorrelation, xSHGSpectrum);
FrogMarginal := pFrogI.ZeroOrderFreqMarginal;
//frmTestPlot.PlotIntensity(FrogMarginal);
//FrogMarginal.ScaleForNonlinearWavelength;
//frmTestPlot.PlotIntensity(FrogMarginal);
frmMargGraph := TfrmMargGraph.Create(Application);
WindowManager.InitializeThisWindow(frmMargGraph);
frmMargGraph.GraphMarginals(Marginal, FrogMarginal);
frmMargGraph.ForceAgreement := mForceMarginals;
frmMargGraph.ShowModal;
if frmMargGraph.ForceAgreement then mForceMarginals := True;
pOutputCals.SaveExperimentalMarginal(Marginal, 'ExpMarg.dat');
if ForceMarginals then
// Show the new marginals, too.
begin
pFrogI.ForceAgreementWithMarginal(Marginal);
FrogMarginal.Free;
FrogMarginal := pFrogI.ZeroOrderFreqMarginal;
frmMargGraph.GraphMarginals(Marginal, FrogMarginal);
frmMargGraph.Caption := 'Marginals, after forcing agreement.';
frmMargGraph.ShowModal;
end;
finally
FrogMarginal.Free;
WindowManager.SaveAsDefaults(frmMargGraph);
frmMargGraph.Free;
Marginal.Free;
xSHGSpectrum.Free;
xAutocorrelation.Free;
xSpectrum.Free;
end;
end;
end.
|
unit Registration;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, User, Authorization,
System.RegularExpressions,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Menus;
type
TRegistrationForm = class(TForm)
RegistrationButtonButton: TButton;
NameLabel: TLabel;
MailLabel: TLabel;
LoginLabel: TLabel;
Password1Label: TLabel;
Password2Label: TLabel;
NameEdit: TEdit;
BackButton: TButton;
MailEdit: TEdit;
LoginEdit: TEdit;
Password1Edit: TEdit;
Password2Edit: TEdit;
InfLabel: TLabel;
CheckBox: TCheckBox;
NameErrorLabel: TLabel;
MailErrorLabel: TLabel;
LoginErrorLabel: TLabel;
Password1ErrorLabel: TLabel;
Password2ErrorLabel: TLabel;
MainMenu: TMainMenu;
HelpButton: TMenuItem;
procedure BackButtonClick(Sender: TObject);
procedure RegistrationButtonButtonClick(Sender: TObject);
function CheckForDublicates: Boolean;
procedure CheckBoxClick(Sender: TObject);
procedure DisplayErrors;
function CheckInput: Boolean;
procedure NameEditChange(Sender: TObject);
procedure MailEditChange(Sender: TObject);
procedure LoginEditChange(Sender: TObject);
procedure Password1EditChange(Sender: TObject);
procedure Password2EditChange(Sender: TObject);
procedure NameEditKeyPress(Sender: TObject; var Key: Char);
procedure MailEditKeyPress(Sender: TObject; var Key: Char);
procedure LoginEditKeyPress(Sender: TObject; var Key: Char);
procedure Password1EditKeyPress(Sender: TObject; var Key: Char);
procedure Password2EditKeyPress(Sender: TObject; var Key: Char);
procedure HelpButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
RegistrationForm: TRegistrationForm;
implementation
{$R *.dfm}
procedure TRegistrationForm.BackButtonClick(Sender: TObject);
begin
Self.Close();
end;
Procedure SaveAccountToFile(User: TUser);
var
SaveFile: file of TUser;
begin
AssignFile(SaveFile, 'passwords.dat');
Reset(SaveFile);
Seek(SaveFile, FileSize(SaveFile));
Write(SaveFile, User);
CloseFile(SaveFile);
end;
procedure TRegistrationForm.CheckBoxClick(Sender: TObject);
begin
if CheckBox.Checked then
begin
Password1Edit.PasswordChar := #0;
Password2Edit.PasswordChar := #0
end
else
begin
Password1Edit.PasswordChar := '*';
Password2Edit.PasswordChar := '*';
end;
end;
function TRegistrationForm.CheckForDublicates: Boolean;
var
OpenFile: File of TUser;
User: TUser;
IsCorrect: Boolean;
begin
try
AssignFile(OpenFile, 'passwords.dat');
if FileExists('passwords.dat') then
Reset(OpenFile)
else
Rewrite(OpenFile);
IsCorrect := True;
while not Eof(OpenFile) do
begin
Read(OpenFile, User);
if (MailEdit.Text = User.Mail) then
begin
IsCorrect := False;
MessageBox(Application.Handle,
'Данный E-Mail уже используется.', 'Ошибка', MB_ICONERROR)
end
else if (LoginEdit.Text = User.Login) then
begin
MessageBox(Application.Handle, 'Данный логин уже используется.',
'Ошибка', MB_ICONERROR);
IsCorrect := False;
end;
end;
CloseFile(OpenFile);
CheckForDublicates := IsCorrect;
except
MessageBox(Handle, 'Ошибка регистрации', 'Уведомленио об ошибке',
MB_ICONERROR);
CheckForDublicates := false;
end;
end;
procedure TRegistrationForm.DisplayErrors;
begin
if (NameEdit.Text = '') then
begin
NameErrorLabel.Visible := True;
NameErrorLabel.Caption := 'Отсутствует имя';
end
else
NameErrorLabel.Caption := '';
if (MailEdit.Text = '') then
begin
MailErrorLabel.Visible := True;
MailErrorLabel.Caption := 'Отсутствует E-Mail';
end
else
begin
if TRegEx.IsMatch(MailEdit.Text, '[\w._]+@\w+\.[a-zA-Z]+') = False then
MailErrorLabel.Caption := 'E-Mail введен некорректно'
else
MailErrorLabel.Caption := '';
end;
if (LoginEdit.Text = '') then
begin
LoginErrorLabel.Visible := True;
LoginErrorLabel.Caption := 'Отсутствует логин';
end
else
LoginErrorLabel.Caption := '';
if (Password1Edit.Text = '') then
begin
Password1ErrorLabel.Visible := True;
Password1ErrorLabel.Caption := 'Отсутствует пароль'
end
else
begin
if (Length(Password1Edit.Text) < 8) then
Password1ErrorLabel.Caption :=
'Пароль должен содержать не менее 8 символов'
else
begin
Password1ErrorLabel.Caption := '';
if Password1Edit.Text <> Password2Edit.Text then
Password1ErrorLabel.Caption := 'Пароли не совпадают'
else
Password1ErrorLabel.Caption := '';
end;
end;
if (Password2Edit.Text = '') then
begin
Password2ErrorLabel.Visible := True;
Password2ErrorLabel.Caption := 'Отсутствует повторный пароль'
end
else
begin
if (Length(Password2Edit.Text) < 8) then
Password2ErrorLabel.Caption :=
'Пароль должен содержать не менее 8 символов'
else
Password2ErrorLabel.Caption := '';
end;
end;
procedure TRegistrationForm.HelpButtonClick(Sender: TObject);
begin
MessageBox(Handle, 'Перед Вами представлена окно регистации.' + #10#13 +
'Для того, чтобы зарегистрироваться, необходимо корректно ' + #10#13 +
'заполнить представленные поля.' + #10#13 +
'Рекомендуется запомнить введённые поля "Логин" и "Пароль", так как они будут нужны в дальнейшем использовании.',
'Помощь', MB_ICONINFORMATION);
end;
function TRegistrationForm.CheckInput: Boolean;
begin
if (NameEdit.Text = '') or (MailEdit.Text = '') or (LoginEdit.Text = '') or
(Password1Edit.Text = '') or (Password2Edit.Text = '') or
(Length(Password1Edit.Text) < 8) or (Length(Password2Edit.Text) < 8) or
(Password1Edit.Text <> Password2Edit.Text) then
CheckInput := False
else
CheckInput := True;
end;
procedure TRegistrationForm.LoginEditChange(Sender: TObject);
begin
LoginErrorLabel.Caption := '';
end;
procedure TRegistrationForm.LoginEditKeyPress(Sender: TObject; var Key: Char);
begin
if (Length(LoginEdit.Text) = 15) and not(Key in [#8]) then
Key := #0;
end;
procedure TRegistrationForm.MailEditChange(Sender: TObject);
begin
MailErrorLabel.Caption := '';
end;
procedure TRegistrationForm.MailEditKeyPress(Sender: TObject; var Key: Char);
begin
if (Length(MailEdit.Text) = 25) and not(Key in [#8]) then
Key := #0;
end;
procedure TRegistrationForm.NameEditChange(Sender: TObject);
begin
NameErrorLabel.Caption := '';
end;
procedure TRegistrationForm.NameEditKeyPress(Sender: TObject; var Key: Char);
begin
if (Length(NameEdit.Text) = 20) and not(Key in [#8]) then
Key := #0;
end;
procedure TRegistrationForm.Password1EditChange(Sender: TObject);
begin
Password1ErrorLabel.Caption := '';
end;
procedure TRegistrationForm.Password1EditKeyPress(Sender: TObject;
var Key: Char);
begin
if (Length(Password1Edit.Text) = 15) and not(Key in [#8]) then
Key := #0;
end;
procedure TRegistrationForm.Password2EditChange(Sender: TObject);
begin
Password2ErrorLabel.Caption := '';
end;
procedure TRegistrationForm.Password2EditKeyPress(Sender: TObject;
var Key: Char);
begin
if (Length(Password2Edit.Text) = 15) and not(Key in [#8]) then
Key := #0;
end;
procedure TRegistrationForm.RegistrationButtonButtonClick(Sender: TObject);
Var
User: TUser;
IsCorrect: Boolean;
AuthorizationForm: TAuthorizationForm;
begin
if CheckInput = True then
begin
User := TUser.Create(NameEdit.Text, MailEdit.Text, LoginEdit.Text,
Password1Edit.Text);
IsCorrect := CheckForDublicates;
if IsCorrect then
begin
SaveAccountToFile(User);
Self.Hide;
Self.Close;
MessageBox(Application.Handle, 'Регистрация прошла успешно!',
'Регистрация', MB_OK);
AuthorizationForm := TAuthorizationForm.Create(Self);
AuthorizationForm.Show;
end;
end
else
DisplayErrors;
end;
end.
|
PROGRAM Decryption(INPUT, OUTPUT);
{Переводит символы из INPUT в код согласно Chiper
и печатает новые символы в OUTPUT}
CONST
Len = 20;
FirstSymOfCpr = ' ';
LastSymOfCpr = 'Z';
CorrSetSymbols = [' ', 'A' .. 'Z'];
TYPE
Str = ARRAY [1 .. Len] OF CHAR;
Chiper = ARRAY [FirstSymOfCpr .. LastSymOfCpr] OF CHAR;
VAR
Chpr: TEXT;
Msg: Str;
Decoder: Chiper;
LenOfStr: INTEGER;
PROCEDURE Initialize(VAR Decoder: Chiper; VAR Chpr: TEXT);
{Присвоить Code шифр замены}
VAR
Symbol: CHAR;
BEGIN {Initialize}
WHILE NOT EOF(Chpr)
DO
BEGIN
IF NOT EOLN(Chpr)
THEN
BEGIN
READ(Chpr, Symbol);
IF ((NOT EOLN(Chpr)) AND (Symbol IN CorrSetSymbols))
THEN
READ(Chpr, Decoder[Symbol])
END;
READLN(Chpr)
END
END; {Initialize}
PROCEDURE Decode(VAR S: Str; VAR Decoder: Chiper);
{Выводит символы из Decoder, соответствующие символам из S}
VAR
Index: 1 .. Len;
BEGIN {Decode}
IF LenOfStr = 0
THEN
WRITE('empty line above')
ELSE
BEGIN
FOR Index := 1 TO LenOfStr
DO
IF Decoder[S[Index]] IN CorrSetSymbols
THEN
WRITE(Decoder[S[Index]])
ELSE
WRITE(S[Index])
END;
WRITELN
END; {Decode}
BEGIN {Decryption}
{Инициализировать Decoder}
ASSIGN(Chpr, 'CHPR.TXT');
RESET(Chpr);
Initialize(Decoder, Chpr);
CLOSE(Chpr);
WHILE NOT EOF(INPUT)
DO
BEGIN
{читать строку в Msg и распечатать ее}
LenOfStr := 0;
WHILE NOT EOLN AND (LenOfStr < Len)
DO
BEGIN
LenOfStr := LenOfStr + 1;
READ(Msg[LenOfStr]);
{эхо ввода}
WRITE(Msg[LenOfStr])
END;
READLN;
WRITELN;
{распечатать кодированное сообщение}
Decode(Msg, Decoder)
END
END. {Decryption}
|
unit TelegaPi.Ext.Sessions;
interface
uses
System.Rtti,
System.Generics.Collections;
type
ItgSession = interface
['{D581A266-7AC0-496A-8784-9DCEDC6849C9}']
function GetItem(const AKey: string): TValue;
procedure SetItem(const AKey: string; const Value: TValue);
function GetCreatedAt: TDateTime;
procedure SetCreatedAt(const Value: TDateTime);
//
procedure Clear;
property Items[const AKey: string]: TValue read GetItem write SetItem; Default;
property CreatedAt: TDateTime read GetCreatedAt write SetCreatedAt;
end;
TtgSession = class(TInterfacedObject, ItgSession)
private
FItems: TDictionary<string, TValue>;
FCreatedAt: TDateTime;
function GetItem(const AKey: string): TValue;
procedure SetItem(const AKey: string; const Value: TValue);
function GetCreatedAt: TDateTime;
procedure SetCreatedAt(const Value: TDateTime);
public
constructor Create;
destructor Destroy; override;
procedure Clear;
property CreatedAt: TDateTime read GetCreatedAt write SetCreatedAt;
property Items[const AKey: string]: TValue read GetItem write SetItem; Default;
end;
ItgSessionManager = interface
['{52E3CD5C-C096-4C3D-BC70-D284233C0250}']
function GetItem(const AID: Int64): ItgSession;
procedure SetItem(const AID: Int64; const Value: ItgSession);
procedure Clear;
property Items[const AID: Int64]: ItgSession read GetItem write SetItem; Default;
end;
TtgSessionManager = class(TInterfacedObject, ItgSessionManager)
private
class var
FInstance: TtgSessionManager;
private
FItems: TDictionary<Int64, ItgSession>;
function GetItem(const AID: Int64): ItgSession;
procedure SetItem(const AID: Int64; const Value: ItgSession);
public
class function NewInstance: TObject; override;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Items[const AID: Int64]: ItgSession read GetItem write SetItem; Default;
end;
implementation
uses
System.SysUtils;
procedure TtgSession.Clear;
begin
FItems.Clear;
end;
constructor TtgSession.Create;
begin
FItems := TDictionary<string, TValue>.Create;
end;
destructor TtgSession.Destroy;
begin
FItems.Free;
inherited;
end;
function TtgSession.GetCreatedAt: TDateTime;
begin
Result := FCreatedAt;
end;
function TtgSession.GetItem(const AKey: string): TValue;
begin
if not FItems.ContainsKey(AKey) then
FItems.Add(AKey, TValue.Empty);
Result := FItems.Items[AKey]
end;
procedure TtgSession.SetCreatedAt(const Value: TDateTime);
begin
FCreatedAt := Value;
end;
procedure TtgSession.SetItem(const AKey: string; const Value: TValue);
begin
FItems.AddOrSetValue(AKey, Value);
end;
{ TtgSesionManager }
procedure TtgSessionManager.Clear;
begin
FItems.Clear;
end;
constructor TtgSessionManager.Create;
begin
FItems := TDictionary<Int64, ItgSession>.Create;
end;
destructor TtgSessionManager.Destroy;
begin
FItems.Free;
inherited;
end;
function TtgSessionManager.GetItem(const AID: Int64): ItgSession;
begin
if not FItems.ContainsKey(AID) then
FItems.Add(AID, TtgSession.Create);
Result := FItems.Items[AID]
end;
class function TtgSessionManager.NewInstance: TObject;
begin
if FInstance = nil then
FInstance := TtgSessionManager(inherited NewInstance);
Result := FInstance;
end;
procedure TtgSessionManager.SetItem(const AID: Int64; const Value: ItgSession);
begin
FItems.AddOrSetValue(AID, Value);
FItems.Items[AID].CreatedAt := Now;
end;
end.
|
unit BusinessTest;
interface
uses dbTest, dbObjectTest, ObjectTest;
type
TBusinessTest = class (TdbObjectTestNew)
published
procedure ProcedureLoad; override;
procedure Test; override;
end;
TBusiness = class(TObjectTest)
function InsertDefault: integer; override;
public
function InsertUpdateBusiness(const Id: integer; Code: Integer;
Name: string): integer;
constructor Create; override;
end;
implementation
uses DB, UtilConst, TestFramework, SysUtils, JuridicalTest;
{ TdbUnitTest }
procedure TBusinessTest.ProcedureLoad;
begin
ScriptDirectory := ProcedurePath + 'OBJECTS\Business\';
inherited;
end;
procedure TBusinessTest.Test;
var Id: integer;
RecordCount: Integer;
ObjectTest: TBusiness;
begin
ObjectTest := TBusiness.Create;
// Получим список
RecordCount := ObjectTest.GetDataSet.RecordCount;
// Вставка Бизнеса
Id := ObjectTest.InsertDefault;
try
// Получение данных о Бизнесе
with ObjectTest.GetRecord(Id) do
Check((FieldByName('Name').AsString = 'Бизнес'), 'Не сходятся данные Id = ' + FieldByName('id').AsString);
Check(ObjectTest.GetDataSet.RecordCount = (RecordCount + 1), 'Количество записей не изменилось');
finally
ObjectTest.Delete(Id);
end;
end;
{ TBusinessTest }
constructor TBusiness.Create;
begin
inherited;
spInsertUpdate := 'gpInsertUpdate_Object_Business';
spSelect := 'gpSelect_Object_Business';
spGet := 'gpGet_Object_Business';
end;
function TBusiness.InsertDefault: integer;
begin
result := InsertUpdateBusiness(0, -1, 'Бизнес');
inherited;
end;
function TBusiness.InsertUpdateBusiness;
begin
FParams.Clear;
FParams.AddParam('ioId', ftInteger, ptInputOutput, Id);
FParams.AddParam('inCode', ftInteger, ptInput, Code);
FParams.AddParam('inName', ftString, ptInput, Name);
result := InsertUpdate(FParams);
end;
initialization
//TestFramework.RegisterTest('Объекты', TBusinessTest.Suite);
end.
|
unit expandablelistview;
{$mode delphi}
interface
uses
Classes, SysUtils, And_jni, AndroidWidget, systryparent;
type
TOnGroupItemExpand = procedure(Sender: TObject; groupItemPosition: integer; groupItemHeader: string) of object;
TOnGroupItemCollapse = procedure(Sender: TObject; groupItemPosition: integer; groupItemHeader: string) of object;
TOnOnChildItemClick = procedure(Sender: TObject; groupItemPosition: integer; groupItemHeader: string; childItemPosition: integer; childItemCaption: string) of object;
{Draft Component code by "Lazarus Android Module Wizard" [10/16/2017 23:51:06]}
{https://github.com/jmpessoa/lazandroidmodulewizard}
{jVisualControl template}
jExpandableListView = class(jVisualControl)
private
FItems: TStrings;
FGroupItemDelimiter: string;
FChildItemDelimiter: string;
FOnGroupItemExpand: TOnGroupItemExpand;
FOnGroupItemCollapse: TOnGroupItemCollapse;
FOnOnChildItemClick: TOnOnChildItemClick;
FFontChildColor: TARGBColorBridge;
FFontChildSize: DWord;
FTextAlign: TTextAlign;
FTextChildAlign: TTextAlign;
FTextChildTypeFace: TTextTypeFace;
FBackgroundChildColor: TARGBColorBridge;
FImageItemIdentifier: string;
FImageChildItemIdentifier: string;
FHighLightSelectedChildItemColor: TARGBColorBridge;
procedure SetVisible(Value: Boolean);
procedure SetColor(Value: TARGBColorBridge); //background
Procedure SetFontColor(_color: TARGBColorBridge);
procedure SetFontChildColor(_color: TARGBColorBridge);
procedure SetTextAlign(_align: TTextAlign);
procedure SetTextChildAlign(_align: TTextAlign);
procedure SetFontFace(_fontFace: TFontFace);
procedure SetTextTypeFace(_typeface: TTextTypeFace);
procedure SetTextChildTypeFace(_typeface: TTextTypeFace);
procedure SetBackgroundChild(_color: TARGBColorBridge);
procedure SetHighLightSelectedChildItemColor(_color: TARGBColorBridge);
procedure SetItems(Value: TStrings);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Init; override;
procedure Refresh;
procedure UpdateLayout; override;
procedure GenEvent_OnClick(Obj: TObject);
function jCreate(): jObject;
procedure jFree();
procedure SetViewParent(_viewgroup: jObject); override;
function GetViewParent(): jObject; override;
procedure RemoveFromViewParent(); override;
function GetView(): jObject; override;
procedure SetLParamWidth(_w: integer);
procedure SetLParamHeight(_h: integer);
function GetLParamWidth(): integer;
function GetLParamHeight(): integer;
procedure SetLGravity(_gravity: TLayoutGravity);
procedure SetLWeight(_w: single);
procedure SetLeftTopRightBottomWidthHeight(_left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer);
procedure AddLParamsAnchorRule(_rule: integer);
procedure AddLParamsParentRule(_rule: integer);
procedure SetLayoutAll(_idAnchor: integer);
procedure ClearLayout();
procedure Add(_header: string; _delimitedChildItems: string); overload;
procedure Add(_delimitedItem: string; _headerDelimiter: string; _childInnerDelimiter: string); overload;
procedure SetGroupItemDelimiter(_itemGroupDelimiter: string);
procedure SetChildItemDelimiter(_itemChildDelimiter: string);
procedure SetFontColorAll(_color: TARGBColorBridge);
procedure SetFontChildColorAll(_color: TARGBColorBridge);
procedure SetFontSizeUnit(_unit: TFontSizeUnit);
procedure SetFontSize(_fontSize: DWord);
procedure SetFontChildSize(_fontSize: DWord);
procedure SetImageItemIdentifier(_imageResIdentifier: string);
procedure SetImageChildItemIdentifier(_imageResIdentifier: string);
procedure Clear();
procedure ClearChildren(_groupPosition: integer);
procedure ClearGroup(_groupPosition: integer);
procedure GenEvent_OnGroupExpand(Obj: TObject; groupPosition: integer; groupHeader: string);
procedure GenEvent_OnGroupCollapse(Obj: TObject; groupPosition: integer; groupHeader: string);
procedure GenEvent_OnChildClick(Obj: TObject; groupPosition: integer; groupHeader: string; childItemPosition: integer; childItemCaption: string);
published
property Items: TStrings read FItems write SetItems;
property GroupItemDelimiter: string read FGroupItemDelimiter write SetGroupItemDelimiter;
property ChildItemDelimiter: string read FChildItemDelimiter write SetChildItemDelimiter;
property BackgroundColor: TARGBColorBridge read FColor write SetColor;
property BackgroundChildColor: TARGBColorBridge read FBackgroundChildColor write SetBackgroundChild default colbrDefault;
property FontColor: TARGBColorBridge read FFontColor write SetFontColor;
property FontChildColor: TARGBColorBridge read FFontChildColor write SetFontChildColor;
property FontSize: DWord read FFontSize write SetFontSize;
property FontChildSize: DWord read FFontChildSize write SetFontChildSize;
property FontSizeUnit: TFontSizeUnit read FFontSizeUnit write SetFontSizeUnit;
property TextAlign: TTextAlign read FTextAlign write SetTextAlign;
property TextChildAlign: TTextAlign read FTextChildAlign write SetTextChildAlign;
property FontFace: TFontFace read FFontFace write SetFontFace default ffNormal;
property TextTypeFace: TTextTypeFace read FTextTypeFace write SetTextTypeFace default tfNormal;
property TextChildTypeFace: TTextTypeFace read FTextChildTypeFace write SetTextChildTypeFace default tfNormal;
property ImageItemIdentifier: string read FImageItemIdentifier write SetImageItemIdentifier;
property ImageChildItemIdentifier: string read FImageChildItemIdentifier write SetImageChildItemIdentifier;
property HighLightSelectedChildItemColor: TARGBColorBridge read FHighLightSelectedChildItemColor write SetHighLightSelectedChildItemColor;
//property OnClick: TOnNotify read FOnClick write FOnClick;
property OnGroupItemExpand: TOnGroupItemExpand read FOnGroupItemExpand write FOnGroupItemExpand;
property OnGroupItemCollapse: TOnGroupItemCollapse read FOnGroupItemCollapse write FOnGroupItemCollapse;
property OnOnChildItemClick: TOnOnChildItemClick read FOnOnChildItemClick write FOnOnChildItemClick;
end;
function jExpandableListView_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject;
procedure jExpandableListView_jFree(env: PJNIEnv; _jexpandablelistview: JObject);
procedure jExpandableListView_SetViewParent(env: PJNIEnv; _jexpandablelistview: JObject; _viewgroup: jObject);
function jExpandableListView_GetParent(env: PJNIEnv; _jexpandablelistview: JObject): jObject;
procedure jExpandableListView_RemoveFromViewParent(env: PJNIEnv; _jexpandablelistview: JObject);
function jExpandableListView_GetView(env: PJNIEnv; _jexpandablelistview: JObject): jObject;
procedure jExpandableListView_SetLParamWidth(env: PJNIEnv; _jexpandablelistview: JObject; _w: integer);
procedure jExpandableListView_SetLParamHeight(env: PJNIEnv; _jexpandablelistview: JObject; _h: integer);
function jExpandableListView_GetLParamWidth(env: PJNIEnv; _jexpandablelistview: JObject): integer;
function jExpandableListView_GetLParamHeight(env: PJNIEnv; _jexpandablelistview: JObject): integer;
procedure jExpandableListView_SetLGravity(env: PJNIEnv; _jexpandablelistview: JObject; _g: integer);
procedure jExpandableListView_SetLWeight(env: PJNIEnv; _jexpandablelistview: JObject; _w: single);
procedure jExpandableListView_SetLeftTopRightBottomWidthHeight(env: PJNIEnv; _jexpandablelistview: JObject; _left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer);
procedure jExpandableListView_AddLParamsAnchorRule(env: PJNIEnv; _jexpandablelistview: JObject; _rule: integer);
procedure jExpandableListView_AddLParamsParentRule(env: PJNIEnv; _jexpandablelistview: JObject; _rule: integer);
procedure jExpandableListView_SetLayoutAll(env: PJNIEnv; _jexpandablelistview: JObject; _idAnchor: integer);
procedure jExpandableListView_ClearLayoutAll(env: PJNIEnv; _jexpandablelistview: JObject);
procedure jExpandableListView_SetId(env: PJNIEnv; _jexpandablelistview: JObject; _id: integer);
procedure jExpandableListView_Add(env: PJNIEnv; _jexpandablelistview: JObject; _header: string; _delimitedItems: string); overload;
procedure jExpandableListView_Add(env: PJNIEnv; _jexpandablelistview: JObject; _delimitedItem: string; _headerDelimiter: string; _childInnerDelimiter: string); overload;
procedure jExpandableListView_SetItemHeaderDelimiter(env: PJNIEnv; _jexpandablelistview: JObject; _itemHeaderDelimiter: string);
procedure jExpandableListView_SetItemChildInnerDelimiter(env: PJNIEnv; _jexpandablelistview: JObject; _itemChildInnerDelimiter: string);
procedure jExpandableListView_SetFontColor(env: PJNIEnv; _jexpandablelistview: JObject; _color: integer);
procedure jExpandableListView_SetFontChildColor(env: PJNIEnv; _jexpandablelistview: JObject; _color: integer);
procedure jExpandableListView_SetFontColorAll(env: PJNIEnv; _jexpandablelistview: JObject; _color: integer);
procedure jExpandableListView_SetFontChildColorAll(env: PJNIEnv; _jexpandablelistview: JObject; _color: integer);
procedure jExpandableListView_SetFontSizeUnit(env: PJNIEnv; _jexpandablelistview: JObject; _unit: integer);
procedure jExpandableListView_SetFontSize(env: PJNIEnv; _jexpandablelistview: JObject; _fontSize: integer);
procedure jExpandableListView_SetFontChildSize(env: PJNIEnv; _jexpandablelistview: JObject; _fontSize: integer);
procedure jExpandableListView_SetTextAlign(env: PJNIEnv; _jexpandablelistview: JObject; _align: integer);
procedure jExpandableListView_SetTextChildAlign(env: PJNIEnv; _jexpandablelistview: JObject; _align: integer);
procedure jExpandableListView_SetFontFace(env: PJNIEnv; _jexpandablelistview: JObject; _fontFace: integer);
procedure jExpandableListView_SetTextTypeFace(env: PJNIEnv; _jexpandablelistview: JObject; _typeface: integer);
procedure jExpandableListView_SetTextChildTypeFace(env: PJNIEnv; _jexpandablelistview: JObject; _typeface: integer);
procedure jExpandableListView_SetBackgroundChild(env: PJNIEnv; _jexpandablelistview: JObject; _color: integer);
procedure jExpandableListView_SetImageItemIdentifier(env: PJNIEnv; _jexpandablelistview: JObject; _imageResIdentifier: string);
procedure jExpandableListView_SetImageChildItemIdentifier(env: PJNIEnv; _jexpandablelistview: JObject; _imageResIdentifier: string);
procedure jExpandableListView_SetHighLightSelectedChildItemColor(env: PJNIEnv; _jexpandablelistview: JObject; _color: integer);
procedure jExpandableListView_Clear(env: PJNIEnv; _jexpandablelistview: JObject);
procedure jExpandableListView_ClearChildren(env: PJNIEnv; _jexpandablelistview: JObject; _groupPosition: integer);
procedure jExpandableListView_ClearGroup(env: PJNIEnv; _jexpandablelistview: JObject; _groupPosition: integer);
implementation
{--------- jExpandableListView --------------}
constructor jExpandableListView.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
if gapp <> nil then FId := gapp.GetNewId();
FHeight := 96; //??
FWidth := 200; //??
FLParamWidth := lpMatchParent; //lpWrapContent
FLParamHeight := lpWrapContent; //lpMatchParent
FAcceptChildrenAtDesignTime:= False;
FItems:= TStringList.Create();
FGroupItemDelimiter:= '$';
FChildItemDelimiter:= ';';
FTextAlign:= alLeft;
FTextChildAlign:= alLeft;
FFontChildColor:= colbrDefault;
FBackgroundChildColor:= colbrDefault;
FHighLightSelectedChildItemColor:= colbrDefault;
end;
destructor jExpandableListView.Destroy;
begin
if not (csDesigning in ComponentState) then
begin
if FjObject <> nil then
begin
jFree();
FjObject:= nil;
end;
end;
//you others free code here...'
FItems.Free;
inherited Destroy;
end;
procedure jExpandableListView.Init;
var
rToP: TPositionRelativeToParent;
rToA: TPositionRelativeToAnchorID;
i: integer;
begin
if not FInitialized then
begin
inherited Init; //set default ViewParent/FjPRLayout as jForm.View!
//your code here: set/initialize create params....
FjObject := jCreate(); if FjObject = nil then exit;
if FParent <> nil then
sysTryNewParent( FjPRLayout, FParent);
FjPRLayoutHome:= FjPRLayout;
jExpandableListView_SetViewParent(gApp.jni.jEnv, FjObject, FjPRLayout);
jExpandableListView_SetId(gApp.jni.jEnv, FjObject, Self.Id);
end;
jExpandableListView_setLeftTopRightBottomWidthHeight(gApp.jni.jEnv, FjObject ,
FMarginLeft,FMarginTop,FMarginRight,FMarginBottom,
sysGetLayoutParams( FWidth, FLParamWidth, Self.Parent, sdW, fmarginLeft + fmarginRight ),
sysGetLayoutParams( FHeight, FLParamHeight, Self.Parent, sdH, fMargintop + fMarginbottom ));
for rToA := raAbove to raAlignRight do
begin
if rToA in FPositionRelativeToAnchor then
begin
jExpandableListView_AddLParamsAnchorRule(gApp.jni.jEnv, FjObject, GetPositionRelativeToAnchor(rToA));
end;
end;
for rToP := rpBottom to rpCenterVertical do
begin
if rToP in FPositionRelativeToParent then
begin
jExpandableListView_AddLParamsParentRule(gApp.jni.jEnv, FjObject, GetPositionRelativeToParent(rToP));
end;
end;
if not FInitialized then
begin
if FFontSizeUnit <> unitDefault then
jExpandableListView_SetFontSizeUnit(gApp.jni.jEnv, FjObject, Ord(FFontSizeUnit));
if FFontSize > 0 then
jExpandableListView_SetFontSize(gApp.jni.jEnv, FjObject , FFontSize);
if FFontColor <> colbrDefault then
jExpandableListView_SetFontColor(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, FFontColor));
if FFontChildColor <> colbrDefault then
jExpandableListView_SetFontChildColor(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, FFontChildColor));
if FBackgroundChildColor <> colbrDefault then
jExpandableListView_SetBackgroundChild(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, FBackgroundChildColor));
if FTextAlign <> alLeft then
jExpandableListView_SetTextAlign(gApp.jni.jEnv, FjObject, Ord(FTextAlign));
if FTextChildAlign <> alLeft then
jExpandableListView_SetTextChildAlign(gApp.jni.jEnv, FjObject, Ord(FTextChildAlign));
if FFontFace <> ffNormal then
jExpandableListView_SetFontFace(gApp.jni.jEnv, FjObject, Ord(FFontFace));
if FTextTypeFace <> tfNormal then
jExpandableListView_SetTextTypeFace(gApp.jni.jEnv, FjObject, Ord(FTextTypeFace));
if FImageItemIdentifier <> '' then
jExpandableListView_SetImageItemIdentifier(gApp.jni.jEnv, FjObject, FImageItemIdentifier);
if FImageChildItemIdentifier <> '' then
jExpandableListView_SetImageChildItemIdentifier(gApp.jni.jEnv, FjObject, FImageChildItemIdentifier);
if FHighLightSelectedChildItemColor <> colbrDefault then
jExpandableListView_SetHighLightSelectedChildItemColor(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, FHighLightSelectedChildItemColor));
for i:= 0 to FItems.Count - 1 do
begin
if FItems.Strings[i] <> '' then
jExpandableListView_Add(gApp.jni.jEnv, FjObject , FItems.Strings[i], FGroupItemDelimiter, FChildItemDelimiter);
end;
end;
if Self.Anchor <> nil then Self.AnchorId:= Self.Anchor.Id
else Self.AnchorId:= -1; //dummy
jExpandableListView_SetLayoutAll(gApp.jni.jEnv, FjObject, Self.AnchorId);
if not FInitialized then
begin
FInitialized:= True;
if FColor <> colbrDefault then
View_SetBackGroundColor(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, FColor));
View_SetVisible(gApp.jni.jEnv, FjObject, FVisible);
end;
end;
procedure jExpandableListView.SetColor(Value: TARGBColorBridge);
begin
FColor:= Value;
if (FInitialized = True) and (FColor <> colbrDefault) then
View_SetBackGroundColor(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, FColor));
end;
procedure jExpandableListView.SetVisible(Value : Boolean);
begin
FVisible:= Value;
if FInitialized then
View_SetVisible(gApp.jni.jEnv, FjObject, FVisible);
end;
procedure jExpandableListView.UpdateLayout;
begin
if not FInitialized then exit;
ClearLayout();
inherited UpdateLayout;
init;
end;
procedure jExpandableListView.Refresh;
begin
if FInitialized then
View_Invalidate(gApp.jni.jEnv, FjObject);
end;
//Event : Java -> Pascal
procedure jExpandableListView.GenEvent_OnClick(Obj: TObject);
begin
if Assigned(FOnClick) then FOnClick(Obj);
end;
function jExpandableListView.jCreate(): jObject;
begin
Result:= jExpandableListView_jCreate(gApp.jni.jEnv, int64(Self), gApp.jni.jThis);
end;
procedure jExpandableListView.jFree();
begin
//in designing component state: set value here...
if FInitialized then
jExpandableListView_jFree(gApp.jni.jEnv, FjObject);
end;
procedure jExpandableListView.SetViewParent(_viewgroup: jObject);
begin
//in designing component state: set value here...
if FInitialized then
jExpandableListView_SetViewParent(gApp.jni.jEnv, FjObject, _viewgroup);
end;
function jExpandableListView.GetViewParent(): jObject;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jExpandableListView_GetParent(gApp.jni.jEnv, FjObject);
end;
procedure jExpandableListView.RemoveFromViewParent();
begin
//in designing component state: set value here...
if FInitialized then
jExpandableListView_RemoveFromViewParent(gApp.jni.jEnv, FjObject);
end;
function jExpandableListView.GetView(): jObject;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jExpandableListView_GetView(gApp.jni.jEnv, FjObject);
end;
procedure jExpandableListView.SetLParamWidth(_w: integer);
begin
//in designing component state: set value here...
if FInitialized then
jExpandableListView_SetLParamWidth(gApp.jni.jEnv, FjObject, _w);
end;
procedure jExpandableListView.SetLParamHeight(_h: integer);
begin
//in designing component state: set value here...
if FInitialized then
jExpandableListView_SetLParamHeight(gApp.jni.jEnv, FjObject, _h);
end;
function jExpandableListView.GetLParamWidth(): integer;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jExpandableListView_GetLParamWidth(gApp.jni.jEnv, FjObject);
end;
function jExpandableListView.GetLParamHeight(): integer;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jExpandableListView_GetLParamHeight(gApp.jni.jEnv, FjObject);
end;
procedure jExpandableListView.SetLGravity(_gravity: TLayoutGravity);
begin
//in designing component state: set value here...
FGravityInParent:= _gravity;
if FInitialized then
jExpandableListView_SetLGravity(gApp.jni.jEnv, FjObject, Ord(_gravity));
end;
procedure jExpandableListView.SetLWeight(_w: single);
begin
//in designing component state: set value here...
if FInitialized then
jExpandableListView_SetLWeight(gApp.jni.jEnv, FjObject, _w);
end;
procedure jExpandableListView.SetLeftTopRightBottomWidthHeight(_left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer);
begin
//in designing component state: set value here...
if FInitialized then
jExpandableListView_SetLeftTopRightBottomWidthHeight(gApp.jni.jEnv, FjObject, _left ,_top ,_right ,_bottom ,_w ,_h);
end;
procedure jExpandableListView.AddLParamsAnchorRule(_rule: integer);
begin
//in designing component state: set value here...
if FInitialized then
jExpandableListView_AddLParamsAnchorRule(gApp.jni.jEnv, FjObject, _rule);
end;
procedure jExpandableListView.AddLParamsParentRule(_rule: integer);
begin
//in designing component state: set value here...
if FInitialized then
jExpandableListView_AddLParamsParentRule(gApp.jni.jEnv, FjObject, _rule);
end;
procedure jExpandableListView.SetLayoutAll(_idAnchor: integer);
begin
//in designing component state: set value here...
if FInitialized then
jExpandableListView_SetLayoutAll(gApp.jni.jEnv, FjObject, _idAnchor);
end;
procedure jExpandableListView.ClearLayout();
var
rToP: TPositionRelativeToParent;
rToA: TPositionRelativeToAnchorID;
begin
//in designing component state: set value here...
if FInitialized then
begin
jExpandableListView_clearLayoutAll(gApp.jni.jEnv, FjObject);
for rToP := rpBottom to rpCenterVertical do
if rToP in FPositionRelativeToParent then
jExpandableListView_addlParamsParentRule(gApp.jni.jEnv, FjObject , GetPositionRelativeToParent(rToP));
for rToA := raAbove to raAlignRight do
if rToA in FPositionRelativeToAnchor then
jExpandableListView_addlParamsAnchorRule(gApp.jni.jEnv, FjObject , GetPositionRelativeToAnchor(rToA));
end;
end;
Procedure jExpandableListView.SetFontColor(_color: TARGBColorBridge);
begin
FFontColor:= _color;
if (FInitialized = True) and (FFontColor <> colbrDefault ) then
jExpandableListView_SetFontColor(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, FFontColor));
end;
procedure jExpandableListView.SetFontChildColor(_color: TARGBColorBridge);
begin
//in designing component state: set value here...
FFontChildColor := _color;
if (FInitialized = True) and (FFontColor <> colbrDefault ) then
jExpandableListView_SetFontChildColor(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, FFontChildColor));
end;
procedure jExpandableListView.SetItems(Value: TStrings);
var
i: integer;
begin
FItems.Assign(Value);
if FInitialized then
begin
for i:= 0 to FItems.Count - 1 do
begin
if FItems.Strings[i] <> '' then
jExpandableListView_Add(gApp.jni.jEnv, FjObject , FItems.Strings[i], FGroupItemDelimiter, FChildItemDelimiter);
end;
end;
end;
procedure jExpandableListView.Add(_header: string; _delimitedChildItems: string);
begin
//in designing component state: set value here...
if FInitialized then
jExpandableListView_Add(gApp.jni.jEnv, FjObject, _header , _delimitedChildItems);
end;
procedure jExpandableListView.Add(_delimitedItem: string; _headerDelimiter: string; _childInnerDelimiter: string);
begin
//in designing component state: set value here...
if FInitialized then
jExpandableListView_Add(gApp.jni.jEnv, FjObject, _delimitedItem ,_headerDelimiter , _childInnerDelimiter);
end;
procedure jExpandableListView.SetGroupItemDelimiter(_itemGroupDelimiter: string);
begin
//in designing component state: set value here...
FGroupItemDelimiter:= _itemGroupDelimiter;
if FInitialized then
jExpandableListView_SetItemHeaderDelimiter(gApp.jni.jEnv, FjObject, _itemGroupDelimiter);
end;
procedure jExpandableListView.SetChildItemDelimiter(_itemChildDelimiter: string);
begin
//in designing component state: set value here...
FChildItemDelimiter:= _itemChildDelimiter;
if FInitialized then
jExpandableListView_SetItemChildInnerDelimiter(gApp.jni.jEnv, FjObject, _itemChildDelimiter);
end;
procedure jExpandableListView.SetFontColorAll(_color: TARGBColorBridge);
begin
//in designing component state: set value here...
if FInitialized then
jExpandableListView_SetFontColorAll(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, _color));
end;
procedure jExpandableListView.SetFontChildColorAll(_color: TARGBColorBridge);
begin
//in designing component state: set value here...
if FInitialized then
jExpandableListView_SetFontChildColorAll(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, _color));
end;
procedure jExpandableListView.SetBackgroundChild(_color: TARGBColorBridge);
begin
//in designing component state: set value here...
FBackgroundChildColor:= _color;
if FInitialized then
jExpandableListView_SetBackgroundChild(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, FBackgroundChildColor));
end;
procedure jExpandableListView.SetFontSizeUnit(_unit: TFontSizeUnit);
begin
//in designing component state: set value here...
FFontSizeUnit:=_unit;
if FInitialized then
jExpandableListView_SetFontSizeUnit(gApp.jni.jEnv, FjObject, Ord(_unit) );
end;
procedure jExpandableListView.SetFontSize(_fontSize: DWord);
begin
//in designing component state: set value here...
FFontSize:= _fontSize;
if FInitialized then
jExpandableListView_SetFontSize(gApp.jni.jEnv, FjObject, _fontSize);
end;
procedure jExpandableListView.SetFontChildSize(_fontSize: DWord);
begin
//in designing component state: set value here...
FFontChildSize:= _fontSize;
if FInitialized then
jExpandableListView_SetFontChildSize(gApp.jni.jEnv, FjObject, _fontSize);
end;
procedure jExpandableListView.SetTextAlign(_align: TTextAlign);
begin
//in designing component state: set value here...
FTextAlign := _align;
if FInitialized then
jExpandableListView_SetTextAlign(gApp.jni.jEnv, FjObject, Ord(_align));
end;
procedure jExpandableListView.SetTextChildAlign(_align: TTextAlign);
begin
//in designing component state: set value here...
FTextChildAlign:= _align;
if FInitialized then
jExpandableListView_SetTextChildAlign(gApp.jni.jEnv, FjObject, Ord(_align) );
end;
procedure jExpandableListView.SetFontFace(_fontFace: TFontFace);
begin
//in designing component state: set value here...
FFontFace:= _fontFace;
if FInitialized then
jExpandableListView_SetFontFace(gApp.jni.jEnv, FjObject, Ord(_fontFace));
end;
procedure jExpandableListView.SetTextChildTypeFace(_typeface: TTextTypeFace);
begin
//in designing component state: set value here...
FTextChildTypeFace:= _typeface;
if FInitialized then
jExpandableListView_SetTextChildTypeFace(gApp.jni.jEnv, FjObject, Ord(_typeface));
end;
procedure jExpandableListView.GenEvent_OnGroupExpand(Obj: TObject; groupPosition: integer; groupHeader: string);
begin
if Assigned(FOnGroupItemExpand) then FOnGroupItemExpand(Obj, groupPosition, groupHeader);
end;
procedure jExpandableListView.SetTextTypeFace(_typeface: TTextTypeFace);
begin
//in designing component state: set value here...
FTextTypeFace:= _typeface;
if FInitialized then
jExpandableListView_SetTextTypeFace(gApp.jni.jEnv, FjObject, Ord(_typeface));
end;
procedure jExpandableListView.SetImageItemIdentifier(_imageResIdentifier: string);
begin
//in designing component state: set value here...
FImageItemIdentifier:= _imageResIdentifier;
if FInitialized then
jExpandableListView_SetImageItemIdentifier(gApp.jni.jEnv, FjObject, FImageItemIdentifier);
end;
procedure jExpandableListView.SetImageChildItemIdentifier(_imageResIdentifier: string);
begin
//in designing component state: set value here...
FImageChildItemIdentifier:= _imageResIdentifier;
if FInitialized then
jExpandableListView_SetImageChildItemIdentifier(gApp.jni.jEnv, FjObject, ImageChildItemIdentifier);
end;
procedure jExpandableListView.SetHighLightSelectedChildItemColor(_color: TARGBColorBridge);
begin
//in designing component state: set value here...
FHighLightSelectedChildItemColor:= _color;
if FInitialized then
jExpandableListView_SetHighLightSelectedChildItemColor(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, FHighLightSelectedChildItemColor));
end;
procedure jExpandableListView.Clear();
begin
//in designing component state: set value here...
if FInitialized then
jExpandableListView_Clear(gApp.jni.jEnv, FjObject);
end;
procedure jExpandableListView.ClearChildren(_groupPosition: integer);
begin
//in designing component state: set value here...
if FInitialized then
jExpandableListView_ClearChildren(gApp.jni.jEnv, FjObject, _groupPosition);
end;
procedure jExpandableListView.ClearGroup(_groupPosition: integer);
begin
//in designing component state: set value here...
if FInitialized then
jExpandableListView_ClearGroup(gApp.jni.jEnv, FjObject, _groupPosition);
end;
procedure jExpandableListView.GenEvent_OnGroupCollapse(Obj: TObject; groupPosition: integer; groupHeader: string);
begin
if Assigned(FOnGroupItemCollapse) then FOnGroupItemCollapse(Obj, groupPosition, groupHeader);
end;
procedure jExpandableListView.GenEvent_OnChildClick(Obj: TObject; groupPosition: integer; groupHeader: string; childItemPosition: integer; childItemCaption: string);
begin
if Assigned(FOnOnChildItemClick) then FOnOnChildItemClick(Obj, groupPosition, groupHeader, childItemPosition, childItemCaption);
end;
{-------- jExpandableListView_JNI_Bridge ----------}
function jExpandableListView_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject;
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].j:= _Self;
jCls:= Get_gjClass(env);
jMethod:= env^.GetMethodID(env, jCls, 'jExpandableListView_jCreate', '(J)Ljava/lang/Object;');
Result:= env^.CallObjectMethodA(env, this, jMethod, @jParams);
Result:= env^.NewGlobalRef(env, Result);
end;
(*
//Please, you need insert:
public java.lang.Object jExpandableListView_jCreate(long _Self) {
return (java.lang.Object)(new jExpandableListView(this,_Self));
}
//to end of "public class Controls" in "Controls.java"
*)
procedure jExpandableListView_jFree(env: PJNIEnv; _jexpandablelistview: JObject);
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'jFree', '()V');
env^.CallVoidMethod(env, _jexpandablelistview, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_SetViewParent(env: PJNIEnv; _jexpandablelistview: JObject; _viewgroup: jObject);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= _viewgroup;
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'SetViewParent', '(Landroid/view/ViewGroup;)V');
env^.CallVoidMethodA(env, _jexpandablelistview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
function jExpandableListView_GetParent(env: PJNIEnv; _jexpandablelistview: JObject): jObject;
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'GetParent', '()Landroid/view/ViewGroup;');
Result:= env^.CallObjectMethod(env, _jexpandablelistview, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_RemoveFromViewParent(env: PJNIEnv; _jexpandablelistview: JObject);
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'RemoveFromViewParent', '()V');
env^.CallVoidMethod(env, _jexpandablelistview, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
function jExpandableListView_GetView(env: PJNIEnv; _jexpandablelistview: JObject): jObject;
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'GetView', '()Landroid/view/View;');
Result:= env^.CallObjectMethod(env, _jexpandablelistview, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_SetLParamWidth(env: PJNIEnv; _jexpandablelistview: JObject; _w: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _w;
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'SetLParamWidth', '(I)V');
env^.CallVoidMethodA(env, _jexpandablelistview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_SetLParamHeight(env: PJNIEnv; _jexpandablelistview: JObject; _h: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _h;
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'SetLParamHeight', '(I)V');
env^.CallVoidMethodA(env, _jexpandablelistview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
function jExpandableListView_GetLParamWidth(env: PJNIEnv; _jexpandablelistview: JObject): integer;
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'GetLParamWidth', '()I');
Result:= env^.CallIntMethod(env, _jexpandablelistview, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
function jExpandableListView_GetLParamHeight(env: PJNIEnv; _jexpandablelistview: JObject): integer;
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'GetLParamHeight', '()I');
Result:= env^.CallIntMethod(env, _jexpandablelistview, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_SetLGravity(env: PJNIEnv; _jexpandablelistview: JObject; _g: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _g;
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'SetLGravity', '(I)V');
env^.CallVoidMethodA(env, _jexpandablelistview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_SetLWeight(env: PJNIEnv; _jexpandablelistview: JObject; _w: single);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].f:= _w;
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'SetLWeight', '(F)V');
env^.CallVoidMethodA(env, _jexpandablelistview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_SetLeftTopRightBottomWidthHeight(env: PJNIEnv; _jexpandablelistview: JObject; _left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer);
var
jParams: array[0..5] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _left;
jParams[1].i:= _top;
jParams[2].i:= _right;
jParams[3].i:= _bottom;
jParams[4].i:= _w;
jParams[5].i:= _h;
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'SetLeftTopRightBottomWidthHeight', '(IIIIII)V');
env^.CallVoidMethodA(env, _jexpandablelistview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_AddLParamsAnchorRule(env: PJNIEnv; _jexpandablelistview: JObject; _rule: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _rule;
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'AddLParamsAnchorRule', '(I)V');
env^.CallVoidMethodA(env, _jexpandablelistview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_AddLParamsParentRule(env: PJNIEnv; _jexpandablelistview: JObject; _rule: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _rule;
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'AddLParamsParentRule', '(I)V');
env^.CallVoidMethodA(env, _jexpandablelistview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_SetLayoutAll(env: PJNIEnv; _jexpandablelistview: JObject; _idAnchor: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _idAnchor;
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'SetLayoutAll', '(I)V');
env^.CallVoidMethodA(env, _jexpandablelistview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_ClearLayoutAll(env: PJNIEnv; _jexpandablelistview: JObject);
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'ClearLayoutAll', '()V');
env^.CallVoidMethod(env, _jexpandablelistview, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_SetId(env: PJNIEnv; _jexpandablelistview: JObject; _id: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _id;
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'setId', '(I)V');
env^.CallVoidMethodA(env, _jexpandablelistview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_Add(env: PJNIEnv; _jexpandablelistview: JObject; _header: string; _delimitedItems: string);
var
jParams: array[0..1] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_header));
jParams[1].l:= env^.NewStringUTF(env, PChar(_delimitedItems));
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'Add', '(Ljava/lang/String;Ljava/lang/String;)V');
env^.CallVoidMethodA(env, _jexpandablelistview, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env,jParams[1].l);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_Add(env: PJNIEnv; _jexpandablelistview: JObject; _delimitedItem: string; _headerDelimiter: string; _childInnerDelimiter: string);
var
jParams: array[0..2] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_delimitedItem));
jParams[1].l:= env^.NewStringUTF(env, PChar(_headerDelimiter));
jParams[2].l:= env^.NewStringUTF(env, PChar(_childInnerDelimiter));
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'Add', '(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V');
env^.CallVoidMethodA(env, _jexpandablelistview, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env,jParams[1].l);
env^.DeleteLocalRef(env,jParams[2].l);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_SetItemHeaderDelimiter(env: PJNIEnv; _jexpandablelistview: JObject; _itemHeaderDelimiter: string);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_itemHeaderDelimiter));
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'SetItemHeaderDelimiter', '(Ljava/lang/String;)V');
env^.CallVoidMethodA(env, _jexpandablelistview, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_SetItemChildInnerDelimiter(env: PJNIEnv; _jexpandablelistview: JObject; _itemChildInnerDelimiter: string);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_itemChildInnerDelimiter));
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'SetItemChildInnerDelimiter', '(Ljava/lang/String;)V');
env^.CallVoidMethodA(env, _jexpandablelistview, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_SetFontColor(env: PJNIEnv; _jexpandablelistview: JObject; _color: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _color;
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'SetFontColor', '(I)V');
env^.CallVoidMethodA(env, _jexpandablelistview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_SetFontChildColor(env: PJNIEnv; _jexpandablelistview: JObject; _color: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _color;
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'SetFontChildColor', '(I)V');
env^.CallVoidMethodA(env, _jexpandablelistview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_SetFontColorAll(env: PJNIEnv; _jexpandablelistview: JObject; _color: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _color;
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'SetFontColorAll', '(I)V');
env^.CallVoidMethodA(env, _jexpandablelistview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_SetFontChildColorAll(env: PJNIEnv; _jexpandablelistview: JObject; _color: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _color;
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'SetFontChildColorAll', '(I)V');
env^.CallVoidMethodA(env, _jexpandablelistview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_SetFontSizeUnit(env: PJNIEnv; _jexpandablelistview: JObject; _unit: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _unit;
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'SetFontSizeUnit', '(I)V');
env^.CallVoidMethodA(env, _jexpandablelistview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_SetFontSize(env: PJNIEnv; _jexpandablelistview: JObject; _fontSize: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _fontSize;
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'SetFontSize', '(I)V');
env^.CallVoidMethodA(env, _jexpandablelistview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_SetFontChildSize(env: PJNIEnv; _jexpandablelistview: JObject; _fontSize: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _fontSize;
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'SetFontChildSize', '(I)V');
env^.CallVoidMethodA(env, _jexpandablelistview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_SetTextAlign(env: PJNIEnv; _jexpandablelistview: JObject; _align: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _align;
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'SetTextAlign', '(I)V');
env^.CallVoidMethodA(env, _jexpandablelistview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_SetTextChildAlign(env: PJNIEnv; _jexpandablelistview: JObject; _align: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _align;
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'SetTextChildAlign', '(I)V');
env^.CallVoidMethodA(env, _jexpandablelistview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_SetFontFace(env: PJNIEnv; _jexpandablelistview: JObject; _fontFace: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _fontFace;
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'SetFontFace', '(I)V');
env^.CallVoidMethodA(env, _jexpandablelistview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_SetTextTypeFace(env: PJNIEnv; _jexpandablelistview: JObject; _typeface: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _typeface;
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'SetTextTypeFace', '(I)V');
env^.CallVoidMethodA(env, _jexpandablelistview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_SetTextChildTypeFace(env: PJNIEnv; _jexpandablelistview: JObject; _typeface: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _typeface;
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'SetTextChildTypeFace', '(I)V');
env^.CallVoidMethodA(env, _jexpandablelistview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_SetBackgroundChild(env: PJNIEnv; _jexpandablelistview: JObject; _color: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _color;
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'SetBackgroundChild', '(I)V');
env^.CallVoidMethodA(env, _jexpandablelistview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_SetImageItemIdentifier(env: PJNIEnv; _jexpandablelistview: JObject; _imageResIdentifier: string);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_imageResIdentifier));
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'SetImageItemIdentifier', '(Ljava/lang/String;)V');
env^.CallVoidMethodA(env, _jexpandablelistview, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_SetImageChildItemIdentifier(env: PJNIEnv; _jexpandablelistview: JObject; _imageResIdentifier: string);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_imageResIdentifier));
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'SetImageChildItemIdentifier', '(Ljava/lang/String;)V');
env^.CallVoidMethodA(env, _jexpandablelistview, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_SetHighLightSelectedChildItemColor(env: PJNIEnv; _jexpandablelistview: JObject; _color: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _color;
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'SetHighLightSelectedChildItemColor', '(I)V');
env^.CallVoidMethodA(env, _jexpandablelistview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_Clear(env: PJNIEnv; _jexpandablelistview: JObject);
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'Clear', '()V');
env^.CallVoidMethod(env, _jexpandablelistview, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_ClearChildren(env: PJNIEnv; _jexpandablelistview: JObject; _groupPosition: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _groupPosition;
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'ClearChildren', '(I)V');
env^.CallVoidMethodA(env, _jexpandablelistview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jExpandableListView_ClearGroup(env: PJNIEnv; _jexpandablelistview: JObject; _groupPosition: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _groupPosition;
jCls:= env^.GetObjectClass(env, _jexpandablelistview);
jMethod:= env^.GetMethodID(env, jCls, 'ClearGroup', '(I)V');
env^.CallVoidMethodA(env, _jexpandablelistview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
end.
|
unit uFormHerancaCadastro;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Edit,
FMX.Layouts, FMX.StdCtrls, FMX.Objects, FMX.Controls.Presentation,
FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base,
FMX.ListView, FMX.TabControl, System.Actions, FMX.ActnList, Data.DB,
Datasnap.DBClient, FMX.Ani, System.Rtti, System.Bindings.Outputs,
Fmx.Bind.Editors, Data.Bind.EngExt, Fmx.Bind.DBEngExt, Data.Bind.Components,
Data.Bind.DBScope, FMX.ListBox, System.ImageList, FMX.ImgList;
type
TFormHerancaCadastro = class(TForm)
tbTopo: TToolBar;
imgFundoToolBar: TImage;
btnRetornar: TSpeedButton;
btnAbrirPesquisa: TSpeedButton;
lblTituloToolBar: TLabel;
lytPrincipal: TLayout;
tbPesquisa: TToolBar;
imgFundoPesquisa: TImage;
edtPesquisa: TEdit;
ltvPesquisa: TListView;
tcPrincipal: TTabControl;
tabPesquisa: TTabItem;
tabDados: TTabItem;
aclGeral: TActionList;
ChangeTabPrincipal: TChangeTabAction;
cdsPesquisa: TClientDataSet;
cdsDados: TClientDataSet;
cdsPesquisacodigo: TIntegerField;
anmPesquisa: TFloatAnimation;
BindSourceDB1: TBindSourceDB;
BindingsList1: TBindingsList;
LinkListControlToField1: TLinkListControlToField;
lytDados: TLayout;
tbTopoDados: TToolBar;
Image1: TImage;
btnRetornarDados: TSpeedButton;
tcDados: TTabControl;
tabDadosGeral: TTabItem;
ListBox1: TListBox;
rctEspera: TRectangle;
AniIndicator1: TAniIndicator;
lblEspera: TLabel;
lytGeral: TLayout;
il1: TImageList;
btn1: TButton;
procedure ltvPesquisaItemClick(const Sender: TObject;
const AItem: TListViewItem);
procedure FormCreate(Sender: TObject);
procedure btnAbrirPesquisaClick(Sender: TObject);
procedure edtPesquisaKeyDown(Sender: TObject; var Key: Word;
var KeyChar: Char; Shift: TShiftState);
procedure edtPesquisaTyping(Sender: TObject);
procedure btnRetornarDadosClick(Sender: TObject);
procedure btnRetornarClick(Sender: TObject);
procedure FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char;
Shift: TShiftState);
procedure edtPesquisaChangeTracking(Sender: TObject);
procedure btn1Click(Sender: TObject);
private
FIDUltimoRegistroPesquisa: Integer;
FPesquisando: Boolean;
procedure SetPesquisando(const Value: Boolean);
property IDUltimoRegistroPesquisa:Integer read FIDUltimoRegistroPesquisa;
procedure MudaTab(aTab:TTabItem; Sender:TObject);
{ Private declarations }
public
property Pesquisando:Boolean read FPesquisando write SetPesquisando;
procedure AntesDePesquisar;virtual;
procedure Pesquisa;virtual;
procedure DepoisDePesquisar;virtual;
protected
procedure Espera(aVisivel:Boolean; pTexto:string='');
{ Public declarations }
end;
implementation
{$R *.fmx}
uses uFormEspera, uFormPrincipal;
{ TFormHerancaCadastro }
procedure TFormHerancaCadastro.AntesDePesquisar;
begin
btnAbrirPesquisaClick(Self);
cdsPesquisa.Close;
Self.Espera(True);
Self.Pesquisando := True;
end;
procedure TFormHerancaCadastro.btn1Click(Sender: TObject);
begin
Pesquisa;
Self.DepoisDePesquisar;
end;
procedure TFormHerancaCadastro.btnAbrirPesquisaClick(Sender: TObject);
begin
tbPesquisa.Visible := not tbPesquisa.Visible;
case tbPesquisa.Visible of
True:
begin
edtPesquisa.Text := '';
edtPesquisa.SetFocus;
btnAbrirPesquisa.StyleLookup := 'arrowuptoolbutton';
end;
False:
begin
btnAbrirPesquisa.StyleLookup := 'searchtoolbutton';
end;
end;
end;
procedure TFormHerancaCadastro.btnRetornarClick(Sender: TObject);
begin
FormPrincipal.MudaTab(FormPrincipal.tabMenuPrincipal, Sender);
end;
procedure TFormHerancaCadastro.btnRetornarDadosClick(Sender: TObject);
begin
MudaTab(tabPesquisa, Sender);
end;
procedure TFormHerancaCadastro.DepoisDePesquisar;
begin
ltvPesquisa.ItemIndex := -1;
Self.Espera(False);
Self.Pesquisando := False;
end;
procedure TFormHerancaCadastro.edtPesquisaChangeTracking(Sender: TObject);
{$IFDEF WIN32}
var
thetext: String;
{$ENDIF}
begin
{$IFDEF WIN32}
thetext := edtPesquisa.Text;
edtPesquisa.OnChangeTracking := nil;
edtPesquisa.Text := '';
edtPesquisa.Text := AnsiUpperCase(thetext);
edtPesquisa.OnChangeTracking := edtPesquisaChangeTracking;
edtPesquisa.GoToTextEnd;
{$ENDIF}
end;
procedure TFormHerancaCadastro.edtPesquisaKeyDown(Sender: TObject;
var Key: Word; var KeyChar: Char; Shift: TShiftState);
begin
if Key = 13 then
begin
Self.Pesquisa;
Self.DepoisDePesquisar;
end;
end;
procedure TFormHerancaCadastro.edtPesquisaTyping(Sender: TObject);
begin
{$IFDEF WIN32}
{$ELSE}
edtPesquisa.Text:=AnsiUpperCase(edtPesquisa.Text);
edtPesquisa.GoToTextEnd;
{$ENDIF}
end;
procedure TFormHerancaCadastro.Espera(aVisivel: Boolean; pTexto: string);
begin
if pTexto = '' then
lblEspera.Text := 'Aguarde...'
else
lblEspera.Text := pTexto;
Self.rctEspera.Visible := aVisivel;
Self.AniIndicator1.Enabled := aVisivel;
if aVisivel then
Self.rctEspera.BringToFront
else
Self.rctEspera.SendToBack;
lytGeral.Enabled := not aVisivel;
Application.ProcessMessages;
end;
procedure TFormHerancaCadastro.FormCreate(Sender: TObject);
begin
Self.FIDUltimoRegistroPesquisa := -1;
tcPrincipal.TabPosition := TTabPosition.None;
tbPesquisa.Visible := False;
Self.tcPrincipal.ActiveTab := tabPesquisa;
if cdsPesquisa.FieldCount > 0 then
cdsPesquisa.CreateDataSet;
if cdsDados.FieldCount > 0 then
cdsDados.CreateDataSet;
end;
procedure TFormHerancaCadastro.FormKeyUp(Sender: TObject; var Key: Word;
var KeyChar: Char; Shift: TShiftState);
begin
if Key = vkHardwareBack then
begin
if tcPrincipal.ActiveTab = tabPesquisa then
btnRetornarClick(Sender)
else
btnRetornarDadosClick(Sender);
end;
end;
procedure TFormHerancaCadastro.ltvPesquisaItemClick(const Sender: TObject;
const AItem: TListViewItem);
begin
MudaTab(tabDados, Sender);
end;
procedure TFormHerancaCadastro.MudaTab(aTab: TTabItem; Sender: TObject);
begin
if tcPrincipal.ActiveTab = aTab then
Exit;
if aTab = tabDados then
tcDados.ActiveTab := tabDadosGeral;
ChangeTabPrincipal.Tab := aTab;
ChangeTabPrincipal.Execute;
end;
procedure TFormHerancaCadastro.Pesquisa;
begin
AntesDePesquisar;
end;
procedure TFormHerancaCadastro.SetPesquisando(const Value: Boolean);
begin
FPesquisando := Value;
end;
end.
|
{*******************************************************************************
Copyright (C) Christian Ulrich info@cu-tec.de
This source 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 commercial alternative
contact us for more information
This code 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.
A copy of the GNU General Public License is available on the World Wide Web
at <http://www.gnu.org/copyleft/gpl.html>. You can also obtain it by writing
to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA.
Created 01.06.2006
*******************************************************************************}
unit uZeosDBDM;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, db, ZConnection, ZSqlMetadata,
ZAbstractRODataset, ZDataset, ZSequence,ZAbstractConnection,
uModifiedDS,ZSqlMonitor,Utils,uBaseDatasetInterfaces,syncobjs,
uBaseDBInterface,uBaseDbClasses,ZCompatibility;
type
TUnprotectedDataSet = class(TDataSet);
{ TZeosDBDM }
TZeosDBDM = class(TBaseDBModule)
procedure FConnectionAfterConnect(Sender: TObject);
procedure FConnectionBeforeConnect(Sender: TObject);
procedure MonitorTrace(Sender: TObject; Event: TZLoggingEvent;
var LogTrace: Boolean);
private
FMainConnection : TZConnection;
FLimitAfterSelect : Boolean;
FLimitSTMT : string;
FDBTyp : string;
FProperties : string;
FPassword : string;
Monitor : TZSQLMonitor;
function GetConnection: TComponent;override;
function DBExists : Boolean;
protected
Sequence : TZSequence;
function GetSyncOffset: Integer;override;
procedure SetSyncOffset(const AValue: Integer);override;
function GetLimitAfterSelect: Boolean;override;
function GetLimitSTMT: string;override;
public
constructor Create(AOwner : TComponent);override;
destructor Destroy;override;
function SetProperties(aProp : string;Connection : TComponent = nil) : Boolean;override;
function CreateDBFromProperties(aProp: string): Boolean; override;
function IsSQLDB : Boolean;override;
function GetNewDataSet(aTable : TBaseDBDataSet;aConnection : TComponent = nil;MasterData : TDataSet = nil;aTables : string = '') : TDataSet;override;
function GetNewDataSet(aSQL : string;aConnection : TComponent = nil;MasterData : TDataSet = nil;aOrigtable : TBaseDBDataSet = nil) : TDataSet;override;
procedure DestroyDataSet(DataSet : TDataSet);override;
function Ping(aConnection : TComponent) : Boolean;override;
function DateToFilter(aValue : TDateTime) : string;override;
function DateTimeToFilter(aValue : TDateTime) : string;override;
function GetUniID(aConnection : TComponent = nil;Generator : string = 'GEN_SQL_ID';AutoInc : Boolean = True) : Variant;override;
procedure StreamToBlobField(Stream : TStream;DataSet : TDataSet;Fieldname : string);override;
function BlobFieldStream(DataSet: TDataSet; Fieldname: string): TStream;
override;
function GetErrorNum(e: EDatabaseError): Integer; override;
procedure DeleteExpiredSessions;override;
function GetNewConnection: TComponent;override;
function QuoteField(aField: string): string; override;
function QuoteValue(aField: string): string; override;
procedure Disconnect(aConnection : TComponent);override;
function StartTransaction(aConnection : TComponent;ForceTransaction : Boolean = False): Boolean;override;
function CommitTransaction(aConnection : TComponent): Boolean;override;
function RollbackTransaction(aConnection : TComponent): Boolean;override;
function IsTransactionActive(aConnection : TComponent): Boolean;override;
function TableExists(aTableName : string;aConnection : TComponent = nil;AllowLowercase: Boolean = False) : Boolean;override;
function TriggerExists(aTriggerName: string; aConnection: TComponent=nil;
AllowLowercase: Boolean=False): Boolean; override;
function GetDBType: string; override;
function GetDBLayerType : string;override;
function CreateTrigger(aTriggerName: string; aTableName: string;
aUpdateOn: string; aSQL: string;aField : string = ''; aConnection: TComponent=nil): Boolean;
override;
function DropTable(aTableName : string) : Boolean;override;
function FieldToSQL(aName : string;aType : TFieldType;aSize : Integer;aRequired : Boolean) : string;
function GetColumns(TableName : string) : TStrings;override;
end;
{ TZeosDBDataSet }
TZeosDBDataSet = class(TZQuery,IBaseDBFilter,IBaseManageDB,IBaseSubDatasets,IBaseModifiedDS)
procedure TDateTimeFieldGetText(Sender: TField; var aText: string;
DisplayText: Boolean);
private
FFirstOpen : Boolean;
FSubDataSets : Tlist;
FFields : string;
FFilter,FBaseFilter,FIntFilter : string;
FLimit : Integer;
FMDS: TDataSource;
FSortDirection : TSortDirection;
FSortFields : string;
FTableNames : string;
FDefaultTableName : string;
FManagedFieldDefs : TFieldDefs;
FManagedIndexDefs : TIndexDefs;
FOrigTable : TBaseDBDataSet;
FUsePermissions : Boolean;
FTableCaption : string;
FDistinct : Boolean;
DoCheck: Boolean;
FUpStdFields : Boolean;
FUpChangedBy : Boolean;
FBaseSortFields : string;
FBaseSorting : string;
FBaseSortDirection : TSortDirection;
FUseBaseSorting : Boolean;
FUseIntegrity : Boolean;
FChangeUni : Boolean;
FSQL,FIntSQL : string;
FParams : TStringList;
FHasNewID : Boolean;
procedure SetNewIDIfNull;
function BuildSQL : string;
function IndexExists(IndexName : string) : Boolean;
procedure WaitForLostConnection;
procedure DoUpdateSQL;
protected
//Internal DataSet Methods that needs to be changed
procedure InternalOpen; override;
procedure InternalRefresh; override;
procedure InternalPost; override;
procedure DoAfterInsert; override;
procedure DoBeforePost; override;
procedure DoBeforeInsert; override;
procedure DoBeforeEdit; override;
procedure SetFieldData(Field: TField; Buffer: Pointer); override;
procedure DoBeforeDelete; override;
procedure DoAfterDelete; override;
procedure DoAfterScroll; override;
procedure DoBeforeCancel; override;
//IBaseDBFilter
function GetFields: string;
function GetBaseFilter: string;
function GetLimit: Integer;
function GetSortDirection: TSortDirection;
function GetSortFields: string;
function GetLocalSortFields : string;
function GetBaseSortFields: string;
function GetSortLocal: Boolean;
procedure SetFields(const AValue: string);
function GetFilter: string;
procedure SetFilter(const AValue: string);
procedure SetBaseFilter(const AValue: string);
function GetSQL: string;
procedure SetSQL(const AValue: string);
procedure Setlimit(const AValue: Integer);
procedure SetSortDirection(const AValue: TSortDirection);
procedure SetSortFields(const AValue: string);
procedure SetLocalSortFields(const AValue : string);
procedure SetBaseSortFields(const AValue: string);
procedure SetSortLocal(const AValue: Boolean);
function GetFilterTables: string;
procedure SetFilterTables(const AValue: string);
function GetUsePermissions: Boolean;
procedure SetUsePermisions(const AValue: Boolean);
function GetDistinct: Boolean;
procedure SetDistinct(const AValue: Boolean);
function GetBaseSorting: string;
procedure SetBaseSorting(AValue: string);
function GetBaseSortDirection: TSortDirection;
procedure SetBaseSortDirection(AValue: TSortDirection);
function GetUseBaseSorting: Boolean;
procedure SetUseBaseSorting(AValue: Boolean);
function GetfetchRows: Integer;
procedure SetfetchRows(AValue: Integer);
//IBaseManageDB
function GetManagedFieldDefs: TFieldDefs;
function GetManagedIndexDefs: TIndexDefs;
function GetTableName: string;
procedure SetTableName(const AValue: string);
function CreateTable : Boolean;
function CheckTable : Boolean;
function AlterTable : Boolean;
function GetConnection: TComponent;
function GetTableCaption: string;
procedure SetTableCaption(const AValue: string);
function GetUpStdFields: Boolean;
procedure SetUpStdFields(AValue: Boolean);
function GetUpChangedBy: Boolean;
procedure SetUpChangedBy(AValue: Boolean);
function GetUseIntegrity: Boolean;
procedure SetUseIntegrity(AValue: Boolean);
function GetAsReadonly: Boolean;
procedure SetAsReadonly(AValue: Boolean);
//IBaseSubDataSets
function GetSubDataSet(aName : string): TComponent;
procedure RegisterSubDataSet(aDataSet : TComponent);
function GetCount : Integer;
function GetSubDataSetIdx(aIdx : Integer): TComponent;
//IBaseModifiedDS
function IsChanged: Boolean;
public
constructor Create(AOwner : TComponent);override;
destructor Destroy;override;
property MasterDataSource : TDataSource read FMDS write FMDS;
property DefaultTableName : string read FDefaultTableName;
procedure DoExecSQL;
function NumRowsAffected: Integer;
end;
implementation
uses ZDbcIntfs,uBaseApplication,uEncrypt;
resourcestring
strUnknownDbType = 'Unbekannter Datenbanktyp';
strDatabaseConnectionLost = 'Die Datenbankverbindung wurde verlohren !';
procedure TZeosDBDataSet.TDateTimeFieldGetText(Sender: TField;
var aText: string; DisplayText: Boolean);
begin
if not Sender.IsNull then
begin
if trunc(Sender.AsDateTime)=Sender.AsDateTime then
aText := FormatDateTime(ShortDateFormat,Sender.AsDateTime)
else
aText := FormatDateTime(ShortDateFormat+' '+ShortTimeFormat,Sender.AsDateTime);
end;
end;
procedure TZeosDBDataSet.SetNewIDIfNull;
begin
if (FieldDefs.IndexOf('AUTO_ID') = -1) and (FieldDefs.IndexOf('SQL_ID') > -1) and FieldByName('SQL_ID').IsNull then
begin
FieldByName('SQL_ID').AsVariant:=TBaseDBModule(Self.Owner).GetUniID(Connection);
FHasNewID:=True;
end
else if (FieldDefs.IndexOf('SQL_ID') = -1) and (FieldDefs.IndexOf('AUTO_ID') > -1) and FieldByName('AUTO_ID').IsNull then
begin
FieldByName('AUTO_ID').AsVariant:=TBaseDBModule(Self.Owner).GetUniID(Connection,'GEN_AUTO_ID');
FHasNewID:=True;
end;
end;
function TZeosDBDataSet.BuildSQL : string;
function BuildJoins : string;
var
aDS : string;
tmp: String;
begin
if not (pos(',',FTableNames) > 0) then
begin
Result := FTableNames;
if Result = '' then
Result := FDefaultTableName;
Result := TBaseDBModule(Owner).QuoteField(Result);
exit;
end;
tmp := FTableNames+',';
Result := copy(FTableNames,0,pos(',',FTableNames)-1);
aDS := Result;
tmp := copy(tmp,pos(',',tmp)+1,length(tmp));
while pos(',',tmp) > 0 do
begin
Result := Result+ ' inner join '+TBaseDBModule(Owner).QuoteField(copy(tmp,0,pos(',',tmp)-1))+' on '+TBaseDBModule(Owner).QuoteField(copy(tmp,0,pos(',',tmp)-1))+'.REF_ID='+aDS+'.SQL_ID';
aDS := TBaseDBModule(Owner).QuoteField(copy(tmp,0,pos(',',tmp)-1));
tmp := copy(tmp,pos(',',tmp)+1,length(tmp));
end;
end;
var
aFilter: String;
aRefField: String;
tmp: String;
SResult: String;
PJ: String = '';
PW: String = '';
procedure BuildSResult;
begin
SResult := '';
if pos(',',TZeosDBDM(Owner).QuoteField(FSortFields)) = 0 then
begin
sResult += TZeosDBDM(Owner).QuoteField(FDefaultTableName)+'.'+TZeosDBDM(Owner).QuoteField(FSortFields);
if FSortDirection = sdAscending then
sResult += ' ASC'
else if FSortDirection = sdDescending then
sResult += ' DESC'
else
begin
if FBaseSortDirection = sdAscending then
sResult += ' ASC'
else if FBaseSortDirection = sdDescending then
sResult += ' DESC'
end;
end
else
begin
tmp := FSortFields;
while pos(',',tmp) > 0 do
begin
sResult += TZeosDBDM(Owner).QuoteField(FDefaultTableName)+'.'+TZeosDBDM(Owner).QuoteField(copy(tmp,0,pos(',',tmp)-1));
tmp := copy(tmp,pos(',',tmp)+1,length(tmp));
if FSortDirection = sdAscending then
sResult += ' ASC'
else
sResult += ' DESC';
if trim(tmp) > '' then
sResult+=',';
end;
if tmp <> '' then
begin
sResult += TZeosDBDM(Owner).QuoteField(FDefaultTableName)+'.'+TZeosDBDM(Owner).QuoteField(tmp);
if FSortDirection = sdAscending then
sResult += ' ASC'
else
sResult += ' DESC';
end;
end;
end;
begin
if FSQL <> '' then
begin
BuildSResult;
if (FManagedFieldDefs.IndexOf('AUTO_ID') = -1) and (TZeosDBDM(Owner).UsersFilter <> '') and FUsePermissions then
begin
PJ := ' LEFT JOIN '+TZeosDBDM(Owner).QuoteField('PERMISSIONS')+' ON ('+TZeosDBDM(Owner).QuoteField('PERMISSIONS')+'.'+TZeosDBDM(Owner).QuoteField('REF_ID_ID')+'='+TZeosDBDM(Owner).QuoteField(FDefaultTableName)+'.'+TZeosDBDM(Owner).QuoteField('SQL_ID')+')';
PW := ' AND ('+aFilter+') AND (('+TZeosDBDM(Owner).UsersFilter+') OR '+TZeosDBDM(Owner).QuoteField('PERMISSIONS')+'.'+TZeosDBDM(Owner).QuoteField('USER')+' is NULL)';
end
else if (FManagedFieldDefs.IndexOf('AUTO_ID') = -1) and FUsePermissions then
begin
PJ := ' LEFT JOIN '+TZeosDBDM(Owner).QuoteField('PERMISSIONS')+' ON ('+TZeosDBDM(Owner).QuoteField('PERMISSIONS')+'.'+TZeosDBDM(Owner).QuoteField('REF_ID_ID')+'='+TZeosDBDM(Owner).QuoteField(FDefaultTableName)+'.'+TZeosDBDM(Owner).QuoteField('SQL_ID')+')';
PW := ' AND ('+TZeosDBDM(Owner).QuoteField('PERMISSIONS')+'.'+TZeosDBDM(Owner).QuoteField('USER')+' is NULL)'
end;
PW := StringReplace(PW,'AND ()','',[rfReplaceAll]);
Result := StringReplace(StringReplace(StringReplace(FSQL,'@PERMISSIONJOIN@',PJ,[]),'@PERMISSIONWHERE@',PW,[]),'@DEFAULTORDER@',SResult,[]);
end
else if Assigned(FOrigTable) then
begin
Result := 'SELECT ';
if FDistinct then
Result := Result+'DISTINCT ';
if TZeosDBDM(Owner).LimitAfterSelect and ((FLimit > 0)) then
Result += Format(TZeosDBDM(Owner).LimitSTMT,[':Limit'])+' ';
if FFields = '' then
Result += TZeosDBDM(Owner).QuoteField(FDefaultTableName)+'.'+'* '
else
Result += FFields+' ';
aFilter := FIntFilter;
if (FBaseFilter <> '') and (aFilter <> '') then
aFilter := '('+fBaseFilter+') and ('+aFilter+')'
else if (FBaseFilter <> '') then
aFilter := '('+fBaseFilter+')';
if Assigned(DataSource) then
begin
with Self as IBaseManageDb do
begin
if ManagedFieldDefs.IndexOf('AUTO_ID') > -1 then
aRefField := 'AUTO_ID'
else
aRefField := 'SQL_ID';
end;
if aFilter <> '' then
aFilter := '('+aFilter+') and ('+TZeosDBDM(Owner).QuoteField('REF_ID')+'=:'+TZeosDBDM(Owner).QuoteField(aRefField)+')'
else
aFilter := TZeosDBDM(Owner).QuoteField('REF_ID')+'=:'+TZeosDBDM(Owner).QuoteField(aRefField);
end;
if (FManagedFieldDefs.IndexOf('AUTO_ID') = -1) and (TZeosDBDM(Owner).UsersFilter <> '') and FUsePermissions then
Result += 'FROM '+BuildJoins+' LEFT JOIN '+TZeosDBDM(Owner).QuoteField('PERMISSIONS')+' ON ('+TZeosDBDM(Owner).QuoteField('PERMISSIONS')+'.'+TZeosDBDM(Owner).QuoteField('REF_ID_ID')+'='+TZeosDBDM(Owner).QuoteField(FDefaultTableName)+'.'+TZeosDBDM(Owner).QuoteField('SQL_ID')+') WHERE ('+aFilter+') AND (('+TZeosDBDM(Owner).UsersFilter+') OR '+TZeosDBDM(Owner).QuoteField('PERMISSIONS')+'.'+TZeosDBDM(Owner).QuoteField('USER')+' is NULL)'
else if (FManagedFieldDefs.IndexOf('AUTO_ID') = -1) and FUsePermissions then
Result += 'FROM '+BuildJoins+' LEFT JOIN '+TZeosDBDM(Owner).QuoteField('PERMISSIONS')+' ON ('+TZeosDBDM(Owner).QuoteField('PERMISSIONS')+'.'+TZeosDBDM(Owner).QuoteField('REF_ID_ID')+'='+TZeosDBDM(Owner).QuoteField(FDefaultTableName)+'.'+TZeosDBDM(Owner).QuoteField('SQL_ID')+') WHERE ('+aFilter+') AND ('+TZeosDBDM(Owner).QuoteField('PERMISSIONS')+'.'+TZeosDBDM(Owner).QuoteField('USER')+' is NULL)'
else
Result += 'FROM '+BuildJoins+' WHERE ('+aFilter+')';
Result := StringReplace(Result,' WHERE () AND ','WHERE ',[]);
Result := StringReplace(Result,' WHERE ()','',[]);
if (FSortFields <> '') and ((FSortDirection <> sdIgnored) or (FBaseSortDirection <> sdIgnored)) then
begin
BuildSResult;
if FUseBaseSorting then
Result += ' ORDER BY '+Format(FBaseSorting,[sResult])
else
Result += ' ORDER BY '+sResult;
end;
if (FLimit > 0) and (not TZeosDBDM(Owner).LimitAfterSelect) then
Result += ' '+Format(TZeosDBDM(Owner).LimitSTMT,[':Limit']);
end
else
Result := SQL.text;
if Assigned(FOrigTable) then TBaseDBModule(ForigTable.DataModule).LastStatement := Result;
end;
function TZeosDBDataSet.IndexExists(IndexName: string): Boolean;
var
Metadata: TZSQLMetadata;
CustomQuery: TZQuery;
begin
CustomQuery := TZQuery.Create(Self);
CustomQuery.Connection := Connection;
if (copy(TZConnection(TBaseDBModule(Owner).MainConnection).Protocol,0,8) = 'firebird')
or (copy(TZConnection(TBaseDBModule(Owner).MainConnection).Protocol,0,9) = 'interbase') then
begin
CustomQuery.SQL.Text := 'select rdb$index_name from rdb$indices where rdb$index_name='+TZeosDBDM(Owner).QuoteValue(indexname);
CustomQuery.Open;
Result := CustomQuery.RecordCount > 0;
CustomQuery.Close;
end
else if (copy(TZConnection(TBaseDBModule(Owner).MainConnection).Protocol,0,6) = 'sqlite') then
begin
CustomQuery.SQL.Text := 'select name from SQLITE_MASTER where "TYPE"=''index'' and NAME='+TZeosDBDM(Owner).QuoteValue(indexname);
CustomQuery.Open;
Result := CustomQuery.RecordCount > 0;
CustomQuery.Close;
end
else if (copy(TZConnection(TBaseDBModule(Owner).MainConnection).Protocol,0,5) = 'mssql') then
begin
CustomQuery.SQL.Text := 'select name from dbo.sysindexes where NAME='+TZeosDBDM(Owner).QuoteValue(indexname);
CustomQuery.Open;
Result := CustomQuery.RecordCount > 0;
CustomQuery.Close;
end
else if (copy(TZConnection(TBaseDBModule(Owner).MainConnection).Protocol,0,8) = 'postgres') then
begin
CustomQuery.SQL.Text := 'select * from pg_class where relname='+TZeosDBDM(Owner).QuoteValue(indexname);
CustomQuery.Open;
Result := CustomQuery.RecordCount > 0;
CustomQuery.Close;
end
else
begin
Metadata := TZSQLMetaData.Create(TZConnection(TBaseDBModule(Owner).MainConnection));
MetaData.Connection := Connection;
MetaData.MetadataType:=mdIndexInfo;
Metadata.Catalog:=TZConnection(TBaseDBModule(Owner).MainConnection).Catalog;
Metadata.TableName:=copy(indexname,0,pos('_',indexname)-1);
MetaData.Filter:='INDEX_NAME='+TZeosDBDM(Owner).QuoteValue(indexname);
MetaData.Filtered:=True;
MetaData.Active:=True;
Result := MetaData.RecordCount > 0;
MetaData.Free;
end;
CustomQuery.Free;
end;
procedure TZeosDBDataSet.WaitForLostConnection;
var
aConnThere: Boolean;
begin
if not TZeosDBDM(Owner).Ping(Connection) then
begin
if Assigned(TZeosDBDM(Owner).OnConnectionLost) then
TZeosDBDM(Owner).OnConnectionLost(TZeosDBDM(Owner));
aConnThere := False;
while not aConnThere do
begin
if GetCurrentThreadID=MainThreadID then
begin
if Assigned(TZeosDBDM(Owner).OnDisconnectKeepAlive) then
TZeosDBDM(Owner).OnDisconnectKeepAlive(TZeosDBDM(Owner));
end;
try
if TZeosDBDM(Owner).Ping(Connection) then aConnThere := True
else sleep(200);
except
sleep(200);
end;
end;
if Assigned(TZeosDBDM(Owner).OnConnect) then
TZeosDBDM(Owner).OnConnect(TZeosDBDM(Owner));
end;
end;
procedure TZeosDBDataSet.DoUpdateSQL;
begin
Close;
if FSQL<>'' then
SetSQL(FSQL)
else
begin
SQL.Text:='';
FIntSQL := '';
SetFilter(FFilter);
end;
end;
function TZeosDBDataSet.CreateTable : Boolean;
var
aSQL: String;
i: Integer;
bConnection: TZAbstractConnection = nil;
// bConnection: TZConnection = nil;
GeneralQuery: TZQuery;
RestartTransaction: Boolean = False;
begin
Result := False;
with TBaseDBModule(Owner) do
begin
if Assigned(FOrigTable) and (FFields = '') then
begin
if FFields = '' then
DoCheck := True;
bConnection := Connection;
Result := True;
aSQL := 'CREATE TABLE '+QuoteField(Uppercase(Self.FDefaultTableName))+' ('+lineending;
if FUpStdFields then
begin
if FManagedFieldDefs.IndexOf('AUTO_ID') = -1 then
aSQL += TZeosDBDM(Self.Owner).FieldToSQL('SQL_ID',ftLargeInt,0,True)+' PRIMARY KEY,'+lineending
else
begin
aSQL += TZeosDBDM(Self.Owner).FieldToSQL('AUTO_ID',ftLargeInt,0,True)+' PRIMARY KEY,'+lineending;
end;
end;
if Assigned(MasterSource) then
begin
aSQL += TZeosDBDM(Self.Owner).FieldToSQL('REF_ID',ftLargeInt,0,True);
if FUseIntegrity then
begin
with MasterSource.DataSet as IBaseManageDB do
begin
if ManagedFieldDefs.IndexOf('AUTO_ID') = -1 then
aSQL += ' REFERENCES '+QuoteField(TZeosDBDataSet(MasterSource.DataSet).DefaultTableName)+'('+QuoteField('SQL_ID')+') ON DELETE CASCADE'
else
aSQL += ' REFERENCES '+QuoteField(TZeosDBDataSet(MasterSource.DataSet).DefaultTableName)+'('+QuoteField('AUTO_ID')+') ON DELETE CASCADE';
end;
if (copy(TZConnection(TBaseDBModule(Self.Owner).MainConnection).Protocol,0,6) = 'sqlite') then
aSQL += ' DEFERRABLE INITIALLY DEFERRED';
end;
aSQL+=','+lineending;
end;
for i := 0 to FManagedFieldDefs.Count-1 do
if FManagedFieldDefs[i].Name <> 'AUTO_ID' then
aSQL += TZeosDBDM(Self.Owner).FieldToSQL(FManagedFieldDefs[i].Name,FManagedFieldDefs[i].DataType,FManagedFieldDefs[i].Size,FManagedFieldDefs[i].Required)+','+lineending;
if FUpStdFields then
aSQL += TZeosDBDM(Self.Owner).FieldToSQL('TIMESTAMPD',ftDateTime,0,True)+');'
else
aSql := copy(aSQL,0,length(aSQL)-2)+');';
try
try
GeneralQuery := TZQuery.Create(Self);
GeneralQuery.Connection := bConnection;
GeneralQuery.SQL.Text := aSQL;
GeneralQuery.ExecSQL;
if bConnection.InTransaction then
begin
TZeosDBDM(Self.Owner).CommitTransaction(bConnection);
TZeosDBDM(Self.Owner).StartTransaction(bConnection);
end;
except
end;
finally
GeneralQuery.Destroy;
end;
end;
end;
Close;
end;
function TZeosDBDataSet.CheckTable: Boolean;
var
i: Integer;
begin
Result := False;
with TBaseDBModule(Owner) do
begin
if DoCheck or (FFields = '') then
begin
for i := 0 to FManagedFieldDefs.Count-1 do
begin
if (FieldDefs.IndexOf(FManagedFieldDefs[i].Name) = -1) and (FManagedFieldDefs[i].Name <> 'AUTO_ID') then
begin
Result := True;
end
else if FieldDefs.IndexOf(FManagedFieldDefs[i].Name)>-1 then
begin
if FieldByName(FManagedFieldDefs[i].Name).Size<FManagedFieldDefs[i].Size then
Result := True;
end;
end;
if Assigned(FManagedIndexDefs) then
for i := 0 to FManagedIndexDefs.Count-1 do //Primary key
if (not IndexExists(Uppercase(Self.DefaultTableName+'_'+FManagedIndexDefs.Items[i].Name))) and (FManagedIndexDefs.Items[i].Name <>'SQL_ID') then
begin
Result := True;
end;
end;
if not Result then
begin
TBaseDBModule(Self.Owner).UpdateTableVersion(Self.FDefaultTableName);
end;
end;
end;
function TZeosDBDataSet.AlterTable: Boolean;
var
i: Integer;
aSQL: String;
GeneralQuery: TZQuery;
Changed: Boolean = False;
aConnection : TZAbstractConnection;
begin
Result := True;
with BaseApplication as IBaseApplication do
Debug('AlterTable:'+FDefaultTableName);
try
if FFields <> '' then exit;
with TBaseDBModule(Owner) do
begin
for i := 0 to FManagedFieldDefs.Count-1 do
if (FieldDefs.IndexOf(FManagedFieldDefs[i].Name) = -1) and (FManagedFieldDefs[i].Name <> 'AUTO_ID') then
begin
aSQL := 'ALTER TABLE '+QuoteField(FDefaultTableName)+' ADD '+TZeosDBDM(Self.Owner).FieldToSQL(FManagedFieldDefs[i].Name,FManagedFieldDefs[i].DataType,FManagedFieldDefs[i].Size,False)+';';
with BaseApplication as IBaseApplication do
Debug(aSQL);
aConnection := Connection;
GeneralQuery := TZQuery.Create(Self);
try
GeneralQuery.Connection := aConnection;
GeneralQuery.SQL.Text := aSQL;
GeneralQuery.ExecSQL;
finally
GeneralQuery.Free;
end;
Changed := True;
Result := True;
end
else if FieldDefs.IndexOf(FManagedFieldDefs[i].Name)>-1 then
begin
if FieldByName(FManagedFieldDefs[i].Name).Size<FManagedFieldDefs[i].Size then
begin
if (copy(Connection.Protocol,0,8) = 'postgres') then
aSQL := 'ALTER TABLE '+QuoteField(FDefaultTableName)+' ALTER COLUMN '+QuoteField(FManagedFieldDefs[i].Name)+' TYPE '+TZeosDBDM(Self.Owner).FieldToSQL('',FManagedFieldDefs[i].DataType,FManagedFieldDefs[i].Size,False)+';'
else
aSQL := 'ALTER TABLE '+QuoteField(FDefaultTableName)+' ALTER COLUMN '+QuoteField(FManagedFieldDefs[i].Name)+' '+TZeosDBDM(Self.Owner).FieldToSQL('',FManagedFieldDefs[i].DataType,FManagedFieldDefs[i].Size,False)+';';
with BaseApplication as IBaseApplication do
Debug(aSQL);
aConnection := Connection;
GeneralQuery := TZQuery.Create(Self);
try
GeneralQuery.Connection := aConnection;
GeneralQuery.SQL.Text := aSQL;
GeneralQuery.ExecSQL;
finally
GeneralQuery.Free;
end;
Changed := True;
Result := True;
end;
end;
aSQL := '';
if Assigned(FManagedIndexDefs) then
for i := 0 to FManagedIndexDefs.Count-1 do //Primary key
if (not IndexExists(Uppercase(Self.DefaultTableName+'_'+FManagedIndexDefs.Items[i].Name))) and (FManagedIndexDefs.Items[i].Name <>'SQL_ID') then
begin
aSQL := aSQL+'CREATE ';
if ixUnique in FManagedIndexDefs.Items[i].Options then
aSQL := aSQL+'UNIQUE ';
aSQL := aSQL+'INDEX '+QuoteField(Uppercase(Self.DefaultTableName+'_'+FManagedIndexDefs.Items[i].Name))+' ON '+QuoteField(Self.DefaultTableName)+' ('+QuoteField(StringReplace(FManagedIndexDefs.Items[i].Fields,';',QuoteField(','),[rfReplaceAll]))+');'+lineending;
with BaseApplication as IBaseApplication do
Debug(aSQL);
if aSQL <> '' then
begin
try
GeneralQuery := TZQuery.Create(Self);
GeneralQuery.Connection := Connection;
GeneralQuery.SQL.Text := aSQL;
GeneralQuery.ExecSQL;
finally
GeneralQuery.Free;
aSQL := '';
end;
end;
Result := True;
end;
end;
except
Result := False;
end;
if Result and Changed and (Self.FDefaultTableName<>'TABLEVERSIONS') then
begin
Connection.DbcConnection.GetMetadata.ClearCache;
{
with BaseApplication as IBaseApplication do
Info('Table '+Self.FDefaultTableName+' was altered reconecting...');
Connection.Disconnect;
Connection.Connect;
}
end;
if Changed then
TBaseDBModule(Self.Owner).UpdateTableVersion(Self.FDefaultTableName);
end;
procedure TZeosDBDataSet.InternalOpen;
var
a: Integer;
begin
if Connection.Protocol='mysql' then
Properties.Values['ValidateUpdateCount'] := 'False';
if Assigned(FOrigTable) and Assigned(ForigTable.DataModule) then
TBaseDBModule(ForigTable.DataModule).LastTime := GetTicks;
if TZeosDBDM(Owner).IgnoreOpenRequests then exit;
if FFirstOpen then
begin
FIntSQL := BuildSQL;
SQL.Text := FIntSQL;
if (FLimit>0) and Assigned(Params.FindParam('Limit')) and ((copy(Connection.Protocol,0,8)<>'postgres') or (FLimit>90)) then
ParamByName('Limit').AsInteger:=FLimit;
FFirstOpen:=False;
end;
if Assigned(FOrigTable) and Assigned(ForigTable.DataModule) then
TBaseDBModule(ForigTable.DataModule).CriticalSection.Enter;
try
try
inherited InternalOpen;
except
InternalClose;
if TZeosDBDM(Owner).Ping(Connection) then
inherited InternalOpen
else
begin
WaitForLostConnection;
inherited InternalOpen;
end;
end;
try
if Assigned(FOrigTable) and Assigned(ForigTable.DataModule) then
begin
FOrigTable.SetDisplayLabels(Self);
if FOrigTable.UpdateFloatFields then
begin
DisableControls;
for a := 0 to Fields.Count -1 do
begin
if Fields[a] is TFloatField then
begin
if Fields[a].Name = 'WEIGHT' then
begin
TFloatField(Fields[a]).DisplayFormat := '#,##0.000##';
TFloatField(Fields[a]).EditFormat := '0.000##';
TFloatField(Fields[a]).Precision:=5;
end
else
begin
TFloatField(Fields[a]).DisplayFormat := '#,##0.00##';
TFloatField(Fields[a]).EditFormat := '0.00##';
TFloatField(Fields[a]).Precision:=5;
end;
end;
if (Fields[a] is TDateTimeField)
then
begin
TDateTimeField(Fields[a]).DisplayFormat := ShortDateFormat+' '+ShortTimeFormat;
TDateTimeField(Fields[a]).OnGetText:=@TDateTimeFieldGetText;
end;
end;
EnableControls;
end;
end;
except
begin
FOrigTable:=nil;
raise;
end;
end;
finally
if Assigned(FOrigTable) and Assigned(ForigTable.DataModule) then
TBaseDBModule(ForigTable.DataModule).CriticalSection.Leave;
end;
end;
procedure TZeosDBDataSet.InternalRefresh;
begin
if TZeosDBDM(Owner).IgnoreOpenRequests then exit;
if Assigned(FOrigTable) and Assigned(ForigTable.DataModule) then
TBaseDBModule(ForigTable.DataModule).CriticalSection.Enter;
try
try
inherited InternalRefresh;
except
InternalClose;
if not Active then
begin
if TZeosDBDM(Owner).Ping(Connection) then
InternalOpen
else
begin
WaitForLostConnection;
InternalOpen;
end;
end;
end;
finally
if Assigned(FOrigTable) and Assigned(ForigTable.DataModule) then
TBaseDBModule(ForigTable.DataModule).CriticalSection.Leave;
end;
end;
procedure TZeosDBDataSet.InternalPost;
var
ok : boolean = false;
rc : Integer = 0;
function CheckID : Boolean;
var
aDs: TDataSet;
begin
if (FieldDefs.IndexOf('AUTO_ID') = -1) and (FieldDefs.IndexOf('SQL_ID') > -1) then
begin
aDs := TBaseDBModule(FOrigTable.DataModule).GetNewDataSet('select '+TBaseDBModule(FOrigTable.DataModule).QuoteField('SQL_ID')+' from '+TBaseDBModule(FOrigTable.DataModule).QuoteField(DefaultTableName)+' where '+TBaseDBModule(FOrigTable.DataModule).QuoteField('SQL_ID')+'='+TBaseDBModule(FOrigTable.DataModule).QuoteValue(FieldByName('SQL_ID').AsVariant));
end
else if (FieldDefs.IndexOf('SQL_ID') = -1) and (FieldDefs.IndexOf('AUTO_ID') > -1) then
begin
aDs := TBaseDBModule(FOrigTable.DataModule).GetNewDataSet('select '+TBaseDBModule(FOrigTable.DataModule).QuoteField('AUTO_ID')+' from '+TBaseDBModule(FOrigTable.DataModule).QuoteField(DefaultTableName)+' where '+TBaseDBModule(FOrigTable.DataModule).QuoteField('AUTO_ID')+'='+TBaseDBModule(FOrigTable.DataModule).QuoteValue(FieldByName('AUTO_ID').AsVariant));
end;
aDs.Open;
Result := aDs.RecordCount>0;
aDs.Free;
end;
procedure CleanID;
begin
if (FieldDefs.IndexOf('AUTO_ID') = -1) and (FieldDefs.IndexOf('SQL_ID') > -1) then
begin
FieldByName('SQL_ID').AsVariant:=Null
end
else if (FieldDefs.IndexOf('SQL_ID') = -1) and (FieldDefs.IndexOf('AUTO_ID') > -1) then
begin
FieldByName('AUTO_ID').AsVariant:=Null;
end;
end;
begin
try
while not ok do
begin
ok := True;
try
inherited InternalPost;
except
begin
inc(rc);
ok := false;
if (FHasNewID and (rc<3)) then
begin
CleanID;
SetNewIDIfNull;
while CheckID do
begin
CleanID;
SetNewIDIfNull;
end;
end
else
begin
ok := true;
raise;
exit;
end;
end;
end;
end;
finally
end;
end;
procedure TZeosDBDataSet.DoAfterInsert;
begin
inherited DoAfterInsert;
if Assigned(FOrigTable) then
begin
FOrigTable.DisableChanges;
FOrigTable.FillDefaults(Self);
FOrigTable.EnableChanges;
end;
end;
procedure TZeosDBDataSet.DoBeforePost;
var
UserCode: String;
begin
inherited DoBeforePost;
if Assigned(Self.FOrigTable) then
Self.FOrigTable.DisableChanges;
FHasNewID:=False;
try
SetNewIDIfNull;
if FUpStdFields and Assigned(FOrigTable) {and (FOrigTable.Changed)} then
begin
if (FieldDefs.IndexOf('TIMESTAMPD') > -1) then
FieldByName('TIMESTAMPD').AsDateTime:=Now();
with BaseApplication as IBaseDBInterface do
begin
if Data.Users.DataSet.Active then
UserCode := Data.Users.IDCode.AsString
else UserCode := 'SYS';
if (FieldDefs.IndexOf('CREATEDBY') > -1) and (FieldByName('CREATEDBY').IsNull) then
FieldByName('CREATEDBY').AsString:=UserCode;
if FUpChangedBy and (FieldDefs.IndexOf('CHANGEDBY') > -1) then
FieldByName('CHANGEDBY').AsString:=UserCode;
end;
end;
if Assigned(DataSource) and (FieldDefs.IndexOf('REF_ID')>-1) and Assigned(FieldByName('REF_ID')) and FieldbyName('REF_ID').IsNull then
begin
if DataSource.DataSet.FieldDefs.IndexOf('AUTO_ID') > -1 then
FieldbyName('REF_ID').AsVariant:=DataSource.DataSet.FieldByName('AUTO_ID').AsVariant
else
FieldbyName('REF_ID').AsVariant:=DataSource.DataSet.FieldByName('SQL_ID').AsVariant;
end;
finally
if Assigned(Self.FOrigTable) then
Self.FOrigTable.EnableChanges;
end;
end;
procedure TZeosDBDataSet.DoBeforeInsert;
begin
if Assigned(DataSource) then
begin
if (DataSource.State <> dsInsert) and (DataSource.DataSet.RecordCount = 0) then
begin
DataSource.DataSet.Append;
end;
if (DataSource.DataSet.State = dsInsert) then
begin
DataSource.DataSet.Post;
DataSource.DataSet.Edit;
end;
end;
inherited DoBeforeInsert;
end;
procedure TZeosDBDataSet.DoBeforeEdit;
begin
inherited DoBeforeEdit;
end;
procedure TZeosDBDataSet.DoBeforeDelete;
begin
inherited DoBeforeDelete;
if (GetTableName='DELETEDITEMS')
or (GetTableName='TABLEVERSIONS')
then exit;
try
if Assigned(FOrigTable) and Assigned(FOrigTable.OnRemove) then FOrigTable.OnRemove(FOrigTable);
if GetUpStdFields = True then
TZeosDBDM(Owner).DeleteItem(FOrigTable);
except
end;
end;
procedure TZeosDBDataSet.DoAfterDelete;
begin
inherited DoAfterDelete;
if Assigned(FOrigTable) then
FOrigTable.Change;
end;
procedure TZeosDBDataSet.DoAfterScroll;
begin
inherited DoAfterScroll;
if Assigned(ForigTable) then
FOrigTable.UnChange;
end;
procedure TZeosDBDataSet.DoBeforeCancel;
begin
inherited DoBeforeCancel;
if State = dsInsert then
begin
if Assigned(FOrigTable) and Assigned(FOrigTable.OnRemove) then FOrigTable.OnRemove(FOrigTable);
end;
end;
function TZeosDBDataSet.GetFields: string;
begin
Result := FFields;
end;
function TZeosDBDataSet.GetFilter: string;
begin
Result := FFilter;
end;
function TZeosDBDataSet.GetBaseFilter: string;
begin
Result := FBaseFilter;
end;
function TZeosDBDataSet.GetLimit: Integer;
begin
Result := FLimit;
end;
function TZeosDBDataSet.GetSortDirection: TSortDirection;
begin
Result := FSortDirection;
end;
function TZeosDBDataSet.GetSortFields: string;
begin
Result := FSortFields;
end;
function TZeosDBDataSet.GetLocalSortFields: string;
begin
Result := SortedFields;
end;
function TZeosDBDataSet.GetBaseSortFields: string;
begin
Result := FBaseSortFields;
end;
function TZeosDBDataSet.GetSortLocal: Boolean;
begin
Result := SortType <> stIgnored;
end;
procedure TZeosDBDataSet.SetFields(const AValue: string);
begin
if FFields<>AValue then
begin
FFields := AValue;
DoUpdateSQL;
end;
end;
procedure TZeosDBDataSet.SetFilter(const AValue: string);
var
NewSQL: string;
i: Integer;
aPar: TParam;
begin
if (FFilter=AValue) and (SQL.text<>'') then
begin
if (AValue<>'') or (pos('where',lowercase(SQL.Text))=0) then
exit;
end;
TZeosDBDM(Owner).DecodeFilter(AValue,FParams,NewSQL);
Close;
FFilter := AValue;
if (FIntFilter<>NewSQL) or (SQL.Text='') then //Params and SQL has changed
begin
FSQL := '';
if TZeosDBDM(Owner).CheckForInjection(AValue) then exit;
FIntFilter:=NewSQL;
FIntSQL := '';
FIntSQL := BuildSQL;
Params.Clear;
SQL.text := FIntSQL;
end;
for i := 0 to FParams.Count-1 do
begin
if Assigned(Params.FindParam(FParams.Names[i])) then
begin
aPar := ParamByName(FParams.Names[i]);
aPar.AsString:=FParams.ValueFromIndex[i];
end;
end;
if (FLimit>0) and Assigned(Params.FindParam('Limit')) then
ParamByName('Limit').AsInteger:=FLimit;
end;
procedure TZeosDBDataSet.SetBaseFilter(const AValue: string);
begin
FBaseFilter := AValue;
DoUpdateSQL;
end;
function TZeosDBDataSet.GetSQL: string;
begin
Result := FSQL;
end;
procedure TZeosDBDataSet.SetSQL(const AValue: string);
var
NewSQL: string;
i: Integer;
aPar: TParam;
begin
if TZeosDBDM(Owner).CheckForInjection(AValue) then exit;
if AValue=FSQL then exit;
Close;
Params.Clear;
FParams.Clear;
FSQL := AValue;
FIntSQL := BuildSQL;
FFilter := '';
FIntFilter:='';
SQL.Text := FIntSQL;
{
TZeosDBDM(Owner).DecodeFilter(AValue,FParams,NewSQL);
Params.Clear;
FSQL := NewSQL;
FIntSQL := BuildSQL;
FFilter := '';
SQL.Text := FIntSQL;
for i := 0 to FParams.Count-1 do
begin
aPar := ParamByName(FParams.Names[i]);
aPar.AsString:=FParams.ValueFromIndex[i];
end;
}
if (FLimit>0) and Assigned(Params.FindParam('Limit')) then
ParamByName('Limit').AsInteger:=FLimit;
end;
procedure TZeosDBDataSet.Setlimit(const AValue: Integer);
begin
if FLimit = AValue then exit;
FLimit := AValue;
DoUpdateSQL;
end;
procedure TZeosDBDataSet.SetSortDirection(const AValue: TSortDirection);
begin
if (FSortDirection=AValue) and Active then exit;
FSortDirection := AValue;
if not GetSortLocal then
begin
DoUpdateSQL;
end;
end;
procedure TZeosDBDataSet.SetSortFields(const AValue: string);
begin
FSortFields := AValue;
end;
procedure TZeosDBDataSet.SetLocalSortFields(const AValue: string);
begin
SortedFields:=AValue;
end;
procedure TZeosDBDataSet.SetBaseSortFields(const AValue: string);
begin
FBaseSortFields := AValue;
end;
procedure TZeosDBDataSet.SetSortLocal(const AValue: Boolean);
begin
if AValue then
begin
if FSortDirection = sdAscending then
SortType := stAscending
else if FSortDirection = sdDescending then
SortType := stDescending
else
SortType := stIgnored;
end
else
SortType := stIgnored;
end;
function TZeosDBDataSet.GetFilterTables: string;
begin
Result := FTableNames;
end;
procedure TZeosDBDataSet.SetFilterTables(const AValue: string);
begin
if AValue = FTableNames then exit;
FTableNames := AValue;
DoUpdateSQL;
end;
function TZeosDBDataSet.GetUsePermissions: Boolean;
begin
Result := FUsePermissions;
end;
procedure TZeosDBDataSet.SetUsePermisions(const AValue: Boolean);
begin
if AValue = FUsePermissions then exit;
FUsePermissions := AValue;
DoUpdateSQL;
end;
function TZeosDBDataSet.GetDistinct: Boolean;
begin
Result := FDistinct;
end;
procedure TZeosDBDataSet.SetDistinct(const AValue: Boolean);
begin
if AValue = FDistinct then exit;
FDistinct := AValue;
DoUpdateSQL;
end;
function TZeosDBDataSet.GetBaseSorting: string;
begin
Result := FBaseSorting;
end;
procedure TZeosDBDataSet.SetBaseSorting(AValue: string);
begin
FBaseSorting := AValue;
end;
function TZeosDBDataSet.GetBaseSortDirection: TSortDirection;
begin
Result := FBaseSortDirection;
end;
procedure TZeosDBDataSet.SetBaseSortDirection(AValue: TSortDirection);
begin
FBaseSortDirection := AValue;
end;
function TZeosDBDataSet.GetUseBaseSorting: Boolean;
begin
Result := FUseBaseSorting;
end;
procedure TZeosDBDataSet.SetUseBaseSorting(AValue: Boolean);
begin
FUseBaseSorting := AValue;
DoUpdateSQL;
end;
function TZeosDBDataSet.GetfetchRows: Integer;
begin
result := FetchRow;
end;
procedure TZeosDBDataSet.SetfetchRows(AValue: Integer);
begin
FetchRow:=AValue;
end;
function TZeosDBDataSet.GetManagedFieldDefs: TFieldDefs;
begin
Result := FManagedFieldDefs;
end;
function TZeosDBDataSet.GetManagedIndexDefs: TIndexDefs;
begin
Result := FManagedIndexDefs;
end;
function TZeosDBDataSet.GetTableName: string;
begin
Result := FDefaultTableName;
end;
procedure TZeosDBDataSet.SetTableName(const AValue: string);
begin
FDefaultTableName := AValue;
end;
function TZeosDBDataSet.GetConnection: TComponent;
begin
Result := Connection;
end;
function TZeosDBDataSet.GetTableCaption: string;
begin
Result := FTableCaption;
end;
procedure TZeosDBDataSet.SetTableCaption(const AValue: string);
begin
FTableCaption := AValue;
end;
function TZeosDBDataSet.GetUpStdFields: Boolean;
begin
Result := FUpStdFields;
end;
procedure TZeosDBDataSet.SetUpStdFields(AValue: Boolean);
begin
FUpStdFields := AValue;
end;
function TZeosDBDataSet.GetUpChangedBy: Boolean;
begin
Result := FUpChangedBy;
end;
procedure TZeosDBDataSet.SetUpChangedBy(AValue: Boolean);
begin
FUpChangedBy:=AValue;
end;
function TZeosDBDataSet.GetUseIntegrity: Boolean;
begin
Result := FUseIntegrity;
end;
procedure TZeosDBDataSet.SetUseIntegrity(AValue: Boolean);
begin
FUseIntegrity:=AValue;
end;
function TZeosDBDataSet.GetAsReadonly: Boolean;
begin
result := Self.ReadOnly;
end;
procedure TZeosDBDataSet.SetAsReadonly(AValue: Boolean);
begin
Self.ReadOnly:=AValue;
end;
procedure TZeosDBDataSet.SetFieldData(Field: TField; Buffer: Pointer);
var
tmp: String;
begin
inherited;
if Assigned(FOrigTable) then
FOrigTable.Change;
end;
function TZeosDBDataSet.GetSubDataSet(aName: string): TComponent;
var
i: Integer;
begin
Result := nil;
for i := 0 to FSubDataSets.Count-1 do
with TBaseDBDataSet(FSubDataSets[i]) as IBaseManageDB do
if TableName = aName then
Result := TBaseDBDataSet(FSubDataSets[i]);
end;
procedure TZeosDBDataSet.RegisterSubDataSet(aDataSet: TComponent);
begin
FSubDataSets.Add(aDataSet);
end;
function TZeosDBDataSet.GetCount: Integer;
begin
Result := FSubDataSets.Count;
end;
function TZeosDBDataSet.GetSubDataSetIdx(aIdx: Integer): TComponent;
begin
Result := nil;
if aIdx < FSubDataSets.Count then
Result := TBaseDbDataSet(FSubDataSets[aIdx]);
end;
function TZeosDBDataSet.IsChanged: Boolean;
begin
Result := Modified;
if Assigned(FOrigTable) then
Result := ForigTable.Changed;
end;
constructor TZeosDBDataSet.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FFirstOpen:=True;
FSQL := '';
DoCheck := False;
fBaseSorting := '%s';
FChangeUni:=False;
FUseBaseSorting:=False;
FBaseSortDirection:=sdIgnored;
FManagedFieldDefs := TFieldDefs.Create(Self);
FManagedIndexDefs := TIndexDefs.Create(Self);
FSubDataSets := TList.Create;
FUsePermissions := False;
FOrigTable := nil;
SortType := stIgnored;
FUpStdFields := True;
FUpChangedBy := True;
FUseIntegrity:=False;//disable for sync
FParams := TStringList.Create;
end;
destructor TZeosDBDataSet.Destroy;
begin
//TODO: Free Subdatasets ??
FParams.Free;
FManagedFieldDefs.Free;
FManagedIndexDefs.Free;
FSubDataSets.Free;
try
inherited Destroy;
except
end;
end;
procedure TZeosDBDataSet.DoExecSQL;
begin
ExecSQL;
end;
function TZeosDBDataSet.NumRowsAffected: Integer;
begin
Result := RowsAffected;
end;
procedure TZeosDBDM.FConnectionAfterConnect(Sender: TObject);
begin
TZConnection(Sender).Password:=Encrypt(TZConnection(Sender).Password,9997);
end;
procedure TZeosDBDM.FConnectionBeforeConnect(Sender: TObject);
begin
TZConnection(Sender).Password:=Decrypt(TZConnection(Sender).Password,9997);
end;
procedure TZeosDBDM.MonitorTrace(Sender: TObject; Event: TZLoggingEvent;
var LogTrace: Boolean);
begin
if LastTime>0 then
LastTime := GetTicks-LastTime;
if LastTime<0 then LastTime := 0;
if Assigned(BaseApplication) then
with BaseApplication as IBaseApplication do
begin
if Event.Error<>'' then
Error(Event.AsString+'('+LastStatement+')')
else if BaseApplication.HasOption('debug-sql') then
Debug(Event.AsString)
else if (LastTime)>50 then
Debug('Long running Query:'+IntToStr(round(LastTime))+' '+Event.AsString);
LastTime:=0;
LastStatement:='';
end;
end;
function TZeosDBDM.GetConnection: TComponent;
begin
Result := TComponent(FMainConnection);
end;
function TZeosDBDM.DBExists: Boolean;
begin
Result := TableExists('USERS') and TableExists('GEN_SQL_ID') and TableExists('GEN_AUTO_ID');
end;
function TZeosDBDM.GetLimitAfterSelect: Boolean;
begin
Result := FLimitAfterSelect;
end;
function TZeosDBDM.GetLimitSTMT: string;
begin
Result := FLimitSTMT;
end;
function TZeosDBDM.GetSyncOffset: Integer;
var
Statement: IZStatement;
ResultSet: IZResultSet;
bConnection: TComponent;
begin
if Assigned(Sequence) then
begin
bConnection := MainConnection;
Sequence.Connection := TZConnection(bConnection);
Result := Sequence.GetCurrentValue shr 56;
Sequence.Connection := nil;
end
else
begin
Statement := TZConnection(MainConnection).DbcConnection.CreateStatement;
ResultSet := Statement.ExecuteQuery('SELECT '+QuoteField('ID')+' FROM '+QuoteField('GEN_SQL_ID'));
if ResultSet.Next then
Result := ResultSet.GetLong(1) shr 56
else Result := 0;
ResultSet.Close;
Statement.Close;
end;
end;
procedure TZeosDBDM.SetSyncOffset(const AValue: Integer);
var
Statement: IZStatement;
aVal: Int64;
begin
aVal := AValue;
aVal := aVal shl 56;
if Assigned(Sequence) then
begin
raise Exception.Create('Not implemented !!!');
end
else
begin
Statement := TZConnection(MainConnection).DbcConnection.CreateStatement;
Statement.Execute('update '+QuoteField('GEN_SQL_ID')+' set '+QuoteField('ID')+'='+IntToStr(aVal));
Statement.Close;
end;
end;
constructor TZeosDBDM.Create(AOwner: TComponent);
begin
FDataSetClass := TZeosDBDataSet;
FMainConnection := TZConnection.Create(AOwner);
if {BaseApplication.HasOption('debug') or} BaseApplication.HasOption('debug-sql') then
begin
Monitor := TZSQLMonitor.Create(FMainConnection);
Monitor.Active:=True;
Monitor.OnTrace:=@MonitorTrace;
end
else Monitor:=nil;
Sequence := nil;
inherited Create(AOwner);
end;
destructor TZeosDBDM.Destroy;
begin
try
if FMainconnection.Connected then
FMainConnection.Disconnect;
if Assigned(Sequence) then
begin
Sequence.Connection := nil;
FreeAndNil(Sequence);
end;
try
//FMainConnection.Destroy;
except
end;
inherited Destroy;
except
end;
end;
function TZeosDBDM.SetProperties(aProp: string;Connection : TComponent = nil): Boolean;
var
tmp: String;
FConnection : TZConnection;
begin
if Assigned(BaseApplication) then
with BaseApplication as IBaseDBInterface do
LastError := '';
FProperties := aProp;
FConnection := TZConnection(Connection);
if not Assigned(FConnection) then
FConnection := FMainConnection;
Result := True;
tmp := aProp;
try
if FConnection.Connected then
FConnection.Disconnect;
FConnection.Port:=0;
FConnection.Properties.Clear;
FConnection.Properties.Add('timeout=2');
FConnection.ClientCodepage:='UTF8';
FConnection.Protocol:='';
FConnection.User:='';
FConnection.Password:='';
FConnection.HostName:='';
FConnection.Database:='';
FConnection.Properties.Clear;
FConnection.Protocol:=copy(tmp,0,pos(';',tmp)-1);
Assert(FConnection.Protocol<>'',strUnknownDbType);
tmp := copy(tmp,pos(';',tmp)+1,length(tmp));
FConnection.HostName := copy(tmp,0,pos(';',tmp)-1);
if pos(':',FConnection.HostName) > 0 then
begin
FConnection.Port:=StrToInt(copy(FConnection.HostName,pos(':',FConnection.HostName)+1,length(FConnection.HostName)));
FConnection.HostName:=copy(FConnection.HostName,0,pos(':',FConnection.HostName)-1);
end
else if pos('/',FConnection.HostName) > 0 then
begin
FConnection.Port:=StrToInt(copy(FConnection.HostName,pos('/',FConnection.HostName)+1,length(FConnection.HostName)));
FConnection.HostName:=copy(FConnection.HostName,0,pos('/',FConnection.HostName)-1);
end;
tmp := copy(tmp,pos(';',tmp)+1,length(tmp));
FConnection.Database:=copy(tmp,0,pos(';',tmp)-1);
tmp := copy(tmp,pos(';',tmp)+1,length(tmp));
FConnection.User := copy(tmp,0,pos(';',tmp)-1);
tmp := copy(tmp,pos(';',tmp)+1,length(tmp));
if copy(tmp,0,1) = 'x' then
FConnection.Password := Decrypt(copy(tmp,2,length(tmp)),99998)
else
FConnection.Password := tmp;
FConnection.Password:=Encrypt(FConnection.Password,9997);
FConnection.BeforeConnect:=@FConnectionBeforeConnect;
FConnection.AfterConnect:=@FConnectionAfterConnect;
if (copy(FConnection.Protocol,0,6) = 'sqlite')
or (copy(FConnection.Protocol,0,8) = 'postgres')
then
begin
{$IFDEF CPUARM}
FConnection.Properties.Add('sslmode=disable');
{$ENDIF}
FConnection.TransactIsolationLevel:=tiNone;
if (copy(FConnection.Protocol,0,6) = 'sqlite') then
if not FileExists(FConnection.Database) then
raise Exception.Create('Databasefile dosend exists');
end
else if (copy(FConnection.Protocol,0,8) = 'firebird')
or (copy(FConnection.Protocol,0,9) = 'interbase')
or (copy(FConnection.Protocol,0,5) = 'mysql')
then
begin
FConnection.TransactIsolationLevel:=tiReadCommitted;
end
else if (copy(FConnection.Protocol,0,5) = 'mssql') then
begin
FConnection.TransactIsolationLevel:=tiReadUnCommitted;
FConnection.ClientCodepage:='utf8';
FConnection.AutoEncodeStrings:=true;
end;
if (copy(FConnection.Protocol,0,5) = 'mysql') then
begin
FConnection.Properties.Add('ValidateUpdateCount=-1');
FConnection.Properties.Add('MYSQL_OPT_RECONNECT=TRUE');
end;
FConnection.Properties.Add('Undefined_Varchar_AsString_Length= 255');
inherited;
//*********Connect***********
FConnection.Connected:=True;
FLimitAfterSelect := False;
FLimitSTMT := 'LIMIT %s';
FDBTyp := FConnection.Protocol;
if FConnection.Protocol = 'sqlite-3' then
begin
//FConnection.ExecuteDirect('PRAGMA synchronous = NORMAL;');
//FConnection.ExecuteDirect('PRAGMA synchronous = FULL;');
FConnection.ExecuteDirect('PRAGMA cache_size = 5120;');
//FConnection.ExecuteDirect('PRAGMA auto_vacuum = INCREMENTAL;');
//FConnection.ExecuteDirect('PRAGMA journal_mode = TRUNCATE;');
FConnection.ExecuteDirect('PRAGMA recursive_triggers = ON;');
FConnection.ExecuteDirect('PRAGMA foreign_keys = ON;');
FConnection.ExecuteDirect('PRAGMA case_sensitive_like = ON;');
//FConnection.ExecuteDirect('PRAGMA secure_delete = ON;');
FConnection.ExecuteDirect('PRAGMA incremental_vacuum(50);');
end
else if (copy(FConnection.Protocol,0,8) = 'firebird')
or (copy(FConnection.Protocol,0,9) = 'interbase') then
begin
FDBTyp := 'firebird';
FLimitSTMT := 'ROWS 1 TO %s';
if not Assigned(Sequence) then
begin
Sequence := TZSequence.Create(Owner);
end;
end
else if FConnection.Protocol = 'mssql' then
begin
FLimitAfterSelect := True;
FLimitSTMT := 'TOP %s';
end;
except on e : Exception do
begin
if Assigned(BaseApplication) then
with BaseApplication as IBaseDBInterface do
LastError := e.Message;
Result := False;
end;
end;
if Result then
begin
if not DBExists then //Create generators
begin
try
if (copy(FConnection.Protocol,0,8) = 'firebird')
or (copy(FConnection.Protocol,0,9) = 'interbase') then
begin
FConnection.ExecuteDirect('EXECUTE BLOCK AS BEGIN'+lineending
+'if (not exists(select 1 from rdb$generators where rdb$generator_name = ''GEN_SQL_ID'')) then'+lineending
+'execute statement ''CREATE SEQUENCE GEN_SQL_ID;'';'+lineending
+'END;');
FConnection.ExecuteDirect('EXECUTE BLOCK AS BEGIN'+lineending
+'if (not exists(select 1 from rdb$generators where rdb$generator_name = ''GEN_AUTO_ID'')) then'+lineending
+'execute statement ''CREATE SEQUENCE GEN_AUTO_ID;'';'+lineending
+'END;');
end
else if copy(FConnection.Protocol,0,6) = 'sqlite' then
begin
FConnection.ExecuteDirect('CREATE TABLE IF NOT EXISTS "GEN_SQL_ID"("SQL_ID" BIGINT NOT NULL PRIMARY KEY,ID BIGINT);');
FConnection.ExecuteDirect('CREATE TABLE IF NOT EXISTS "GEN_AUTO_ID"("SQL_ID" BIGINT NOT NULL PRIMARY KEY,ID BIGINT);');
end
else
begin
if not TableExists('GEN_SQL_ID') then
FConnection.ExecuteDirect('CREATE TABLE '+QuoteField('GEN_SQL_ID')+'('+QuoteField('SQL_ID')+' BIGINT NOT NULL PRIMARY KEY,'+QuoteField('ID')+' BIGINT);');
if not TableExists('GEN_AUTO_ID') then
FConnection.ExecuteDirect('CREATE TABLE '+QuoteField('GEN_AUTO_ID')+'('+QuoteField('SQL_ID')+' BIGINT NOT NULL PRIMARY KEY,'+QuoteField('ID')+' BIGINT);');
end
except on e : Exception do
begin
if Assigned(BaseApplication) then
with BaseApplication as IBaseDBInterface do
LastError := e.Message;
Result := False;
end;
end;
end;
end;
end;
function TZeosDBDM.CreateDBFromProperties(aProp: string): Boolean;
var
FConnection: TZConnection;
tmp: String;
aPassword: String;
aUser: String;
aDatabase: String;
begin
FConnection := TZConnection.Create(Self);
if Assigned(BaseApplication) then
with BaseApplication as IBaseDBInterface do
LastError := '';
tmp := aProp;
FConnection.Protocol:=copy(tmp,0,pos(';',tmp)-1);
Assert(FConnection.Protocol<>'',strUnknownDbType);
tmp := copy(tmp,pos(';',tmp)+1,length(tmp));
FConnection.HostName := copy(tmp,0,pos(';',tmp)-1);
if pos(':',FConnection.HostName) > 0 then
begin
FConnection.Port:=StrToInt(copy(FConnection.HostName,pos(':',FConnection.HostName)+1,length(FConnection.HostName)));
FConnection.HostName:=copy(FConnection.HostName,0,pos(':',FConnection.HostName)-1);
end
else if pos('/',FConnection.HostName) > 0 then
begin
FConnection.Port:=StrToInt(copy(FConnection.HostName,pos('/',FConnection.HostName)+1,length(FConnection.HostName)));
FConnection.HostName:=copy(FConnection.HostName,0,pos('/',FConnection.HostName)-1);
end;
tmp := copy(tmp,pos(';',tmp)+1,length(tmp));
aDatabase:=copy(tmp,0,pos(';',tmp)-1);
tmp := copy(tmp,pos(';',tmp)+1,length(tmp));
aUser := copy(tmp,0,pos(';',tmp)-1);
FConnection.User:=aUser;
tmp := copy(tmp,pos(';',tmp)+1,length(tmp));
FConnection.Database:=aDatabase;
if copy(tmp,0,1) = 'x' then
aPassword := Decrypt(copy(tmp,2,length(tmp)),99998)
else
aPassword := tmp;
FConnection.Password:=aPassword;
if (copy(FConnection.Protocol,0,8) = 'postgres')
then
begin
FConnection.Database:='postgres';
end
else if (copy(FConnection.Protocol,0,5) = 'mssql') then
FConnection.Properties.Add('CreateNewDatabase=CREATE DATABASE "'+aDatabase+'"')
else if (copy(FConnection.Protocol,0,8) = 'firebird')
or (copy(FConnection.Protocol,0,9) = 'interbase')
then
begin
if FConnection.HostName <> '' then
FConnection.Properties.Add('CreateNewDatabase=CREATE DATABASE '''+FConnection.HostName+':'+aDatabase+''' USER '''+aUser+''' PASSWORD '''+aPassword+''' PAGE_SIZE = 4096 DEFAULT CHARACTER SET UTF8')
else
FConnection.Properties.Add('CreateNewDatabase=CREATE DATABASE '''+aDatabase+''' USER '''+aUser+''' PASSWORD '''+aPassword+''' PAGE_SIZE = 4096 DEFAULT CHARACTER SET UTF8');
end
else if (copy(FConnection.Protocol,0,6) = 'sqlite') then
begin
ForceDirectories(ExtractFileDir(FConnection.Database));
end;
try
FConnection.Connected:=True;
except
on e : Exception do
if Assigned(BaseApplication) then
with BaseApplication as IBaseDBInterface do
begin
LastError := e.Message;
//debugln(LastError);
end;
end;
if (copy(FConnection.Protocol,0,8) = 'postgres')
then
begin
Result := FConnection.ExecuteDirect('CREATE DATABASE "'+aDatabase+'" WITH OWNER = "'+aUser+'" ENCODING = ''UTF8'' CONNECTION LIMIT = -1;');
FConnection.Disconnect;
FConnection.Database:=aDatabase;
end;
FConnection.Connected:=True;
Result := FConnection.Connected;
FConnection.Free;
end;
function TZeosDBDM.IsSQLDB: Boolean;
begin
Result:=True;
end;
function TZeosDBDM.GetNewDataSet(aTable: TBaseDBDataSet;
aConnection: TComponent; MasterData: TDataSet; aTables: string): TDataSet;
begin
if IgnoreOpenrequests then exit;
Result := FDataSetClass.Create(Self);
if not Assigned(aConnection) then
aConnection := MainConnection;
with TZeosDBDataSet(Result) do
begin
Connection := TZConnection(aConnection);
FTableNames := aTables;
aTable.DefineFields(Result);
aTable.DefineDefaultFields(Result,Assigned(Masterdata));
FOrigTable := aTable;
if Assigned(Masterdata) then
begin
if not Assigned(TZeosDBDataSet(MasterData).MasterDataSource) then
begin
TZeosDBDataSet(MasterData).MasterDataSource := TDataSource.Create(Self);
TZeosDBDataSet(MasterData).MasterDataSource.DataSet := MasterData;
end;
DataSource := TZeosDBDataSet(MasterData).MasterDataSource;
MasterSource := TZeosDBDataSet(MasterData).MasterDataSource;
with Masterdata as IBaseSubDataSets do
RegisterSubDataSet(aTable);
end;
end;
end;
function TZeosDBDM.GetNewDataSet(aSQL: string; aConnection: TComponent;
MasterData : TDataSet = nil;aOrigtable : TBaseDBDataSet = nil): TDataSet;
begin
Result := FDataSetClass.Create(Self);
if not Assigned(aConnection) then
aConnection := MainConnection;
with TZeosDBDataSet(Result) do
begin
FOrigTable := aOrigtable;
Connection := TZConnection(aConnection);
SQL.Text := aSQL;
FSQL:=aSQL;
if Assigned(Masterdata) then
begin
if not Assigned(TZeosDBDataSet(MasterData).MasterDataSource) then
begin
TZeosDBDataSet(MasterData).MasterDataSource := TDataSource.Create(Self);
TZeosDBDataSet(MasterData).MasterDataSource.DataSet := MasterData;
end;
DataSource := TZeosDBDataSet(MasterData).MasterDataSource;
MasterSource := TZeosDBDataSet(MasterData).MasterDataSource;
end;
end;
end;
procedure TZeosDBDM.DestroyDataSet(DataSet: TDataSet);
begin
try
if Assigned(DataSet) and Assigned(TZeosDBDataSet(DataSet).MasterSource) then
begin
TZeosDBDataSet(DataSet).MasterSource.DataSet.DataSource.Free;
TZeosDBDataSet(DataSet).MasterSource := nil;
TZeosDBDataSet(DataSet).DataSource := nil;
end;
except
with BaseApplication as IBaseApplication do
Debug(Self.ClassName+' has Masterdata that is destroyed before itself !!');
end;
end;
function TZeosDBDM.Ping(aConnection: TComponent): Boolean;
var
atime: Integer;
begin
Result := True;
exit;
try
Result := TZConnection(aConnection).Ping;
except
Result := False;
end;
end;
function TZeosDBDM.DateToFilter(aValue: TDateTime): string;
begin
if FMainConnection.Protocol = 'mssql' then
Result := QuoteValue(FormatDateTime('YYYYMMDD',aValue))
else
Result:=inherited DateToFilter(aValue);
end;
function TZeosDBDM.DateTimeToFilter(aValue: TDateTime): string;
begin
if FMainConnection.Protocol = 'mssql' then
Result := QuoteValue(FormatDateTime('YYYYMMDD HH:MM:SS.ZZZZ',aValue))
else
Result:=inherited DateTimeToFilter(aValue);
end;
function TZeosDBDM.GetUniID(aConnection : TComponent = nil;Generator : string = 'GEN_SQL_ID';AutoInc : Boolean = True): Variant;
var
Statement: IZStatement;
ResultSet: IZResultSet;
bConnection: TComponent;
begin
if Assigned(Sequence) then
begin
bConnection := MainConnection;
if Assigned(aConnection) then
bConnection := aConnection;
Sequence.SequenceName:=Generator;
Sequence.Connection := TZConnection(bConnection);
Result := Sequence.GetNextValue;
Sequence.Connection := nil;
end
else
begin
try
if (copy(FMainConnection.Protocol,0,6) = 'sqlite') and (Assigned(aConnection)) then
Statement := TZConnection(aConnection).DbcConnection.CreateStatement //we have global locking in sqlite so we must use the actual connection
else
Statement := TZConnection(MainConnection).DbcConnection.CreateStatement;
if AutoInc then
begin
if (copy(FMainConnection.Protocol,0,5) = 'mysql') then
begin
Statement.Execute('update '+QuoteField(Generator)+' set '+QuoteField('ID')+'='+QuoteField('ID')+'+1;')
end
else
begin
if LimitAfterSelect then
Statement.Execute('update '+QuoteField(Generator)+' set '+QuoteField('ID')+'=(select '+Format(LimitSTMT,['1'])+' '+QuoteField('ID')+' from '+QuoteField(Generator)+')+1;')
else
Statement.Execute('update '+QuoteField(Generator)+' set '+QuoteField('ID')+'=(select '+QuoteField('ID')+' from '+QuoteField(Generator)+' '+Format(LimitSTMT,['1'])+')+1;');
end;
end;
except
end;
try
ResultSet := Statement.ExecuteQuery('SELECT '+QuoteField('ID')+' FROM '+QuoteField(Generator));
if ResultSet.Next then
Result := ResultSet.GetLong(1)
else
begin
Statement.Execute('insert into '+QuoteField(GENERATOR)+' ('+QuoteField('SQL_ID')+','+QuoteField('ID')+') VALUES (1,1000);');
Result := 1000;
end;
ResultSet.Close;
Statement.Close;
except
end;
end;
end;
const
ChunkSize: Longint = 16384; { copy in 8K chunks }
procedure TZeosDBDM.StreamToBlobField(Stream: TStream; DataSet: TDataSet;
Fieldname: string);
var
Posted: Boolean;
GeneralQuery: TZQuery;
pBuf : Pointer;
cnt: LongInt;
dStream: TStream;
totCnt: LongInt;
begin
totCnt := 0;
if DataSet.Fielddefs.IndexOf(FieldName) = -1 then
begin
if DataSet.State = dsInsert then
begin
Posted := True;
DataSet.Post;
end;
GeneralQuery := TZQuery.Create(Self);
GeneralQuery.Connection := TZQuery(DataSet).Connection;
GeneralQuery.SQL.Text := 'select * from '+QuoteField(TZeosDBDataSet(DataSet).DefaultTableName)+' where '+QuoteField('SQL_ID')+'='+QuoteValue(DataSet.FieldByName('SQL_ID').AsString)+';';
GeneralQuery.Open;
GeneralQuery.Edit;
dStream := GeneralQuery.CreateBlobStream(GeneralQuery.FieldByName(Fieldname),bmWrite);
try
GetMem(pBuf, ChunkSize);
try
cnt := Stream.Read(pBuf^, ChunkSize);
cnt := dStream.Write(pBuf^, cnt);
totCnt := totCnt + cnt;
{Loop the process of reading and writing}
while (cnt > 0) do
begin
{Read bufSize bytes from source into the buffer}
cnt := Stream.Read(pBuf^, ChunkSize);
{Now write those bytes into destination}
cnt := dStream.Write(pBuf^, cnt);
{Increment totCnt for progress and do arithmetic to update the gauge}
totcnt := totcnt + cnt;
end;
finally
FreeMem(pBuf, ChunkSize);
end;
finally
dStream.Free;
end;
GeneralQuery.Post;
GeneralQuery.Free;
if Posted then DataSet.Edit;
end
else inherited;
end;
function TZeosDBDM.BlobFieldStream(DataSet: TDataSet; Fieldname: string
): TStream;
var
GeneralQuery: TZQuery;
aSql: String;
begin
Result := nil;
if DataSet.Fielddefs.IndexOf(FieldName) = -1 then
begin
GeneralQuery := TZQuery.Create(Self);
GeneralQuery.Connection := TZQuery(DataSet).Connection;
aSql := 'select '+QuoteField(Fieldname)+' from '+QuoteField(TZeosDBDataSet(DataSet).DefaultTableName)+' where '+QuoteField('SQL_ID')+'='+QuoteValue(DataSet.FieldByName('SQL_ID').AsString)+';';
GeneralQuery.SQL.Text := aSql;
GeneralQuery.Open;
result := GeneralQuery.CreateBlobStream(GeneralQuery.FieldByName(Fieldname),bmRead);
GeneralQuery.Free;
end
else Result := inherited;
end;
function TZeosDBDM.GetErrorNum(e: EDatabaseError): Integer;
begin
Result:=inherited GetErrorNum(e);
if e is EZDatabaseError then
Result := EZDatabaseError(e).ErrorCode;
end;
procedure TZeosDBDM.DeleteExpiredSessions;
var
GeneralQuery: TZQuery;
begin
GeneralQuery := TZQuery.Create(Self);
GeneralQuery.Connection := FMainConnection;
GeneralQuery.SQL.Text := 'DELETE FROM '+QuoteField('ACTIVEUSERS')+' WHERE ('+QuoteField('EXPIRES')+' < '+Self.DateTimeToFilter(Now)+');';
GeneralQuery.ExecSQL;
GeneralQuery.Free;
end;
function TZeosDBDM.GetNewConnection: TComponent;
begin
Result := TZConnection.Create(Self);
with Result as TZConnection do
begin
Setproperties(FProperties,Result);
end;
end;
function TZeosDBDM.QuoteField(aField: string): string;
begin
Result:=inherited QuoteField(aField);
if (copy(TZConnection(MainConnection).Protocol,0,5) = 'mysql') then
Result := '`'+aField+'`';
end;
function TZeosDBDM.QuoteValue(aField: string): string;
begin
Result:=inherited QuoteValue(aField);
if (copy(TZConnection(MainConnection).Protocol,0,5) = 'mysql') then
Result := ''''+aField+'''';
end;
procedure TZeosDBDM.Disconnect(aConnection: TComponent);
begin
TZConnection(aConnection).Disconnect;
end;
function TZeosDBDM.StartTransaction(aConnection: TComponent;ForceTransaction : Boolean = False): Boolean;
begin
TZConnection(aConnection).Tag := Integer(TZConnection(aConnection).TransactIsolationLevel);
if ForceTransaction and (copy(TZConnection(aConnection).Protocol,0,6) = 'sqlite') then
TZConnection(aConnection).TransactIsolationLevel:=tiReadCommitted
else if (copy(TZConnection(aConnection).Protocol,0,8) = 'postgres') then
TZConnection(aConnection).TransactIsolationLevel:=tiReadCommitted
else if (copy(TZConnection(aConnection).Protocol,0,5) = 'mssql') then
TZConnection(aConnection).TransactIsolationLevel:=tiReadUnCommitted;
TZConnection(aConnection).StartTransaction;
end;
function TZeosDBDM.CommitTransaction(aConnection: TComponent): Boolean;
begin
if not TZConnection(aConnection).AutoCommit then
TZConnection(aConnection).Commit;
if TZTransactIsolationLevel(TZConnection(aConnection).Tag) <> TZConnection(aConnection).TransactIsolationLevel then
TZConnection(aConnection).TransactIsolationLevel := TZTransactIsolationLevel(TZConnection(aConnection).Tag);
end;
function TZeosDBDM.RollbackTransaction(aConnection: TComponent): Boolean;
begin
if not TZConnection(aConnection).AutoCommit then
TZConnection(aConnection).Rollback;
if TZTransactIsolationLevel(TZConnection(aConnection).Tag) <> TZConnection(aConnection).TransactIsolationLevel then
TZConnection(aConnection).TransactIsolationLevel := TZTransactIsolationLevel(TZConnection(aConnection).Tag);
end;
function TZeosDBDM.IsTransactionActive(aConnection: TComponent): Boolean;
begin
Result := TZConnection(aConnection).InTransaction;
end;
function TZeosDBDM.TableExists(aTableName: string;aConnection : TComponent = nil;AllowLowercase: Boolean = False): Boolean;
var
aIndex: longint;
i: Integer;
tmp: String;
begin
Result := False;
try
if Tables.Count = 0 then
begin
//Get uncached
if not Assigned(aConnection) then
begin
FMainConnection.DbcConnection.GetMetadata.ClearCache;
FMainConnection.GetTableNames('','',Tables);
FMainConnection.GetTriggerNames('','',Triggers);
end
else
begin
TZConnection(aConnection).DbcConnection.GetMetadata.ClearCache;
TZConnection(aConnection).GetTableNames('','',Tables);
FMainConnection.GetTriggerNames('','',Triggers);
end;
end;
except
end;
if Tables.IndexOf(aTableName) > 0 then
begin
Result := True;
exit;
end;
for i := 0 to Tables.Count-1 do
begin
tmp := Tables[i];
if (Uppercase(tmp) = aTableName)
then
begin
Result := True;
break;
end;
end;
end;
function TZeosDBDM.TriggerExists(aTriggerName: string; aConnection: TComponent;
AllowLowercase: Boolean): Boolean;
var
i: Integer;
tmp: String;
GeneralQuery: TZQuery;
begin
if Triggers.Count= 0 then
begin
GeneralQuery := TZQuery.Create(Self);
GeneralQuery.Connection:=TZConnection(MainConnection);
if (copy(FMainConnection.Protocol,0,10) = 'postgresql') then
begin
GeneralQuery.SQL.Text:='select tgname from pg_trigger;';
GeneralQuery.Open;
end
else if (copy(FMainConnection.Protocol,0,6) = 'sqlite') then
begin
GeneralQuery.SQL.Text:='select name from sqlite_master where type=''trigger'';';
GeneralQuery.Open;
end
else if (FMainConnection.Protocol = 'mssql') then
begin
GeneralQuery.SQL.Text:='SELECT trigger_name = name FROM sysobjects WHERE type = ''TR''';
GeneralQuery.Open;
end;
if GeneralQuery.Active then
with GeneralQuery do
begin
First;
while not EOF do
begin
Triggers.Add(Fields[0].AsString);
Next;
end;
end;
GeneralQuery.Destroy;
end;
Result := False;
if Triggers.IndexOf(aTriggerName) > 0 then
begin
Result := True;
exit;
end;
for i := 0 to Triggers.Count-1 do
begin
tmp := Triggers[i];
if (Uppercase(tmp) = aTriggerName) then
begin
Result := True;
break;
end;
end;
end;
function TZeosDBDM.GetDBType: string;
begin
Result:=TZConnection(MainConnection).Protocol;
if copy(Result,0,8)='postgres' then Result := 'postgres';
if Result='interbase' then Result := 'firebird';
if Result='sqlite-3' then Result := 'sqlite';
end;
function TZeosDBDM.GetDBLayerType: string;
begin
Result := 'SQL';
end;
function TZeosDBDM.CreateTrigger(aTriggerName: string; aTableName: string;
aUpdateOn: string; aSQL: string;aField : string = ''; aConnection: TComponent = nil): Boolean;
var
GeneralQuery: TZQuery;
begin
if TriggerExists(aTableName+'_'+aTriggerName) then exit;
GeneralQuery := TZQuery.Create(Self);
GeneralQuery.Connection := TZConnection(MainConnection);
if Assigned(aConnection) then GeneralQuery.Connection:=TZConnection(aConnection);
if (copy(FMainConnection.Protocol,0,10) = 'postgresql') then
begin
if (aField <> '') and (aUpdateOn='UPDATE') then
begin
aSQL := 'IF $NEW$.'+QuoteField(aField)+'!=$OLD$.'+QuoteField(aField)+' THEN '+LineEnding+aSQL+' END IF;';
end;
GeneralQuery.SQL.Text :=
'DROP TRIGGER IF EXISTS '+QuoteField(aTableName+'_'+aTriggerName)+' ON '+QuoteField(aTableName)+';'+LineEnding
+'CREATE OR REPLACE FUNCTION '+aTableName+'_'+aTriggerName+'_TRIGGER() RETURNS TRIGGER AS $BASE$'+LineEnding
+'BEGIN'+LineEnding
+StringReplace(StringReplace(StringReplace(aSQL,'$NEW$','new',[rfReplaceAll]),'$OLD$','old',[rfReplaceAll]),'$UPDATED$','new',[rfReplaceAll])+LineEnding
+'RETURN NEW;'+LineEnding
+'END;'+LineEnding
+'$BASE$ LANGUAGE plpgsql;'+LineEnding
+'CREATE TRIGGER '+QuoteField(aTableName+'_'+aTriggerName)+' AFTER '+aUpdateOn+' ON '+QuoteField(aTableName)+' FOR EACH ROW EXECUTE PROCEDURE '+aTableName+'_'+aTriggerName+'_TRIGGER();'+LineEnding;
//DebugLn(GeneralQuery.SQL.Text);
GeneralQuery.ExecSQL;
end
else if (FMainConnection.Protocol = 'mssql') then
begin
if (aField <> '') and (aUpdateOn='UPDATE') then
begin
aSQL := 'IF INSERTED.'+QuoteField(aField)+'!=DELETED.'+QuoteField(aField)+' THEN '+LineEnding+aSQL+' END IF;';
end;
GeneralQuery.SQL.Text :=
'CREATE OR ALTER TRIGGER '+QuoteField(aTableName+'_'+aTriggerName)+' FOR '+QuoteField(aTableName)+' AFTER '+StringReplace(aUpdateOn,'or',',',[rfReplaceAll])
+' AS'+LineEnding
+'BEGIN'+LineEnding
+StringReplace(StringReplace(StringReplace(aSQL,'$NEW$','INSERTED',[rfReplaceAll]),'$OLD$','DELETED',[rfReplaceAll]),'$UPDATED$','new',[rfReplaceAll])+LineEnding
+'END;';
//DebugLn(GeneralQuery.SQL.Text);
GeneralQuery.ExecSQL;
end
{ else if (copy(FMainConnection.Protocol,0,6) = 'sqlite') then
begin
GeneralQuery.SQL.Text :=
'CREATE TRIGGER IF NOT EXISTS '+QuoteField(aTableName+'_'+aTriggerName)+' AFTER '+StringReplace(aUpdateOn,'or',',',[rfReplaceAll]);
if aField <> '' then
GeneralQuery.SQL.Text := GeneralQuery.SQL.Text+' OF '+QuoteField(aField);
GeneralQuery.SQL.Text := GeneralQuery.SQL.Text+' ON '+QuoteField(aTableName)+' FOR EACH ROW'+LineEnding
+'BEGIN'+LineEnding
+StringReplace(StringReplace(StringReplace(aSQL,'$NEW$','new',[rfReplaceAll]),'$OLD$','old',[rfReplaceAll]),'$UPDATED$','new',[rfReplaceAll])+LineEnding
+'END'+LineEnding;
DebugLn(GeneralQuery.SQL.Text);
GeneralQuery.ExecSQL;
end }
else
Result:=inherited CreateTrigger(aTriggerName, aTableName, aUpdateOn, aSQL,aField, aConnection);
GeneralQuery.Destroy;
end;
function TZeosDBDM.DropTable(aTableName: string): Boolean;
var
GeneralQuery: TZQuery;
begin
GeneralQuery := TZQuery.Create(Self);
GeneralQuery.Connection := TZConnection(MainConnection);
GeneralQuery.SQL.Text := 'drop table '+QuoteField(aTableName);
GeneralQuery.ExecSQL;
GeneralQuery.Destroy;
Result := True;
RemoveCheckTable(aTableName);
end;
function TZeosDBDM.FieldToSQL(aName: string; aType: TFieldType; aSize: Integer;
aRequired: Boolean): string;
begin
if aName <> '' then
Result := QuoteField(aName)
else Result:='';
case aType of
ftString:
begin
if (copy(FMainConnection.Protocol,0,8) = 'firebird')
or (copy(FMainConnection.Protocol,0,9) = 'interbase')
or (copy(FMainConnection.Protocol,0,10) = 'postgresql') then
Result := Result+' VARCHAR('+IntToStr(aSize)+')'
else
Result := Result+' NVARCHAR('+IntToStr(aSize)+')';
end;
ftSmallint,
ftInteger:Result := Result+' INTEGER';
ftLargeInt:
begin
Result := Result+' BIGINT';
end;
ftAutoInc:
begin
if (FMainConnection.Protocol = 'mssql') then
Result := Result+' INTEGER PRIMARY KEY IDENTITY'
else if (copy(FMainConnection.Protocol,0,6) = 'sqlite') then
Result := Result+' INTEGER PRIMARY KEY AUTOINCREMENT'
else Result := Result+' INTEGER PRIMARY KEY';
end;
ftFloat:
begin
if (copy(FMainConnection.Protocol,0,8) = 'firebird')
or (copy(FMainConnection.Protocol,0,9) = 'interbase') then
Result := Result+' DOUBLE PRECISION'
else
Result := Result+' FLOAT';
end;
ftDate:
begin
if (FMainConnection.Protocol = 'mssql') then
Result := Result+' DATETIME'
else
Result := Result+' DATE';
end;
ftDateTime:
begin
if (FMainConnection.Protocol = 'mssql')
or (copy(FMainConnection.Protocol,0,6) = 'sqlite')
then
Result := Result+' DATETIME'
else
Result := Result+' TIMESTAMP'
end;
ftTime:
begin
if (FMainConnection.Protocol = 'mssql') then
Result := Result+' DATETIME'
else
Result := Result+' TIME';
end;
ftBlob:
begin
if (FMainConnection.Protocol = 'mssql') then
Result := Result+' IMAGE'
else if (copy(FMainConnection.Protocol,0,10) = 'postgresql') then
Result := Result+' BYTEA'
else
Result := Result+' BLOB';
end;
ftMemo:
begin;
if (copy(FMainConnection.Protocol,0,8) = 'firebird')
or (copy(FMainConnection.Protocol,0,9) = 'interbase') then
Result := Result+' BLOB SUB_TYPE 1'
else
Result := Result+' TEXT';
end;
end;
if aRequired then
Result := Result+' NOT NULL'
else
begin
if (FMainConnection.Protocol = 'mssql') then
Result := Result+' NULL'
end;
end;
function TZeosDBDM.GetColumns(TableName: string): TStrings;
var
Metadata: IZDatabaseMetadata;
begin
Metadata := FMainConnection.DbcConnection.GetMetadata;
Result := TStringList.Create;
with Metadata.GetColumns(FMainConnection.Catalog,'',TableNAme,'') do
try
while Next do
Result.Add(GetStringByName('COLUMN_NAME'));
finally
Close;
end;
end;
initialization
uBaseDBInterface.DatabaseLayers.Add(TZeosDBDM);
end.
|
unit uBotaoSeguro;
interface
uses
System.SysUtils, System.Classes, FMX.Types, FMX.Controls, FMX.StdCtrls;
type
TBotaoSeguro = class(TButton)
private
{ Private declarations }
FClicando: Boolean;
FConfirma: Boolean;
FMensagem: String;
procedure SetConfirma(const Value: Boolean);
procedure SetMensagem(const Value: String);
function GetConfirma: Boolean;
protected
{ Protected declarations }
procedure Click; override;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
published
{ Published declarations }
property Confirma: Boolean read GetConfirma write SetConfirma default True;
property Mensagem: String read FMensagem write SetMensagem;
end;
procedure Register;
implementation
uses
FMX.Dialogs, System.UITypes;
procedure Register;
begin
RegisterComponents('Samples', [TBotaoSeguro]);
end;
{ TBotaoSeguro }
procedure TBotaoSeguro.Click;
var
aExecuta: Boolean;
begin
if FClicando then
Exit;
FClicando := True;
try
if Confirma then
aExecuta := MessageDlg(Mensagem, TMsgDlgType.mtConfirmation, [TMsgDlgBtn.mbYes, TMsgDlgBtn.mbNo], 0 ) = IDYes
else
aExecuta := True;
if aExecuta then
inherited;
finally
FClicando := False;
end;
end;
constructor TBotaoSeguro.Create(AOwner: TComponent);
begin
inherited;
FClicando := False;
FConfirma := True;
FMensagem := 'Confirma ?';
end;
function TBotaoSeguro.GetConfirma: Boolean;
begin
Result := FConfirma and (Mensagem <> '');
end;
procedure TBotaoSeguro.SetConfirma(const Value: Boolean);
var
aTerminaComRetic: Boolean;
begin
FConfirma := Value;
aTerminaComRetic := Copy(Text,Length(Text)-2,3) = '...';
if FConfirma and not aTerminaComRetic then
Text := Text + '...'
else if (not FConfirma) and (aTerminaComRetic) then
Text := Copy(Text,1,Length(Text)-3);
end;
procedure TBotaoSeguro.SetMensagem(const Value: String);
begin
FMensagem := Value;
if Value = '' then
Confirma := False;
end;
end.
|
unit Tasker.Plugin.Event;
interface
type
TDummy = class
end;
//// ----------------------------- EVENT PLUGIN ONLY --------------------------------- //
//
// public static class Event {
//
// public final static String PASS_THROUGH_BUNDLE_MESSAGE_ID_KEY = BASE_KEY + ".MESSAGE_ID";
//
// private final static String EXTRA_REQUEST_QUERY_PASS_THROUGH_DATA = EXTRAS_PREFIX + "PASS_THROUGH_DATA";
//
// /**
// * @param extrasFromHost intent extras from the intent received by the QueryReceiver
// * @see #addPassThroughData(Intent, Bundle)
// */
// public static boolean hostSupportsRequestQueryDataPassThrough( Bundle extrasFromHost ) {
// return hostSupports( extrasFromHost, EXTRA_HOST_CAPABILITY_REQUEST_QUERY_DATA_PASS_THROUGH );
// }
//
// /**
// * Specify a bundle of data (probably representing whatever change happened in the condition)
// * which will be included in the QUERY_CONDITION broadcast sent by the host for each
// * event instance of the plugin.
// *
// * The minimal purpose is to enable the plugin to associate a QUERY_CONDITION to the
// * with the REQUEST_QUERY that caused it.
// *
// * Note that for security reasons it is advisable to also store a message ID with the bundle
// * which can be compared to known IDs on receipt. The host cannot validate the source of
// * REQUEST_QUERY intents so fake data may be passed. Replay attacks are also possible.
// * addPassThroughMesssageID() can be used to add an ID if the plugin doesn't wish to add it's
// * own ID to the pass through bundle.
// *
// * Note also that there are several situations where REQUEST_QUERY will not result in a
// * QUERY_CONDITION intent (e.g. event throttling by the host), so plugin-local data
// * indexed with a message ID needs to be timestamped and eventually timed-out.
// *
// * This function can be called multiple times, each time all keys in data will be added to
// * that of previous calls.
// *
// * @param requestQueryIntent intent being sent to the host
// * @param data the data to be passed-through
// * @see #hostSupportsRequestQueryDataPassThrough(Bundle)
// * @see #retrievePassThroughData(Intent)
// * @see #addPassThroughMessageID
// *
// */
// public static void addPassThroughData( Intent requestQueryIntent, Bundle data ) {
//
// Bundle passThroughBundle = retrieveOrCreatePassThroughBundle( requestQueryIntent );
//
// passThroughBundle.putAll( data );
// }
//
// /**
// * Retrieve the pass through data from a QUERY_REQUEST from the host which was generated
// * by a REQUEST_QUERY from the plugin.
// *
// * Note that if addPassThroughMessageID() was previously called, the data will contain an extra
// * key TaskerPlugin.Event.PASS_THOUGH_BUNDLE_MESSAGE_ID_KEY.
// *
// * @param queryConditionIntent QUERY_REQUEST sent from host
// * @return data previously added to the REQUEST_QUERY intent
// * @see #hostSupportsRequestQueryDataPassThrough(Bundle)
// * @see #addPassThroughData(Intent,Bundle)
// */
// public static Bundle retrievePassThroughData( Intent queryConditionIntent ) {
// return (Bundle) getExtraValueSafe(
// queryConditionIntent,
// EXTRA_REQUEST_QUERY_PASS_THROUGH_DATA,
// Bundle.class,
// "retrievePassThroughData"
// );
// }
//
// /**
// * Add a message ID to a REQUEST_QUERY intent which will then be included in the corresponding
// * QUERY_CONDITION broadcast sent by the host for each event instance of the plugin.
// *
// * The minimal purpose is to enable the plugin to associate a QUERY_CONDITION to the
// * with the REQUEST_QUERY that caused it. It also allows the message to be verified
// * by the plugin to prevent e.g. replay attacks
// *
// * @param requestQueryIntent intent being sent to the host
// * @return a guaranteed non-repeating within 100 calls message ID
// * @see #hostSupportsRequestQueryDataPassThrough(Bundle)
// * @see #retrievePassThroughData(Intent)
// * @return an ID for the bundle so it can be identified and the caller verified when it is again received by the plugin
// *
// */
// public static int addPassThroughMessageID( Intent requestQueryIntent ) {
//
// Bundle passThroughBundle = retrieveOrCreatePassThroughBundle( requestQueryIntent );
//
// int id = getPositiveNonRepeatingRandomInteger();
//
// passThroughBundle.putInt( PASS_THROUGH_BUNDLE_MESSAGE_ID_KEY, id );
//
// return id;
// }
//
// /*
// * Retrieve the pass through data from a QUERY_REQUEST from the host which was generated
// * by a REQUEST_QUERY from the plugin.
// *
// * @param queryConditionIntent QUERY_REQUEST sent from host
// * @return the ID which was passed through by the host, or -1 if no ID was found
// * @see #hostSupportsRequestQueryDataPassThrough(Bundle)
// * @see #addPassThroughData(Intent,Bundle)
// */
// public static int retrievePassThroughMessageID( Intent queryConditionIntent ) {
//
// int toReturn = -1;
//
// Bundle passThroughData = Event.retrievePassThroughData( queryConditionIntent );
//
// if ( passThroughData != null ) {
// Integer id = (Integer) getBundleValueSafe(
// passThroughData,
// PASS_THROUGH_BUNDLE_MESSAGE_ID_KEY,
// Integer.class,
// "retrievePassThroughMessageID"
// );
//
// if ( id != null )
// toReturn = id;
// }
//
// return toReturn;
// }
//
// // internal use
// private static Bundle retrieveOrCreatePassThroughBundle( Intent requestQueryIntent ) {
//
// Bundle passThroughBundle;
//
// if ( requestQueryIntent.hasExtra( EXTRA_REQUEST_QUERY_PASS_THROUGH_DATA ) )
// passThroughBundle = requestQueryIntent.getBundleExtra( EXTRA_REQUEST_QUERY_PASS_THROUGH_DATA );
// else {
// passThroughBundle = new Bundle();
// requestQueryIntent.putExtra( EXTRA_REQUEST_QUERY_PASS_THROUGH_DATA, passThroughBundle );
// }
//
// return passThroughBundle;
// }
// }
implementation
end.
|
{
******************************************************************************
Модуль доступа к данным СК-2007
Версия = 3.00
Мордовское РДУ
fvv@rdurm.odusv.so-ups.ru
******************************************************************************
Пример использования:
uses
ck7GetData;
var
ck: Tck7Data;
res: TOutCKDataArray;
begin
ck := Tck7Data.Create('Test');
ck.SQLServers.Add(Tck7SQLServer.Create('oik07-1-mrdv','login','password'));
ck.SQLServers.Add(Tck7SQLServer.Create('oik07-2-mrdv','login','password'));
ck.SQLServers.Add(Tck7SQLServer.Create('oik07-3-mrdv')); // windows domain authentification
try
if ck.OpenConnection() then
begin
res := ck.GetArrayValueTI_Sync(444,ckPV,ckTI48,Date());
if res <> nil then
for i:= 0 to Length(res)-1 do
WriteLn( DtToStr(res[i].TStamp) + ValueToStr(res[i].Value) + PriznToHexStr(res[i].Prizn) );
end;
finally
ck.Free;
end;
end;
******************************************************************************
}
unit ck7GetData;
interface
uses DB, ADODB, SysUtils, Classes, Math;
type
TLengthArrayTI = ( // набор данных
ckTI24 = 24, // 24 точки
ckTI48 = 48 // 48 точек
);
TCategoryTI = ( // num список категорий
ckTI = 73, // 1 I 73 Телеизмерения ТИ
ckTS = 83, // 2 S 83 Телесигналы ТС
ckIIS = 74, // 3 J 74 Интегралы и средние ИС
ckSV = 87, // 4 W 87 СВ-1 (мгновенная,СДВ) СВ
ckPL = 80, // 5 P 80 Планы ПЛ
ckEI = 85, // 6 U 85 Ежедневная информация ЕИ
ckSP = 67, // 7 C 67 Специальные параметры вещественные СП
ckPV = 72, // 8 H 72 СВ-2 (усредненная) ПВ
ckFTI = 76, // 9 L 76 Фильтрованные телеизмерения ФТИ
ckMSK = 77, // 10 M 77 Специальные параметры целочисленные МСК
ckTIS = 65, // 11 A 65 "Телеизмерения ""сырые""" ТИС
ckTSS = 66, // 12 B 66 "Телесигналы ""сырые""" ТСС
ckPCHAS = 202, // 13 К 202 Универсальные хранилища 30 мин ПЧАС
ckCHAS = 203, // 14 Л 203 Универсальные хранилища 1 час ЧАС
ckSYT = 207 // 15 П 207 Универсальные хранилища 1 день СУТ
);
{
почему то не используются (нет флага InRTDB):
O ОТИ Оцененные ТИ 0
Б МИН Универсальные хранилища 1 мин 0
Г ПМИН Универсальные хранилища 5 мин 0
З ДМИН Универсальные хранилища 10 мин 0
И ЧЧАС Универсальные хранилища 15 мин 0
У МЕС Универсальные хранилища 1 месяц 0
Ъ СД Статич.данные для локальных дорасчетов (const) 0
Д ЛД Локальный дорасчет на формах 0
D Д Временная локальная переменная дорасчета 0
R Т Период (временной интервал из таблицы Period) 0
T ЕИТ Текстовая ежедневная информация 0
}
TTI = record // телеизмерение
id: Integer;
cat: TCategoryTI;
end;
TTIArray = array of TTI;
TOutCKData = record // результат запроса
TStamp: TDateTime; // дата время
Value: Double; // значение
Prizn: Integer; // признак достоверности
end;
TOutCKDataArray = array of TOutCKData;
TOutCKDataArrayManyTI = array of TOutCKDataArray;
TStringArray = array of string;
TDoubleArray = array of Double;
Tck7SQLServer = class //сервер SQL
Server: string;
WinAuth: Boolean;
Login: string;
Pas: string;
public
constructor Create(sServer: string); overload;
constructor Create(Sserver: string; sLogin: string; sPas: string); overload;
end;
Tck7SQLServerList = class(TList) // список серверов SQL
private
function Get(Index: Integer): Tck7SQLServer;
procedure Put(Index: Integer; const Value: Tck7SQLServer);
public
property Items[Index: Integer]: Tck7SQLServer read Get write Put; default;
procedure Clear; override;
end;
//получение данных
TCK7Data = class
private
sCaption: string; // заголовок задачи
ADOCon: TADOConnection; // соединение с SQL
sConnected: Boolean; // есть ли связь с СК
iTimeOut: Integer; // сек на выполнение команды
sMainSQLServer: string; // имя главного SQL сервера OIK
listSQLServers: Tck7SQLServerList; // список SQL Server-ов СК-2007
public
property Caption: string read sCaption write sCaption;
property Connected: Boolean read sConnected;
property TimeOut: Integer read iTimeOut write iTimeOut;
property MainSQLServer: string read sMainSQLServer;
property SQLServers: Tck7SQLServerList read listSQLServers write listSQLServers;
constructor Create(sCapt: string = 'CK2007');
destructor Free();
function OpenConnection(): Boolean;
procedure CloseConnection();
function GetArrayValueTI_Sync(ti: Integer; cat: TCategoryTI; lena: TLengthArrayTI; date1: TDateTime): TOutCKDataArray; overload;
function GetArrayValueTI_Sync(ti: Integer; cat: TCategoryTI; lena: TLengthArrayTI; date1, date2: TDateTime): TOutCKDataArray; overload;
function GetArrayValueTI_Sync(ti: TTIArray; lena: TLengthArrayTI; date1: TDateTime): TOutCKDataArrayManyTI; overload;
function GetArrayValueTI_Sync(ti: TTIArray; lena: TLengthArrayTI; date1, date2: TDateTime): TOutCKDataArrayManyTI; overload;
end;
function DtToStr(dt: TDateTime; frm: string = 'dd.mm.yyyy hh:nn:ss'): string;
function PriznToHexStr(prz: Integer): string;
function PriznToStr(prz: Integer): string;
function PriznNoData(prz: Integer): Boolean;
function ValueToStr(val: Double; frm: string = '%f'): string;
function NumToCat(i: Byte): TCategoryTI;
function CatToNum(cat: TCategoryTI): Byte;
function GetMaxAndHour(arr: TOutCKDataArray): string; overload;
function GetMaxAndHour(arr: TOutCKDataArrayManyTI): TStringArray; overload;
function GetMinAndHour(arr: TOutCKDataArray): string; overload;
function GetMinAndHour(arr: TOutCKDataArrayManyTI): TStringArray; overload;
function GetAvg(arr: TOutCKDataArray): Double; overload;
function GetAvg(arr: TOutCKDataArrayManyTI): TDoubleArray; overload;
function GetSum(arr: TOutCKDataArray): Double; overload;
function GetSum(arr: TOutCKDataArrayManyTI): TDoubleArray; overload;
procedure RoundArray(var arr: TOutCKDataArray; countsign: Byte); overload;
procedure RoundArray(var arr: TOutCKDataArrayManyTI; countsign: Byte); overload;
implementation
constructor TCK7Data.Create(sCapt: string = 'CK2007');
begin
iTimeOut := 30;
sConnected := false;
sCaption := sCapt;
sMainSQLServer:= '';
listSQLServers := Tck7SQLServerList.Create();
ADOCon := TADOConnection.Create(nil);
end;
destructor TCK7Data.Free();
begin
SQLServers.Free;
ADOCon.Free;
end;
function TCK7Data.OpenConnection(): Boolean;
var
i, mainI: Integer;
ADOConTest: TADOConnection;
Query: TAdoQuery;
begin
//определение основного сервера ОИК
sConnected := false;
if self.SQLServers.Count < 1 then
begin
Result := sConnected;
Exit;
end;
sMainSQLServer := '';
for i := 0 to self.SQLServers.Count - 1 do
begin
ADOConTest := TADOConnection.Create(nil);
try
//формирование строки подключения к серверу
ADOConTest.ConnectionString := Format('Provider=SQLOLEDB.1;Data Source=%s;Initial Catalog=%s;', [self.SQLServers[i].Server, 'OIK']);
if self.SQLServers[i].WinAuth then
ADOConTest.ConnectionString := ADOConTest.ConnectionString + 'Integrated Security=SSPI;'
else
ADOConTest.ConnectionString := ADOConTest.ConnectionString + Format('User ID=%s;Password=%s;', [self.SQLServers[i].Login, self.SQLServers[i].Pas]);
ADOConTest.LoginPrompt := false;
ADOConTest.ConnectionTimeout := self.TimeOut;
//подключение к серверу
try
ADOConTest.Open;
except
sConnected := false;
end;
//зарпос на главную базу
if ADOConTest.Connected then
begin
Query := TAdoQuery.Create(nil);
try
Query.Connection := ADOConTest;
Query.SQL.Text := 'exec :ckSrv = [dbo].fn_GetMainOIKServerName';
Query.Prepared := True;
Query.CommandTimeout := self.TimeOut;
try
Query.ExecSQL;
sMainSQLServer := Query.Parameters.ParamByName('ckSrv').Value;
except
sMainSQLServer := '';
end;
finally
Query.Free
end;
end;
finally
if ADOConTest.Connected then ADOConTest.Close();
ADOConTest.Free();
end;
//если главный сервер определён то перебирать другие сервера не нужно
if sMainSQLServer <> '' then Break;
end;
if sMainSQLServer = '' then
begin
//ниодин из серверов не выдал результата
sConnected := false;
end
else
begin
//определить какой из серверов главный
mainI := 0;
for i := 0 to self.SQLServers.Count - 1 do
if self.SQLServers[i].Server = self.MainSQLServer then
mainI := i;
//создать подключение на базе ADOCon
ADOCon.ConnectionString := Format('Provider=SQLOLEDB.1;Data Source=%s;Initial Catalog=%s;', [self.MainSQLServer, 'OIK']);
if self.SQLServers[mainI].WinAuth then
ADOCon.ConnectionString := ADOCon.ConnectionString + 'Integrated Security=SSPI;'
else
ADOCon.ConnectionString := ADOCon.ConnectionString + Format('User ID=%s;Password=%s;', [self.SQLServers[mainI].Login, self.SQLServers[mainI].Pas]);
ADOCon.LoginPrompt := false;
ADOCon.ConnectionTimeout := self.TimeOut;
//подключение к серверу
try
ADOCon.Open;
sConnected := ADOCon.Connected;
except
sConnected := false;
end;
end;
Result := sConnected;
end;
procedure TCK7Data.CloseConnection();
begin
if ADOCon.Connected then ADOCon.Close;
end;
//______________ Get Data ________________________________________________
function TCK7Data.GetArrayValueTI_Sync(ti: Integer; cat: TCategoryTI; lena: TLengthArrayTI; date1: TDateTime): TOutCKDataArray;
begin
Result := GetArrayValueTI_Sync(ti,cat,lena,date1,date1+1);
end;
function TCK7Data.GetArrayValueTI_Sync(ti: Integer; cat: TCategoryTI; lena: TLengthArrayTI; date1, date2: TDateTime): TOutCKDataArray;
var
step: Integer;
Query: TADOStoredProc;
i: Integer;
begin
{
Получение данных за интервал времени с определённым шагом (локальное время)
exec @i= [OIK].[dbo].StepLt 'H','4581,1015', '20101116 0:00:00',0, '20101116 10:00:00',0,3600,0
4,6 параметры нудны на момент перехода времени
}
Result := nil;
if lena = ckTI24 then step := 60*60 else step := 60*30;
if self.Connected then
begin
Query := TADOStoredProc.Create(nil);
try
Query.Connection := self.ADOCon;
Query.ProcedureName := 'StepLt';
Query.Parameters.CreateParameter('@Cat', ftString, pdInput, 2, System.Chr(Byte(cat)));
Query.Parameters.CreateParameter('@Ids', ftString, pdInput, 300, IntToStr(ti));
Query.Parameters.CreateParameter('@Start', ftDate, pdInput, 0, date1);
Query.Parameters.CreateParameter('@StartIsSummer', ftInteger, pdInput, 0, 0);
Query.Parameters.CreateParameter('@Stop', ftDate, pdInput, 0, date2);
Query.Parameters.CreateParameter('@StopIsSummer', ftInteger, pdInput, 0, 0);
Query.Parameters.CreateParameter('@Step', ftInteger, pdInput, 0, step);
Query.Parameters.CreateParameter('@ShowSystemTime', ftInteger, pdInput, 0, 0);
Query.Prepared := True;
Query.CommandTimeout := self.TimeOut;
try
Query.Open();
if Query.RecordCount > 0 then
SetLength(Result, Query.RecordCount);
i:=0;
while (not Query.EOF) do
begin
Result[i].TStamp := Query.FieldByName('timeLt').AsDateTime;
Result[i].Value := Query.FieldByName('value').AsFloat;
Result[i].Prizn := Query.FieldByName('QC').AsInteger;
{
Query.FieldByName('id').AsInteger;
Query.FieldByName('timeLt').AsDateTime;
Query.FieldByName('LtType').AsInteger;
Query.FieldByName('value').AsFloat;
Query.FieldByName('QC').AsInteger;
Query.FieldByName('time2Lt').AsDateTime;
Query.FieldByName('LtType2').AsInteger;
}
Query.Next;
Inc(i);
end;
// убираем полночь следующего дня
if Length(Result)>1 then
SetLength(Result,Length(Result)-1);
except
Result := nil;
end;
finally
if Query.Active then Query.Close();
Query.Free
end;
end;
end;
function TCK7Data.GetArrayValueTI_Sync(ti: TTIArray; lena: TLengthArrayTI; date1: TDateTime): TOutCKDataArrayManyTI;
begin
Result := GetArrayValueTI_Sync(ti,lena,date1,date1+1);
end;
function TCK7Data.GetArrayValueTI_Sync(ti: TTIArray; lena: TLengthArrayTI; date1, date2: TDateTime): TOutCKDataArrayManyTI;
var
dt: TDateTime;
i: Integer;
begin
if date1 > date2 then
begin
dt := date1;
date1 := date2;
date2 := dt;
end;
Result := nil;
if (ti = nil) or (Length(ti)<1) then
Exit;
SetLength(Result,Length(ti));
for i:=0 to Length(ti)-1 do
Result[i] := GetArrayValueTI_Sync(ti[i].Id, ti[i].Cat, lena, date1, date2);
end;
//________________ TCK7SQLServerList _________________________________________
constructor Tck7SQLServer.Create(sServer: string);
begin
Server := sServer;
WinAuth := true;
end;
constructor Tck7SQLServer.Create(Sserver: string; sLogin: string; sPas: string);
begin
Server := sServer;
WinAuth := false;
Login := sLogin;
Pas := sPas;
end;
procedure Tck7SQLServerList.Clear();
var
i: Integer;
begin
for i := 0 to Count - 1 do
Items[i].Free;
inherited;
end;
function Tck7SQLServerList.Get(Index: Integer): Tck7SQLServer;
begin
Result:=Tck7SQLServer(inherited Get(Index));
end;
procedure Tck7SQLServerList.Put(Index: Integer; const Value: Tck7SQLServer);
begin
inherited Put(Index, Value);
end;
// _________ Output function _________________________________________________
function DtToStr(dt: TDateTime; frm: string = 'dd.mm.yyyy hh:nn:ss'): string;
begin
Result := FormatDateTime(frm, dt);
end;
function ValueToStr(val: Double; frm: string = '%f'): string;
begin
Result := Format(frm, [val]);
end;
function PriznToHexStr(prz: Integer): string;
begin
Result := '0x' + IntToHex(prz, 8);
end;
function PriznToStr(prz: Integer): string;
begin
{
00 000 001 - недостоверность: дребезг ТС
00 000 002 - источник: ручной ввод с блокировкой ТМ
00 000 202 - источник: ручной ввод без блокировки
00 000 004 - недостоверность: недоверие ТМ
00 000 008 - недостоверность: ПНУ
00 000 010 - источник: расчёт
00 000 030 - недостоверность: параметры функции
00 000 040 - источник: внешняя система
00 000 080 - недостоверность: сбой телеметрии
00 000 100 - источник: телеметрия
00 000 200 - недостоверность: необновление
00 000 400 - недостоверность: сбой расчета
00 000 800 - недостоверность: по дублю
00 001 000 - недостоверность: нарушение физ. границ
00 002 000 - недостоверность: по оценке состояния
00 008 000 - нет данных
00 010 000 - нарушение: нижний аварийный
00 020 000 - нарушение: верхний предупредительный
00 040 000 - нарушение: нижний предупредительный
00 080 000 - замена: отчетной информацией
00 100 000 - замена: дублем
00 200 000 - нарушение: верхний аварийный
00 800 000 - недостоверность: скачок
01 000 000 - замена: принудительная
04 000 000 - источник: технологическая задача
08 000 000 - недостоверность: подозрение на скачок
10 000 000 - источник: данные АСКУЭ
20 000 000 - источник: обнуление
40 000 000 - источник: повтор предыдущего значения
}
if PriznToHexStr(prz) = '0x00000001' then
Result := 'недостоверность: дребезг ТС'
else if PriznToHexStr(prz) = '0x00000002' then
Result := 'источник: ручной ввод с блокировкой ТМ'
else if PriznToHexStr(prz) = '0x00000202' then
Result := 'источник: ручной ввод без блокировки'
else if PriznToHexStr(prz) = '0x00000004' then
Result := 'недостоверность: недоверие ТМ'
else if PriznToHexStr(prz) = '0x00000008' then
Result := 'недостоверность: ПНУ'
else if PriznToHexStr(prz) = '0x00000010' then
Result := 'источник: расчёт'
else if PriznToHexStr(prz) = '0x00000030' then
Result := 'недостоверность: параметры функции'
else if PriznToHexStr(prz) = '0x00000040' then
Result := 'источник: внешняя система'
else if PriznToHexStr(prz) = '0x00000080' then
Result := 'недостоверность: сбой телеметрии'
else if PriznToHexStr(prz) = '0x00000100' then
Result := 'источник: телеметрия'
else if PriznToHexStr(prz) = '0x00000200' then
Result := 'недостоверность: необновление'
else if PriznToHexStr(prz) = '0x00000400' then
Result := 'недостоверность: сбой расчета'
else if PriznToHexStr(prz) = '0x00000800' then
Result := 'недостоверность: по дублю'
else if PriznToHexStr(prz) = '0x00001000' then
Result := 'недостоверность: нарушение физ. границ'
else if PriznToHexStr(prz) = '0x00002000' then
Result := 'недостоверность: по оценке состояния'
else if PriznToHexStr(prz) = '0x00008000' then
Result := 'нет данных'
else if PriznToHexStr(prz) = '0x00010000' then
Result := 'нарушение: нижний аварийный'
else if PriznToHexStr(prz) = '0x00020000' then
Result := 'нарушение: верхний предупредительный'
else if PriznToHexStr(prz) = '0x00040000' then
Result := 'нарушение: нижний предупредительный'
else if PriznToHexStr(prz) = '0x00080000' then
Result := 'замена: отчетной информацией'
else if PriznToHexStr(prz) = '0x00100000' then
Result := 'замена: дублем'
else if PriznToHexStr(prz) = '0x00200000' then
Result := 'нарушение: верхний аварийный'
else if PriznToHexStr(prz) = '0x00800000' then
Result := 'недостоверность: скачок'
else if PriznToHexStr(prz) = '0x01000000' then
Result := 'замена: принудительная'
else if PriznToHexStr(prz) = '0x04000000' then
Result := 'источник: технологическая задача'
else if PriznToHexStr(prz) = '0x08000000' then
Result := 'недостоверность: подозрение на скачок'
else if PriznToHexStr(prz) = '0x10000000' then
Result := 'источник: данные АСКУЭ'
else if PriznToHexStr(prz) = '0x20000000' then
Result := 'источник: обнуление'
else if PriznToHexStr(prz) = '0x40000000' then
Result := 'источник: повтор предыдущего значения'
else
Result := PriznToHexStr(prz);
end;
function PriznNoData(prz: Integer): Boolean;
begin
Result := PriznToHexStr(prz) = '0x00008000';
end;
function NumToCat(i: Byte): TCategoryTI;
begin
case i of
1: Result := ckTI;
2: Result := ckTS;
3: Result := ckIIS;
4: Result := ckSV;
5: Result := ckPL;
6: Result := ckEI;
7: Result := ckSP;
8: Result := ckPV;
9: Result := ckFTI;
10: Result := ckMSK;
11: Result := ckTIS;
12: Result := ckTSS;
13: Result := ckPCHAS;
14: Result := ckCHAS;
15: Result := ckSYT;
else Result := ckTI;
end;
end;
function CatToNum(cat: TCategoryTI): Byte;
begin
case cat of
ckTI: Result := 1;
ckTS: Result := 2;
ckIIS: Result := 3;
ckSV: Result := 4;
ckPL: Result := 5;
ckEI: Result := 6;
ckSP: Result := 7;
ckPV: Result := 8;
ckFTI: Result := 9;
ckMSK: Result := 10;
ckTIS: Result := 11;
ckTSS: Result := 12;
ckPCHAS: Result := 13;
ckCHAS: Result := 14;
ckSYT: Result := 15;
else Result := 1;
end;
end;
//-------------------------------------------------------------------
function GetMaxAndHour(arr: TOutCKDataArray): string;
var
ValueMax: Double;
i: Integer;
begin
Result:='';
if Length(arr) >= 1 then
begin
ValueMax := arr[0].Value;
Result := FloatToStr(arr[0].Value) + ' ('+ DtToStr(arr[0].TStamp,'hh:nn') + ')';
for i:=0 to Length(arr)-1 do
if (not PriznNoData(arr[i].Prizn)) and ((arr[i].Value > ValueMax) or (ValueMax = MinDouble)) then
begin
ValueMax := arr[i].Value;
Result := FloatToStr(arr[i].Value) + ' ('+ DtToStr(arr[i].TStamp,'hh:nn') + ')';
end;
end;
end;
function GetMaxAndHour(arr: TOutCKDataArrayManyTI): TStringArray;
var
i: Integer;
begin
Result := nil;
if Length(arr) >= 1 then
begin
SetLength(Result, Length(arr));
for i:=0 to Length(arr)-1 do
Result[i] := GetMaxAndHour(arr[i]);
end;
end;
function GetMinAndHour(arr: TOutCKDataArray): string;
var
ValueMin: Double;
i: Integer;
begin
Result:='';
if Length(arr) >= 1 then
begin
ValueMin := arr[0].Value;
Result := FloatToStr(arr[0].Value) + ' ('+ DtToStr(arr[0].TStamp,'hh:nn') + ')';
for i:=0 to Length(arr)-1 do
if (not PriznNoData(arr[i].Prizn)) and ((arr[i].Value < ValueMin) or (ValueMin = MaxDouble)) then
begin
ValueMin := arr[i].Value;
Result := FloatToStr(arr[i].Value) + ' ('+ DtToStr(arr[i].TStamp,'hh:nn') + ')';
end;
end;
end;
function GetMinAndHour(arr: TOutCKDataArrayManyTI): TStringArray;
var
i: Integer;
begin
Result := nil;
if Length(arr) >= 1 then
begin
SetLength(Result, Length(arr));
for i:=0 to Length(arr)-1 do
Result[i] := GetMinAndHour(arr[i]);
end;
end;
function GetAvg(arr: TOutCKDataArray): Double;
var
count, i: Integer;
begin
Result := 0;
count := 0;
if Length(arr) >= 1 then
for i:= 0 to Length(arr)-1 do
if not PriznNoData(arr[i].Prizn) then
begin
Result := Result + arr[i].Value;
Inc(count);
end;
if count > 0 then
Result := Result / count;
end;
function GetAvg(arr: TOutCKDataArrayManyTI): TDoubleArray;
var
i: Integer;
begin
Result := nil;
if Length(arr) >= 1 then
begin
SetLength(Result, Length(arr));
for i:=0 to Length(arr)-1 do
Result[i] := GetAvg(arr[i]);
end;
end;
function GetSum(arr: TOutCKDataArray): Double;
var
i: Integer;
begin
Result := 0;
if Length(arr) >= 1 then
for i:=0 to Length(arr)-1 do
if not PriznNoData(arr[i].Prizn) then
Result := Result + arr[i].Value;
end;
function GetSum(arr: TOutCKDataArrayManyTI): TDoubleArray;
var
i: Integer;
begin
Result := nil;
if Length(arr) >= 1 then
begin
SetLength(Result, Length(arr));
for i:=0 to Length(arr)-1 do
Result[i] := GetSum(arr[i]);
end;
end;
procedure RoundArray(var arr: TOutCKDataArray; countsign: Byte);
var
i: Integer;
begin
if Length(arr) >= 1 then
for i:=0 to Length(arr)-1 do
arr[i].Value:=Math.RoundTo(arr[i].Value,-countsign);
end;
procedure RoundArray(var arr: TOutCKDataArrayManyTI; countsign: Byte);
var
i: Integer;
begin
if Length(arr) >= 1 then
for i:=0 to Length(arr)-1 do
RoundArray(arr[i],countsign);
end;
end.
|
unit BarGraphVCL;
interface
uses
Classes, Graphics, Controls, ExtCtrls, Windows, Generics.Collections, Math;
type
TBarItem = class(TShape)
public
constructor Create(AOwner: TComponent); override;
end;
TBarList = TObjectlist<TBarItem>;
TBarGraph = class(TCustomPanel)
private
FBarList: TBarList;
FColors: array [0 .. 255] of TColor;
FMax: Integer;
FColor2: TColor;
FColor1: TColor;
FMin: Integer;
FQuantity: Integer;
FPosition: Integer;
procedure SetColor1(const Value: TColor);
procedure SetColor2(const Value: TColor);
procedure SetMax(const Value: Integer);
procedure SetMin(const Value: Integer);
procedure SetPosition(const Value: Integer);
procedure SetQuantity(const Value: Integer);
protected
procedure Rebuild;
procedure ComputeColors;
procedure ApplyColors;
procedure UpdatePosition;
procedure UpdateSize;
procedure Loaded; override;
procedure Resize; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Min: Integer read FMin write SetMin default 1;
property Max: Integer read FMax write SetMax default 10;
property Position: Integer read FPosition write SetPosition;
property Color1: TColor read FColor1 write SetColor1 default clBlack;
property Color2: TColor read FColor2 write SetColor2 default clWhite;
property Quantity: Integer read FQuantity write SetQuantity default 2;
property ParentBackground;
property Color;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Samples', [TBarGraph]);
end;
{ TBarItem }
constructor TBarItem.Create(AOwner: TComponent);
begin
inherited;
// Pen.Style := psClear;
end;
{ TBarGraph }
constructor TBarGraph.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FMin := 1;
FMax := 10;
FColor1 := clBlack;
FColor2 := clWhite;
FQuantity := 2;
BevelOuter := bvNone;
Caption := '';
FBarList := TBarList.Create;
Rebuild;
end;
destructor TBarGraph.Destroy;
begin
FBarList.Free;
inherited;
end;
procedure TBarGraph.Loaded;
begin
inherited;
UpdateSize;
UpdatePosition
end;
procedure TBarGraph.Rebuild;
var
i: Integer;
BarItem: TBarItem;
begin
FBarList.Clear;
for i := FMin + 1 to FMax do
begin
BarItem := TBarItem.Create(Self);
BarItem.Parent := Self;
FBarList.Add(BarItem);
end;
ComputeColors;
end;
procedure TBarGraph.Resize;
begin
inherited;
UpdateSize;
end;
procedure TBarGraph.UpdateSize;
var
i, NewLeft: Integer;
begin
NewLeft := 0;
for i := 0 to FBarList.Count - 1 do
begin
FBarList[i].Height := Height div FBarList.Count * (i + 1);
FBarList[i].Width := Width div FBarList.Count;
FBarList[i].Left := NewLeft;
FBarList[i].Top := Height - FBarList[i].Height;
NewLeft := NewLeft + FBarList[i].Width;
end;
end;
procedure TBarGraph.ApplyColors;
var
i: Integer;
ColorIndex: Integer;
begin
for i := 0 to FBarList.Count - 1 do
begin
ColorIndex := (i + 1) * 255 div FBarList.Count;
ColorIndex := Math.Min(255, ColorIndex);
ColorIndex := Math.Max(0, ColorIndex);
FBarList[i].Brush.Color := FColors[ColorIndex];
FBarList[i].Pen.Color := FColors[ColorIndex];
end;
end;
function RGBToColor(R, G, B: Byte): TColor;
begin
Result := B shl 16 or G shl 8 or R;
end;
procedure TBarGraph.ComputeColors;
var
dRed, dGreen, dBlue: Integer;
RGBColor1, RGBColor2: TColor;
RGB1, RGB2: TRGBQuad;
i: Integer;
rgbRed, rgbGreen, rgbBlue: Byte;
begin
RGBColor1 := ColorToRGB(Color1);
RGBColor2 := ColorToRGB(Color2);
RGB1.rgbRed := GetRValue(RGBColor1);
RGB1.rgbGreen := GetGValue(RGBColor1);
RGB1.rgbBlue := GetBValue(RGBColor1);
RGB1.rgbReserved := 0;
RGB2.rgbRed := GetRValue(RGBColor2);
RGB2.rgbGreen := GetGValue(RGBColor2);
RGB2.rgbBlue := GetBValue(RGBColor2);
RGB2.rgbReserved := 0;
dRed := RGB2.rgbRed - RGB1.rgbRed;
dGreen := RGB2.rgbGreen - RGB1.rgbGreen;
dBlue := RGB2.rgbBlue - RGB1.rgbBlue;
for i := 0 to 255 do
begin
rgbRed := RGB1.rgbRed + (i * dRed) div 255;
rgbGreen := RGB1.rgbGreen + (i * dGreen) div 255;
rgbBlue := RGB1.rgbBlue + (i * dBlue) div 255;
FColors[i] := RGBToColor(rgbRed, rgbGreen, rgbBlue);
end;
ApplyColors;
UpdatePosition;
end;
procedure TBarGraph.UpdatePosition;
var
i: Integer;
begin
for i := 0 to FBarList.Count - 1 do
begin
FBarList[i].Visible := (FMin + i < FPosition);
end;
end;
procedure TBarGraph.SetColor1(const Value: TColor);
begin
FColor1 := Value;
ComputeColors;
end;
procedure TBarGraph.SetColor2(const Value: TColor);
begin
FColor2 := Value;
ComputeColors;
end;
procedure TBarGraph.SetMax(const Value: Integer);
begin
FMax := Value;
Rebuild;
end;
procedure TBarGraph.SetMin(const Value: Integer);
begin
FMin := Value;
Rebuild;
end;
procedure TBarGraph.SetPosition(const Value: Integer);
begin
if FPosition <> Value then
begin
FPosition := Value;
UpdatePosition;
end;
end;
procedure TBarGraph.SetQuantity(const Value: Integer);
begin
FQuantity := Value;
Rebuild;
end;
end.
|
(*
this file is a part of audio components suite v 2.3.
copyright (c) 2002-2005 andrei borovsky. all rights reserved.
see the license file for more details.
you can contact me at mail@z0m3ie.de
*)
unit acs_procs;
interface
uses
SysUtils, ACS_Types, Math;
type
TAcsFilterWindowType = (fwHamming, fwHann, fwBlackman);
TWindowFunction = (wf_None, wf_Hamming, wf_Blackman, wf_KaiserBessel, wf_FlatTop);
{$IFDEF LINUX}
function FindLibs(const Pattern: String): String;
{$ENDIF}
{$ifdef CPU386}
{.$define USE_ASM}
{$endif}
procedure Windowing(var data: array of double; Taps: integer; WF: TWindowFunction);
procedure FFT(var data: array of double; nn: integer; invers: boolean);
// Fast Fourier Transformation for Complex array
// Direction = 1 - forward FFT, Direction = -1 - inverse FFT.
procedure ComplexFFT(var Data: TAcsArrayOfComplex; Direction: Integer);
// The Hann function window
procedure FillHanningWindow(out OutData: TAcsArrayOfDouble; Width: Integer);
procedure FillHammingWindow(out OutData: TAcsArrayOfDouble; Width: Integer);
procedure BlackmanWindow(out OutData: TAcsArrayOfDouble; Width: Integer; Symmetric: Boolean);
procedure CalculateSincKernel(out OutData: TAcsArrayOfDouble; CutOff: Double; Width: Integer; WType: TAcsFilterWindowType);
// not used
procedure SmallIntArrayToDouble(InData: PSmallInt; OutData: PDouble; DataSize: Integer);
// not used
procedure SmallIntArrayToComplex(InData: PSmallInt; OutData: PAcsComplex; DataSize: Integer);
// Computes Data1[i] = Data1[i] * Data2[i], i = [0..DataSize-1]
procedure MultDoubleArrays(var Data1: TAcsArrayOfDouble; const Data2: TAcsArrayOfDouble; DataSize: Integer);
// Magnitude = sqrt(Re^2 + Im^2)
function Magnitude(const Re, Im: Double): Double;
// Amplitude = Log10(Magnitude)
function Amplitude(const Re, Im: Double): Double;
(*
Amplitude
/
| Lg(Abs(InData[i])) + Shift, if Lg(Abs(InData[i])) + Shift >= 0
OutData[i] = < 0, if Lg(Abs(InData[i])) + Shift < 0
| 0, if Abs(InData[i]) = 0.
\
i = [0..DataSize-1]
*)
procedure LgAmplitude(const InData: TAcsArrayOfComplex; out OutData: TAcsArrayOfDouble; DataSize, Shift: Integer);
implementation
{$IFDEF LINUX}
function FindLibs(const Pattern: String): String;
function FindInPath(sPath: string): string;
var
SR: TSearchRec;
begin
Result:='';
if FindFirst(sPath+Pattern, faAnyFile, SR) = 0 then
begin
Result := sPath+SR.Name;
FindClose(SR);
end;
end;
begin
Result:=FindInPath('/usr/lib/');
if Result = '' then Result:=FindInPath('/usr/lib/i386-linux-gnu/');
if Result = '' then Result:=FindInPath('/usr/lib/x86_64-linux-gnu/');
if Result = '' then Result:=FindInPath('/usr/local/lib/');
end;
{$ENDIF}
(* This routine is converted from the original C code by P. Burke
Direction = 1 - forward FFT, Direction = -1 - inverse FFT. *)
procedure ComplexFFT(var Data: TAcsArrayOfComplex; Direction: Integer);
var
i, i1, j, m, l, l1, l2, Log2n: Integer;
c1, c2, tr, ti, t1, t2, u1, u2, z: Double;
DataSize: Integer;
begin
DataSize := Length(Data);
Log2n := Trunc(Log2(DataSize));
// Do the bit reversal
j := 1;
for i:=0 to DataSize-1 do
begin
if (j < DataSize) and (i < j) then
begin
tr := Data[i].Re;
ti := Data[i].Im;
Data[i].Re := Data[j].Re;
Data[i].Im := Data[j].Im;
Data[j].Re := tr;
Data[j].Im := ti;
end;
m := DataSize div 2;
while (m >= 2) and (j > m) do
begin
Dec(j, m);
m := (m div 2);
end;
Inc(j, m);
end;
// Compute the FFT
c1 := -1.0;
c2 := 0.0;
l2 := 1;
for l := 0 to Log2n - 1 do
begin
l1 := l2;
l2 := (l2 shl 1);
u1 := 1.0;
u2 := 0.0;
for j:=0 to l1 - 1 do
begin
i := j;
while (i + l1) < DataSize do
begin
i1 := i + l1;
t1 := u1 * Data[i1].Re - u2 * Data[i1].Im;
t2 := u1 * Data[i1].Im + u2 * Data[i1].Re;
Data[i1].Re := Data[i].Re - t1;
Data[i1].Im := Data[i].Im - t2;
Data[i].Re := Data[i].Re + t1;
Data[i].Im := Data[i].Im + t2;
Inc(i, l2);
end;
z := u1*c1 - u2*c2;
u2 := u1*c2 + u2*c1;
u1 := z;
end;
c2 := Sqrt((1.0 - c1) / 2.0);
if Direction = 1 then
c2 := -c2;
c1 := Sqrt((1.0 + c1) / 2.0);
end;
// Scaling for forward transform
if Direction = 1 then
for i:=0 to DataSize-1 do
begin
Data[i].Re := Data[i].Re / DataSize;
Data[i].Im := Data[i].Im / DataSize;
end;
end;
procedure Windowing(var data: array of double; Taps: integer; WF: TWindowFunction);
var i:integer;
begin
for i:=0 to high(data) do
case WF of
wf_None : ;
wf_Hamming : data[i]:=data[i]*(0.54-0.46*cos((i*2*PI)/Taps));
wf_Blackman : data[i]:=data[i]*(0.42-0.5*cos((i*2*PI)/Taps)+0.08*cos((i*4*PI)/Taps));
wf_KaiserBessel : data[i]:=data[i]*(0.4021-0.4986*cos((i*2*PI)/Taps)+0.0981*cos((i*4*PI)/Taps)-0.0012*cos((i*6*PI)/Taps));
wf_FlatTop : data[i]:=data[i]*(0.2155-0.4159*cos((i*2*PI)/Taps)+0.2780*cos((i*4*PI)/Taps)-0.0836*cos((i*6*PI)/Taps)+0.0070*cos((i*8*PI)/Taps));
end;//case
end;
procedure four(data: array of Real; isign: Integer);
var tmpdata : array of Real;
alpha, beta, theta,
temp,sw,cw : double;
i,j,Count : integer;
begin
Count:=length(data);
setlength(tmpdata,2*Count);
//ZeroMemory(tmpdata,sizeof(tmpdata));
for i := 0 to Length(tmpdata) do
tmpdata[i] := 0;
for i:=0 to Count-1 do
begin
theta:=isign*2.0*PI*(i/Count);
temp:=sin(0.5*theta);
alpha:=2.0*sqr(temp);
beta:=sin(theta);
cw:=1.0;
sw:=0.0;
for j:=0 to Count-1 do
begin
tmpdata[2*i]:=tmpdata[2*i]+(cw*data[2*j]-sw*data[2*j+1]);
tmpdata[2*i+1]:=tmpdata[2*i+1]+(cw*data[2*j+1]+sw*data[2*j]);
// cw:=(temp=cw)-(alpha*cw+beta*sw);
sw:=sw-(alpha*sw-beta*temp);
end;
end;
if (isign=-1) then
begin
for i:=0 to 2*Count-1 do tmpdata[i]:=tmpdata[i]/Count;
end;
for i:=0 to 2*Count-1 do data[i]:=tmpdata[i];
setlength(tmpdata,0);
end;
procedure DFT(data: array of Real; isign: integer);
var i,i1,i2,i3,i4,np3, Count : integer;
c1,c2,h1r,h2r,h1i,h2i : Real;
wr,wi,wpr,wpi,wtemp,theta : Real;
begin
Count:=length(data);
if (Count mod 4<>0) then raise EMathError.Create('Fehler in DFT (N kein Vielfaches von 4)');
c1:=0.5;
theta:=PI/(Count/2);
if (isign=1) then
begin
c2:=-0.5;
four(data,1);
end else
begin
c2:=0.5;
theta:=-theta;
end;
wtemp:=sin(0.5*theta);
wpr:=-2.0*wtemp*wtemp;
wpi:=sin(theta);
wr:=1.0+wpr;
wi:=wpi;
np3:=Count+3;
for i:=2 to Count div 4 do
begin
// i4:=1+(i3=np3-(i2=1+(i1=i+i-1)));
h1r:=c1*(data[i1]+data[i3]);
h1i:=c1*(data[i2]-data[i4]);
h2r:=-c2*(data[i2]+data[i4]);
h2i:=c2*(data[i1]-data[i3]);
data[i1]:=h1r+wr*h2r-wi*h2i;
data[i2]:= h1i+wr*h2i+wi*h2r;
data[i3]:= h1r-wr*h2r+wi*h2i;
data[i4]:=-h1i+wr*h2i+wi*h2r;
// wr:=(wtemp=wr)*wpr-wi*wpi+wr;
wi:=wi*wpr+wtemp*wpi+wi;
end;
if (isign=1) then
begin
// data[1]:=(h1r=data[1])+data[2];
data[2]:=h1r-data[2];
end else
begin
// data[1]:=c1*((h1r=data[1])+data[2]);
data[2]:=c1*(h1r-data[2]);
four(data,-1);
end;
end;
procedure SWAP(var a, b:double);
var temp:double;
begin
temp:=(a);
a:=b;
b:=temp;
end;
procedure FFT(var data: array of double; nn: integer; invers: boolean);
(* Programs using routine FOUR1 must define type
TYPE
gldarray = ARRAY [1..nn2] OF real;
in the calling routine, where nn2=nn+nn. *)
var ii,jj,n,mmax,m,j,istep,i: integer;
wtemp,wr,wpr,wpi,wi,theta: double;
tempr,tempi: real;
begin
n := 2*nn;
j := 1;
for ii := 1 to nn do
begin
i := 2*ii-1;
if (j > i) then
begin
tempr := data[j];
tempi := data[j+1];
data[j] := data[i];
data[j+1] := data[i+1];
data[i] := tempr;
data[i+1] := tempi
end;
m := n div 2;
while ((m >= 2) and (j > m)) do
begin
j := j-m;
m := m div 2
end;
j := j+m
end;
mmax := 2;
while (n > mmax) do
begin
istep := 2*mmax;
if invers then
theta := 6.28318530717959/mmax else
theta := 6.28318530717959/-mmax;
wpr := -2.0*sqr(sin(0.5*theta));
wpi := sin(theta);
wr := 1.0;
wi := 0.0;
for ii := 1 to (mmax div 2) do
begin
m := 2*ii-1;
for jj := 0 to ((n-m) div istep) do
begin
i := m + jj*istep;
j := i+mmax;
tempr := real(wr)*data[j]-real(wi)*data[j+1];
tempi := real(wr)*data[j+1]+real(wi)*data[j];
data[j] := data[i]-tempr;
data[j+1] := data[i+1]-tempi;
data[i] := data[i]+tempr;
data[i+1] := data[i+1]+tempi
end;
wtemp := wr;
wr := wr*wpr-wi*wpi+wr;
wi := wi*wpr+wtemp*wpi+wi
end;
mmax := istep
end;
end;
procedure FillHanningWindow(out OutData: TAcsArrayOfDouble; Width: Integer);
var
i, n: Integer;
begin
SetLength(OutData, Width);
if Width <= 0 then
Exit;
n := Width-1;
OutData[0] := 0.5 * (1 + cos((TwoPi * Width) / n));
for i := 1 to Width-1 do
OutData[i] := 0.5 * (1 - cos((TwoPi * Width) / n));
end;
procedure FillHammingWindow(out OutData: TAcsArrayOfDouble; Width: Integer);
var
i, n: Integer;
begin
SetLength(OutData, Width);
n := Width - 1;
for i := 1 to Width do
OutData[i-1] := 0.54 - 0.46 * Cos(TwoPi * i / n);
end;
procedure BlackmanWindow(out OutData: TAcsArrayOfDouble; Width: Integer; Symmetric: Boolean);
var
i, n: Integer;
begin
SetLength(OutData, Width);
if Symmetric then
n := Width - 1
else
n := Width;
for i := 0 to Width-1 do
OutData[i] := 0.42 - 0.5 * Cos(TwoPi * i / n) + 0.08 * Cos(2 * TwoPi * i / n);
end;
procedure CalculateSincKernel(out OutData: TAcsArrayOfDouble; CutOff: Double; Width: Integer; WType: TAcsFilterWindowType);
var
i: Integer;
Sinc: Double;
Window: TAcsArrayOfDouble;
begin
{ TODO : http://avisynth.nl/index.php/Resampling }
case WType of
fwHamming: FillHammingWindow(Window, Width);
fwHann: FillHanningWindow(Window, Width);
fwBlackman: BlackmanWindow(Window, Width, False);
end;
SetLength(OutData, Width);
Sinc := 0;
for i := 0 to Width-1 do
begin
if i-(Width shr 1) <> 0 then
OutData[i] := Sin(TwoPi * CutOff * (i-(Width shr 1))) / (i-(Width shr 1)) * Window[i]
else
OutData[i] := TwoPi * CutOff * Window[i];
Sinc := Sinc + OutData[i];
end;
for i := 0 to Width-1 do
OutData[i] := OutData[i] / Sinc;
end;
procedure SmallIntArrayToDouble(InData: PSmallInt; OutData: PDouble; DataSize: Integer);
begin
{$ifdef USE_ASM}
asm
MOV EDX, DataSize;
SHL EDX, 3;
MOV ECX, OutData;
ADD EDX, ECX;
MOV EAX, InData;
@test: CMP EDX, ECX;
JE @out;
FILD WORD[EAX];
ADD EAX, 2;
FSTP QWORD[ECX];
ADD ECX, 8;
JMP @test;
@out: ;
end;
{$ENDIF}
end;
procedure SmallIntArrayToComplex(InData: PSmallInt; OutData: PAcsComplex; DataSize: Integer);
begin
{$ifdef USE_ASM}
asm
MOV EDX, DataSize;
SHR EDX, 4;
MOV ECX, OutData;
ADD EDX, ECX;
MOV EAX, InData;
@test: CMP EDX, ECX;
JE @out;
FILD WORD[EAX];
ADD EAX, 2;
FSTP QWORD[EAX];
ADD ECX, 16;
JMP @test;
@out: ;
end;
{$ENDIF}
end;
procedure MultDoubleArrays(var Data1: TAcsArrayOfDouble; const Data2: TAcsArrayOfDouble; DataSize: Integer);
{$ifndef USE_ASM}
var
i: integer;
{$endif}
begin
DataSize := Length(Data2);
{$ifndef USE_ASM}
for i:=0 to DataSize-1 do
begin
Data1[i] := Data1[i] * Data2[i];
end;
{$else}
asm
MOV EDX, DataSize;
SHL EDX, 3; // DataSize * 8
MOV ECX, Data1[0]; // ECX = @Data1
ADD EDX, ECX; // EDX = @Data1 + (DataSize * 8)
MOV EAX, Data2[0]; // EAX = @Data2
@test: CMP EDX, ECX;
JE @out; // if @Data1 = EDX then Exit
FLD QWORD[ECX]; // load double from Data1
FLD QWORD[EAX]; // load double from Data2
FMUL; // multiply them
FSTP QWORD[EAX]; // save result to Data2
ADD ECX, 8; // next Data1
ADD EAX, 8; // next Data2
JMP @test;
@out: ;
end;
{$endif}
end;
function Magnitude(const Re, Im: Double): Double;
begin
Result := sqrt( power(abs(Re), 2) + power(abs(Im), 2) );
end;
function Amplitude(const Re, Im: Double): Double;
begin
Result := sqrt( power(abs(Re), 2) + power(abs(Im), 2) );
if Result > 0 then
Result := log10(Result);
end;
procedure LgAmplitude(const InData: TAcsArrayOfComplex; out OutData: TAcsArrayOfDouble;
DataSize, Shift: Integer);
var
LogBase: Double;
{$ifndef USE_ASM}
num: Double;
i: integer;
{$endif}
begin
DataSize := Length(InData);
SetLength(OutData, DataSize);
{$ifndef USE_ASM}
//LogBase := 1 / log2(10); // 0.3010299956639812
for i:=0 to DataSize-1 do
begin
OutData[i] := 0;
num := sqrt( power(abs(InData[i].Re), 2) + power(abs(InData[i].Im), 2) );
if num > 0 then
begin
num := log10(num) + Shift;
//num := num * log2(LogBase) + Shift; // log10 equivalent
//num := LogBase * log2(num) + Shift;
if num >= 0 then
OutData[i] := num;
end;
end;
{$else}
asm
FLD1; // st0 := 1.0
FLDL2T; // st1 <- st0, st0 := log2(10)
FDIVP ST(1), ST(0); // st0 := st1 / st0
FSTP LogBase; // LogBase := 1/log2(10)
MOV EDX, DataSize;
SHL EDX, 3; // DataSize * 8
MOV ECX, OutData[0]; // cx := @OutData
ADD EDX, ECX; // dx := @OutData + (DataSize*8)
MOV EAX, InData[0]; // ax := @InData.re
@test: CMP EDX, ECX;
JE @out;
FLD QWORD[EAX]; // st0 := InData.re
FABS ST(0); // abs(st0)
FMUL ST(0), ST(0); // st0 := st0 * st0 (st0 ^ 2)
ADD EAX, 8; // ax := InData.im
FLD QWORD[EAX]; // st1 := st0, st0 := @ax
FABS ST(0); // abs(st0)
FMUL ST(0), ST(0); // st0 := st0 * st0 (st0 ^ 2)
FADDP ST(1), ST(0); // st0 := st0 + st1
FSQRT; // st0 := sqrt(st0)
FTST; // test st0
PUSH EAX; // save ax
FSTSW AX; // status -> ax
SAHF; // ah -> flags
JE @skip; // if 0 goto @skip
FLD LogBase; // st1:=st0, st0 := LogBase
FXCH; // st0 <-> st1 (st1=LogBase)
FYL2X; // st0 := st1 * log2(st0)
FIADD Shift; // st0 := st0 + Shift
FTST; // test st0
FSTSW AX; // status -> ax
SAHF; // ah -> flags
JAE @skip; // >=0 -> @skip
FSTP QWORD[ECX]; // st0 -> @cx
FLDZ; // st0 := 0
@skip: POP EAX; // load ax
ADD EAX, 8; // next InData
FSTP QWORD[ECX]; // st0 -> @cx
ADD ECX, 8; // @cx+8
JMP @test; // goto @test
@out: ;
end;
{$endif}
end;
end.
|
//Delphi wrapper for Google Chrome's "pdf.dll" with GetPDFPageSizeByIndex()
//Wrote by Simon Kroik, 06.2013-03.2018
//Version 2.0
//Tested with Delphi 6
UNIT MyChromePDFRender;
INTERFACE
uses MyPDFRender, Windows, Classes, DB, Graphics, Types;
type
TChromePDFBufferSize = integer;
TMyChromePDFRender = class(TCustomMyPDFRender)
private
FBuffer : PChar;
FBufferSize : TChromePDFBufferSize;
FPagesCount : integer;
FMaxPageWidthCm : extended;
protected
procedure InitEmptyFields(); override;
function GetPagesCount(): integer; override;
function GetSizeInBytes(): int64; override;
procedure AssignTo(Dest: TPersistent); override;
public
procedure Clear(); override;
function SavePDFToStream(AStream: TStream): boolean; override;
function LoadPDFFromStream(AStream: TStream; ALength: int64=0): boolean; override;
function GetPageSizeInCm(APageNumber: integer;
var AWidthCm: extended;
var AHeightCm: extended): boolean; override;
function GetPageSizeInPixel(APageNumber: integer;
ADpiX: integer;
ADpiY: integer;
var AWidth: integer;
var AHeight: integer): boolean; override;
function RenderPDFToDC(ADC: HDC;
ARectLeft: integer;
ARectTop: integer;
ARectWidth: integer;
ARectHeight: integer;
APageNumber: integer;
ADpiX: integer;
ADpiY: integer;
ADoFitToBounds: boolean;
ADoStretchToBounds: boolean;
ADoKeepAspectRatio: boolean;
ADoCenterInBounds: boolean;
ADoAutoRotate: boolean): boolean; override;
public
property MaxPageWidthCm: extended read FMaxPageWidthCm;
end;
IMPLEMENTATION
uses SysUtils;
//##############################################################################
{ Utils }
//##############################################################################
//
// The "pdf.dll" has problems. For excample, LoadLibrary('pdf.dll') returns 0
// with the GetLastError() = 3221225614
//
// Hier found I the solution:
// http://stackoverflow.com/questions/3534572/delphi-loadlibrary-returns-0-lasterrorcde-3221225616-what-does-this-mean
//
// GetLastError() after LoadLibrary('pdf.dll') was "3221225614", not "3221225616"
// but the solution from StackOverflow.com also works.
//
// The error code, 3221225616, seems, when asking Google, to be the result of an
// invalid floating point operation. Now, this seems very technical; indeed, what
// does loading a library have to do with floating point computations?
// The floating point control word (CW) is a bitfield where the bits specify how
// the processor should handle floating-point errors; it is actually rather
// common that unexpected floating point errors can be dealt with by changing
// one of these bits to 1 (which by the way is the default state). For an other
// example, see this question of mine, in which I get a totally unexpected
// division by zero error, which is dealt with by setting the "div by zero" bit
// of the control word to 1.
//
// var
// SavedCW: word;
//
// ...
// SavedCW := Get8087CW;
// Set8087CW(SavedCW or $7);
// DLLHandle := LoadLibrary('3rdparty.dll');
// Set8087CW(SavedCW);
//
//------------------------------------------------------------------------------
const
LibName = 'pdf.dll';
type
TGraphicCracker = class(Graphics.TGraphic);
type
TGetPDFDocInfoProc = procedure(pdf_buffer : PChar;
buffer_size : integer;
page_count : PInt;
max_page_width : PDouble
); cdecl;
TGetPDFPageSizeByIndexFunc = function(pdf_buffer : PChar;
buffer_size : integer;
page_number : integer;
width : PDouble;
height : PDouble): BOOL; cdecl;
TRenderPDFPageToDCFunc = function(pdf_buffer : PChar;
buffer_size : integer;
page_number : integer;
dc : HDC;
dpi_x : integer;
dpi_y : integer;
bounds_origin_x : integer;
bounds_origin_y : integer;
bounds_width : integer;
bounds_height : integer;
fit_to_bounds : boolean;
stretch_to_bounds : boolean;
keep_aspect_ratio : boolean;
center_in_bounds : boolean;
autorotate : boolean
): BOOL; cdecl;
VAR
internal_hLib : THandle;
internal_procGetPDFDocInfo : TGetPDFDocInfoProc;
internal_funcGetPDFPageSizeByIndex : TGetPDFPageSizeByIndexFunc;
internal_funcRenderPDFPageToDC : TRenderPDFPageToDCFunc;
//------------------------------------------------------------------------------
procedure BeforeCallDLL(out ASavedCW: word);
begin
ASavedCW:=Get8087CW();
Set8087CW(ASavedCW or $7); //see infos after "IMPLEMENTATION"
end;
//------------------------------------------------------------------------------
procedure AfterCallDLL(const ASavedCW: word);
begin
Set8087CW(ASavedCW);
end;
//------------------------------------------------------------------------------
procedure FreeLib();
var
iSavedCW : word;
begin
if internal_hLib<>0 then
begin
BeforeCallDLL(iSavedCW);
try
try
FreeLibrary(internal_hLib);
finally
internal_hLib:=0;
end;
finally
AfterCallDLL(iSavedCW);
end;
end; //if internal_hLib<>0
end;
//------------------------------------------------------------------------------
procedure RaiseLibLoadingException(const AMessage: string);
begin
try
FreeLib();
finally
raise EMyPDFRendererError.Create(
'Library "'+LibName+'" is not correct loaded.'#13#10+AMessage
);
end;
end;
//------------------------------------------------------------------------------
function LoadLibIfNeed(): boolean;
var
iSavedCW : word;
iLastErr : DWORD;
begin
if internal_hLib=0 then
begin
BeforeCallDLL(iSavedCW);
try
internal_hLib:=LoadLibrary(LibName);
iLastErr:=GetLastError();
finally
AfterCallDLL(iSavedCW);
end;
if internal_hLib=0 then
RaiseLibLoadingException(SysErrorMessage(iLastErr))
else
begin
//-- GetPDFDocInfo --
@internal_procGetPDFDocInfo :=
GetProcAddress(internal_hLib, 'GetPDFDocInfo');
if not Assigned(@internal_procGetPDFDocInfo) then
RaiseLibLoadingException('function "GetPDFDocInfo" is not found.');
//-- GetPDFPageSizeByIndex --
@internal_funcGetPDFPageSizeByIndex :=
GetProcAddress(internal_hLib, 'GetPDFPageSizeByIndex');
if not Assigned(@internal_funcGetPDFPageSizeByIndex) then
RaiseLibLoadingException('function "GetPDFPageSizeByIndex" is not found.');
//-- RenderPDFPageToDC --
@internal_funcRenderPDFPageToDC :=
GetProcAddress(internal_hLib, 'RenderPDFPageToDC');
if not Assigned(@internal_funcRenderPDFPageToDC) then
RaiseLibLoadingException('function "RenderPDFPageToDC" is not found.');
// >>> not used Function from DLL: RenderPDFPageToBitmap()
end; //if internal_hLib<>0
end;
Result:=(internal_hLib<>0);
end;
//##############################################################################
{ TMyChromePDFRender }
//##############################################################################
function TMyChromePDFRender.GetPagesCount(): integer;
begin
Result:=FPagesCount;
end;
//------------------------------------------------------------------------------
function TMyChromePDFRender.GetSizeInBytes(): int64;
begin
Result:=FBufferSize;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TMyChromePDFRender.InitEmptyFields();
begin
inherited;
FBuffer:=nil;
FBufferSize:=0;
FPagesCount:=0;
FMaxPageWidthCm:=0;
end;
//------------------------------------------------------------------------------
procedure TMyChromePDFRender.Clear();
begin
inherited;
FreeMem(FBuffer);
InitEmptyFields();
end;
//------------------------------------------------------------------------------
procedure TMyChromePDFRender.AssignTo(Dest: TPersistent);
var
DstRender : TMyChromePDFRender;
begin
inherited;
if Dest is TMyChromePDFRender then
begin
DstRender:=TMyChromePDFRender(Dest);
DstRender.FBufferSize:=FBufferSize;
DstRender.FPagesCount:=FPagesCount;
DstRender.FMaxPageWidthCm:=FMaxPageWidthCm;
GetMem(DstRender.FBuffer, DstRender.FBufferSize);
Move(FBuffer^, DstRender.FBuffer^, DstRender.FBufferSize);
end;
end;
//------------------------------------------------------------------------------
function TMyChromePDFRender.SavePDFToStream(AStream: TStream): boolean;
begin
if FBufferSize>0 then
begin
AStream.Write(FBuffer^, FBufferSize);
Result:=true;
end
else
Result:=false;
end;
//------------------------------------------------------------------------------
function TMyChromePDFRender.LoadPDFFromStream(AStream: TStream;
ALength: int64): boolean;
var
iPDFSize : int64;
fMaxPageWidthPix72dpi : double; //for WEB
iSavedCW : word;
begin
if ALength>0 then
begin
iPDFSize:=ALength;
if AStream.Position+iPDFSize > AStream.Size then
raise EMyPDFRendererError.Create(
'Length-Parameter is over the stream size'
);
end
else
begin
iPDFSize:=AStream.Size - AStream.Position;
end;
if iPDFSize>High(TChromePDFBufferSize) then
raise EMyPDFRendererError.Create(
'PDF is too big: '+IntToStr(iPDFSize div (1024*1024))+' MB'
);
LoadLibIfNeed();
Clear();
FBufferSize:=iPDFSize;
GetMem(FBuffer, FBufferSize);
AStream.ReadBuffer(FBuffer^, FBufferSize);
BeforeCallDLL(iSavedCW);
try
internal_procGetPDFDocInfo(FBuffer,
FBufferSize,
@FPagesCount,
@fMaxPageWidthPix72dpi);
finally
AfterCallDLL(iSavedCW);
end;
FMaxPageWidthCm:=InchToCm(fMaxPageWidthPix72dpi/72.0);
Result:=true;
end;
////////////////////////////////////////////////////////////////////////////////
function TMyChromePDFRender.GetPageSizeInCm(APageNumber: integer;
var AWidthCm: extended; var AHeightCm: extended): boolean;
var
iSavedCW : word;
fWidthPix72dpi : double; //for WEB
fHeightPix72dpi : double; //for WEB
begin
LoadLibIfNeed();
RaiseIfPageNumberWrong(APageNumber);
BeforeCallDLL(iSavedCW);
try
// From: https://chromium.googlesource.com/chromium/src/+/master/pdf/pdf.h
//
// Gets the dimensions of a specific page in a document.
// |pdf_buffer| is the buffer that contains the entire PDF document to be
// rendered.
// |pdf_buffer_size| is the size of |pdf_buffer| in bytes.
// |page_number| is the page number that the function will get the dimensions
// of.
// |width| is the output for the width of the page in points.
// |height| is the output for the height of the page in points.
// Returns false if the document or the page number are not valid.
Result:=internal_funcGetPDFPageSizeByIndex(FBuffer, // pdf_buffer
FBufferSize, // buffer_size
APageNumber-1, // page_number
@fWidthPix72dpi, // width
@fHeightPix72dpi);// height
AWidthCm:=InchToCm(fWidthPix72dpi/72.0);
AHeightCm:=InchToCm(fHeightPix72dpi/72.0);
finally
AfterCallDLL(iSavedCW);
end;
end;
//------------------------------------------------------------------------------
function TMyChromePDFRender.GetPageSizeInPixel(APageNumber: integer;
ADpiX: integer; ADpiY: integer; var AWidth: integer;
var AHeight: integer): boolean;
var
iSavedCW : word;
fWidthPix72dpi : double; //for WEB
fHeightPix72dpi : double; //for WEB
begin
LoadLibIfNeed();
RaiseIfPageNumberWrong(APageNumber);
BeforeCallDLL(iSavedCW);
try
Result:=internal_funcGetPDFPageSizeByIndex(FBuffer, // pdf_buffer
FBufferSize, // buffer_size
APageNumber-1, // page_number
@fWidthPix72dpi, // width
@fHeightPix72dpi);// height
AWidth:=Round(fWidthPix72dpi/72.0*ADpiX);
AHeight:=Round(fHeightPix72dpi/72.0*ADpiY);
finally
AfterCallDLL(iSavedCW);
end;
end;
//------------------------------------------------------------------------------
function TMyChromePDFRender.RenderPDFToDC(ADC: HDC;
ARectLeft, ARectTop, ARectWidth, ARectHeight: integer; APageNumber: integer;
ADpiX, ADpiY: integer; ADoFitToBounds: boolean; ADoStretchToBounds: boolean;
ADoKeepAspectRatio: boolean; ADoCenterInBounds: boolean;
ADoAutoRotate: boolean): boolean;
var
iSavedCW : word;
begin
LoadLibIfNeed();
RaiseIfPageNumberWrong(APageNumber);
BeforeCallDLL(iSavedCW);
try
// From: https://chromium.googlesource.com/chromium/src/+/master/pdf/pdf.h
//
// |pdf_buffer| is the buffer that contains the entire PDF document to be
// rendered.
// |buffer_size| is the size of |pdf_buffer| in bytes.
// |page_number| is the 0-based index of the page to be rendered.
// |dc| is the device context to render into.
// |dpi_x| and |dpi_y| are the x and y resolutions respectively. If either
// value is -1, the dpi from the DC will be used.
// |bounds_origin_x|, |bounds_origin_y|, |bounds_width| and |bounds_height|
// specify a bounds rectangle within the DC in which to render the PDF
// page.
// |fit_to_bounds| specifies whether the output should be shrunk to fit the
// supplied bounds if the page size is larger than the bounds in any
// dimension. If this is false, parts of the PDF page that lie outside
// the bounds will be clipped.
// |stretch_to_bounds| specifies whether the output should be stretched to fit
// the supplied bounds if the page size is smaller than the bounds in any
// dimension.
// If both |fit_to_bounds| and |stretch_to_bounds| are true, then
// |fit_to_bounds| is honored first.
// |keep_aspect_ratio| If any scaling is to be done is true, this flag
// specifies whether the original aspect ratio of the page should be
// preserved while scaling.
// |center_in_bounds| specifies whether the final image (after any scaling is
// done) should be centered within the given bounds.
// |autorotate| specifies whether the final image should be rotated to match
// the output bound.
// Returns false if the document or the page number are not valid.
Result:=internal_funcRenderPDFPageToDC(FBuffer, // pdf_buffer
FBufferSize, // buffer_size
APageNumber-1, // page_number
ADC, // dc
ADpiX, // dpi_x
ADpiY, // dpi_y
ARectLeft, // bounds_origin_x
ARectTop, // bounds_origin_y
ARectWidth, // bounds_width
ARectHeight, // bounds_height
ADoFitToBounds, // fit_to_bounds
ADoStretchToBounds, // stretch_to_bounds
ADoKeepAspectRatio, // keep_aspect_ratio
ADoCenterInBounds, // center_in_bounds
ADoAutoRotate); // autorotate
finally
AfterCallDLL(iSavedCW);
end;
end;
////////////////////////////////////////////////////////////////////////////////
INITIALIZATION
internal_hLib:=0;
FINALIZATION
FreeLib();
END.
|
unit TestArchive_u;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ztvBase, ztvGbls, ztvZipCheck, Err_msgs, ztvRegister,
SignatureDetect_u, Advanced, LZMA_u, ArchView_u, StdCtrls, Buttons,
ComCtrls, Viewer_u;
type
TdlgTestArchive = class(TForm)
btnTest: TBitBtn;
btnCancel: TBitBtn;
lvResult: TListView;
pbArchive: TProgressBar;
procedure FormCreate(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure btnTestClick(Sender: TObject);
private
procedure UniCheckerOnProgress(Sender:TObject;ProgressByFile,ProgressByArchive:Byte);
procedure UniCheckerOnGetPass(Sender: TObject; FN: String;
Var Password: String; Var TryAgain: BOOLEAN);
procedure UniCheckOnStatus(Sender: TObject; FN: String; PassFail: BOOLEAN);
procedure UniCheckOnError(Sender: TObject; FN, MsgEx,
VolumeID: String; ECode: Integer);
procedure AddItem(FileName,State:String);
procedure MZFStatus(Sender:TObject;FileName:String; Failed:Boolean);
procedure MZFOnProgress(Sender:TObject;FProgress,AProgress:Byte;Var Abort:Boolean);
procedure MZFGetPass(Sender:TObject;Var Pass:ShortString);
{ Private declarations }
public
ArchiveFile:String;
ArcType:TFileType;
FileSpec:TStringList;
Abort:Boolean;
procedure CheckArchive;
{ Public declarations }
end;
var
dlgTestArchive: TdlgTestArchive;
implementation
{$R *.dfm}
procedure TdlgTestArchive.btnCancelClick(Sender: TObject);
begin
Abort:=True;
end;
procedure TdlgTestArchive.btnTestClick(Sender: TObject);
begin
btnTest.Enabled:=False;
pbArchive.Position:=0;
CheckArchive;
btnTest.Enabled:=True;
end;
procedure TdlgTestArchive.FormCreate(Sender: TObject);
begin
FileSpec:=TStringList.Create;
Abort:=False;
//
Caption:=ReadFromLanguage('Windows','wndCheckArchive',Caption);
btnTest.Caption:=ReadFromLanguage('Buttons','btnTest',btnTest.Caption);
btnCancel.Caption:=ReadFromLanguage('Buttons','btnCancel',btnCancel.Caption);
lvResult.Columns[0].Caption:=ReadFromLanguage('ListItems','liFile',lvResult.Columns[0].Caption);
lvResult.Columns[1].Caption:=ReadFromLanguage('ListItems','liType',lvResult.Columns[1].Caption);
lvResult.Columns[2].Caption:=ReadFromLanguage('ListItems','liStatus',lvResult.Columns[2].Caption);
end;
procedure TdlgTestArchive.AddItem(FileName: string; State: string);
var Item:TListItem;
begin
Item:=lvResult.Items.Add;
Item.Caption:=FileName;
Item.SubItems.Add(ExtractFileExt(FileName));
Item.SubItems.Add(State);
end;
procedure TdlgTestArchive.UniCheckerOnProgress(Sender:TObject;ProgressByFile,ProgressByArchive:Byte);
begin
pbArchive.Position:=ProgressByArchive;
end;
procedure TdlgTestArchive.UniCheckerOnGetPass(Sender: TObject; FN: String;
Var Password: String; Var TryAgain: BOOLEAN);
var Temp:String;
begin
if InputQuery('WinMZF',ReadFromLanguage('Messages','Password','Enter password'),Temp) then
Password:=Temp
Else
TryAgain:=False;
end;
procedure TDlgTestArchive.UniCheckOnStatus(Sender: TObject; FN: string; PassFail: Boolean);
begin
if Not PassFail then
AddItem((FN),ReadFromLanguage('Status','Failed','Failed!'))
Else
AddItem((FN),ReadFromLanguage('Status','Normal','Ok!'));
end;
procedure TDlgTestArchive.MZFStatus(Sender:TObject;FileName:String; Failed:Boolean);
begin
if Failed then
AddItem((FileName),ReadFromLanguage('Status','Failed','Failed!'))
Else
AddItem((FileName),ReadFromLanguage('Status','Normal','Ok!'));
end;
procedure TDlgTestArchive.UniCheckOnError(Sender: TObject; FN: string; MsgEx: string; VolumeID: string; ECode: Integer);
begin
AddItem((FN),Format('Error-%s error code %d',[MsgEx,ECode]));
end;
procedure TDlgTestArchive.MZFOnProgress(Sender: TObject; FProgress: Byte; AProgress: Byte; var Abort: Boolean);
begin
pbArchive.Position:=AProgress;
end;
procedure TDlgTestArchive.MZFGetPass(Sender: TObject; var Pass: OpenString);
var Temp:String;
begin
if InputQuery('WinMZF',ReadFromLanguage('Messages','Password','Enter password'),Temp) then
Pass:=Temp;
end;
procedure TDlgTestArchive.CheckArchive;
var MZFViewer:TMZFViewer;
UniversalCheck:TZipCheck;
Index:LongWord;
begin
case Self.ArcType of
ftMZF:
Begin
MZFViewer:=TMZFViewer.Create;
MZFViewer.ArchiveName:=Self.ArchiveFile;
MZFViewer.OnCheck:=MZFStatus;
MZFViewer.OnProgress:=MZFOnProgress;
MZFViewer.OnPassQuest:=MZFGetPass;
MZFViewer.CheckArchive;
MZFViewer.Free;
End;
ftZip,ftZoo,ftBH,ftGZip,ftLha,ftCab,ftArj,ftPKG5,ftACE2:
Begin
UniversalCheck:=TZipCheck.Create(Nil);
UniversalCheck.ArchiveFile:=Self.ArchiveFile;
for Index := 0 to FileSpec.Count - 1 do
UniversalCheck.FileSpec.Add(FileSpec[Index]);
//Apply properies
UniversalCheck.OnProgress:=UniCheckerOnProgress;
UniversalCheck.OnGetPassword:=UniCheckerOnGetPass;
UniversalCheck.OnStatus:=UniCheckOnStatus;
UniversalCheck.OnError:=UniCheckOnError;
//
UniversalCheck.Activate;
UniversalCheck.Free;
End;
ftRar: ;
ft7z: ;
end;
end;
end.
|
{$IFDEF FREEPASCAL}
{$MODE DELPHI}
{$ENDIF}
unit dll_user32_msg;
interface
uses
atmcmbaseconst, winconst, wintype;
function GetMessage(var lpMsg: TMsg; AWnd: HWND;
wMsgFilterMin, wMsgFilterMax: UINT): BOOL; stdcall; external user32 name 'GetMessageA';
function TranslateMessage(const lpMsg: TMsg): BOOL; stdcall; external user32 name 'TranslateMessage';
const
{ PeekMessage() Options }
PM_NOREMOVE = 0;
PM_REMOVE = 1;
PM_NOYIELD = 2;
function PeekMessage(var lpMsg: TMsg; AWnd: HWND; wMsgFilterMin, wMsgFilterMax, wRemoveMsg: UINT): BOOL; stdcall; external user32 name 'PeekMessageA';
function DispatchMessage(const lpMsg: TMsg): Longint; stdcall; external user32 name 'DispatchMessageA';
function PostMessage(AWnd: HWND; Msg: UINT; wParam: WPARAM; lParam: LPARAM): BOOL; stdcall; external user32 name 'PostMessageA';
procedure PostQuitMessage(nExitCode: Integer); stdcall; external user32 name 'PostQuitMessage';
function PostThreadMessage(idThread: DWORD; AMsg: UINT; wParam: WPARAM; lParam: LPARAM): BOOL; stdcall; external user32 name 'PostThreadMessageA';
function RegisterWindowMessage(lpStr: PAnsiChar): UINT; stdcall; external user32 name 'RegisterWindowMessageA';
function SendNotifyMessage(AWnd: HWND; Msg: UINT; wParam: WPARAM; lParam: LPARAM): BOOL; stdcall; external user32 name 'SendNotifyMessageA';
function SendMessage(AWnd: HWND; Msg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall; external user32 name 'SendMessageA';
const
{ SendMessageTimeout values }
SMTO_NORMAL = 0;
SMTO_BLOCK = 1;
SMTO_ABORTIFHUNG = 2;
SMTO_NOTIMEOUTIFNOTHUNG = 8;
function SendMessageTimeout(AWnd: HWND; Msg: UINT; wParam: WPARAM; lParam: LPARAM;
fuFlags, uTimeout: UINT; var lpdwResult: DWORD): LRESULT; stdcall; external user32 name 'SendMessageTimeoutA';
function WaitMessage: BOOL; stdcall; external user32 name 'WaitMessage';
function ReplyMessage(lResult: LRESULT): BOOL; stdcall; external user32 name 'ReplyMessage';
function WaitForInputIdle(hProcess: THandle; dwMilliseconds: DWORD): DWORD; stdcall; external user32 name 'WaitForInputIdle';
function BroadcastSystemMessage(Flags: DWORD; Recipients: PDWORD;
uiMessage: UINT; wParam: WPARAM; lParam: LPARAM): Longint; stdcall; external user32 name 'BroadcastSystemMessageA';
function CallMsgFilter(var lpMsg: TMsg; nCode: Integer): BOOL; stdcall; external user32 name 'CallMsgFilterA';
type
TFNSendAsyncProc = TFarProc;
function SendMessageCallback(AWnd: HWND; Msg: UINT; wParam: WPARAM;
lParam: LPARAM; lpResultCallBack: TFNSendAsyncProc; dwData: DWORD): BOOL; stdcall; external user32 name 'SendMessageCallbackA';
// ChangeWindowMessageFilter(WM_COPYDATA, MSGFLT_ADD);
(*
http://msdn.microsoft.com/zh-cn/ms632675
Using the ChangeWindowMessageFilter function is not recommended, as it has process-wide scope. Instead, use the ChangeWindowMessageFilterEx function to control access to specific windows as needed. ChangeWindowMessageFilter may not be supported in future versions of Windows
Adds or removes a message from the User Interface Privilege Isolation (UIPI) message filter.
在vista以上的系统,有些程序需要管理员的权限,所以需要服务,这个函数可以解决低权和高权程序之间的沟通。
ChangeWindowMessageFilter(WM_COPYDATA, MSGFLT_ADD);
ChangeWindowMessageFilter(WM_MKFinder, MSGFLT_ADD);
ChangeWindowMessageFilter(WM_MKNoteHost, MSGFLT_ADD);
// windows 8, windows 7 下 拖动失效
ChangeWindowMessageFilter(WM_DROPFILES, MSGFLT_ADD);
// WM_COPYGLOBALDATA $0049
ChangeWindowMessageFilter($0049, MSGFLT_ADD);
*)
const
MSGFLT_ADD = 1;// Adds the message to the filter. This has the effect of allowing
// the message to be received.
MSGFLT_REMOVE = 2;// Removes the message from the filter. This has the effect of blocking the message.
function ChangeWindowMessageFilter(Message: UINT; dwFlag: DWord): BOOL; stdcall; external user32 name 'ChangeWindowMessageFilter';
type
PCHANGEFILTERSTRUCT = ^TCHANGEFILTERSTRUCT;
TCHANGEFILTERSTRUCT = record
cbSize: DWORD;
ExtStatus: DWORD;
end;
const
MSGFLT_RESET = 0;
MSGFLT_ALLOW = 1;
MSGFLT_DISALLOW = 2;
// ExtStatus
MSGFLTINFO_NONE = 0;
MSGFLTINFO_ALREADYALLOWED_FORWND = 1;
MSGFLTINFO_ALREADYDISALLOWED_FORWND = 2;
MSGFLTINFO_ALLOWED_HIGHER = 3;
function ChangeWindowMessageFilterEx(AWnd: HWND; Message: UINT; dwAction: DWord;
pChangeFilterStruct: PCHANGEFILTERSTRUCT): BOOL; stdcall; external user32 name 'ChangeWindowMessageFilterEx';
implementation
end.
|
unit UPrefAppFiletypes;
{ ClickForms Application }
{ Bradford Technologies, Inc. }
{ All Rights Reserved }
{ Source Code Copyrighted © 1998-2011 by Bradford Technologies, Inc. }
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids_ts, TSGrid, ExtCtrls, StdCtrls, Registry, Buttons, IniFiles;
type
clfFileAssociation = record
extension: String;
description: String;
docType: String;
end;
TPrefAppFiletypes = class(TFrame)
Panel1: TPanel;
tsGrid: TtsGrid;
gbAssociation: TGroupBox;
lblExtension: TLabel;
edtExt: TEdit;
lblDesc: TLabel;
edtDesc: TEdit;
bbtnAdd: TBitBtn;
bbtnEdit: TBitBtn;
bbtnSave: TBitBtn;
procedure tsGridClickCell(Sender: TObject; DataColDown, DataRowDown,
DataColUp, DataRowUp: Integer; DownPos, UpPos: TtsClickPosition);
procedure DisplayDataRow(DataRow: Integer);
procedure SetGrpAndBtns(ItemID:Integer; SelRow: Integer=0);
procedure bbtnEditClick(Sender: TObject);
procedure bbtnAddClick(Sender: TObject);
procedure bbtnSaveClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
constructor CreateFrame(AOwner: TComponent);
procedure SetFileAssociations;
end;
function extractExePathFromRegValue(regString: String): String;
function GetExePath(docType: String; var ExePath: String): Boolean;
implementation
uses
UStatus, UGlobals;
const
//document types and Registry Keys are hardcoded in ClickForms installer
MaxStdAssociations = 6;
docTypeClf = 'ClickForms.Document';
docTypeOrder = 'OrderProcessor.Application';
clfFileAssociations: Array[1..MaxStdAssociations] of clfFileAssociation = (
(extension: '*.clk'; description: 'ClickFORMS Report'; docType: docTypeClf),
(extension: '*.cft'; description: 'ClickFORMS Template'; docType: docTypeClf),
(extension: '*.rxml'; description: 'CLVS XML Order'; docType: docTypeClf),
(extension: '*.oxf'; description: 'Appraisal XML Order'; docType: docTypeClf),
(extension: '*.uao'; description: 'Universal XML Order'; docType: docTypeOrder),
(extension: '*.xap'; description: 'AppraisalPort, ETrack XML Orders'; docType: docTypeOrder)
);
colExt = 1;
colDesc = 2;
colStatus = 3;
colDelete = 4;
asterisk = '*';
backslash = '\';
exePathRegKey = '\shell\open\command';
WEFileExtRegKey = '\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts';
applString = 'Application';
orderProcessorPath = '\Tools\Orders\OrderProcessor.exe';
{$R *.dfm}
//in windows Registry document command line looks like "exePath" "%1"
function extractExePathFromRegValue(regString: String): String;
const
quote = '"';
var
delim: Integer;
begin
result := regstring;
if length(result) = 0 then
exit;
delim := Pos(quote,result);
if delim = 0 then
exit;
result := Copy(result,delim +1, length(result));
if length(result) = 0 then
exit;
delim := Pos(quote,result);
if delim > 0 then
result := Copy(result,1,delim - 1);
end;
function GetExePath(docType: String; var ExePath: String): Boolean;
const
//in present we use just 2 document type in Registry to associate file type
clfRegKey = '\SOFTWARE\Bradford\ClickForms2';
ClfRegPathName = 'Path';
var
reg: TRegistry;
begin
result := False;
exePath := '';
reg := TRegistry.Create;
with reg do
try
RootKey := HKEY_LOCAL_MACHINE;
if not OpenKey(clfRegKey,false) then
exit;
exePath := ReadString(ClfRegPathName); //Clickforms Path
if CompareText(docType,docTypeClf) = 0 then
begin
if FileExists(exePath) then
result := True;
end
else
if CompareText(docType, docTypeOrder) = 0 then
begin
exePath := ExtractFilePath(exePath) + OrderProcessorPath;
if FileExists(exePath) then
result := True;
end;
finally
reg.Free;
end;
end;
constructor TPrefAppFiletypes.CreateFrame(AOwner: TComponent);
const
AssocSec = 'FileAssoc';
Err = 'Error';
var
AssocRow, index: integer;
ClfIniFile: TInifile;
RowStr, theExt, theDesc: String;
begin
inherited Create(AOwner);
with tsGrid do
begin
for index := low(clfFileAssociations) to high(clfFileAssociations) do
begin
if tsGrid.Rows < index then
tsGrid.Rows := Succ(tsGrid.Rows);
cell[colExt,index] := clfFileAssociations[index].extension;
cell[colDesc,index] := clfFileAssociations[index].description;
cellCheckBoxState[colStatus,index] := cbUnChecked;
cellColor[colExt, index] := clInactiveBorder;
cellReadOnly[colExt, index] := roOn;
cellColor[colDesc, index] := clInactiveBorder;
cellReadOnly[colDesc, index] := roOn;
cellColor[colDelete, index] := clInactiveBorder;
cellControlType[colDelete, index] := ctText;
cellReadOnly[colDelete, index] := roOn;
end;
ClfIniFile := TIniFile.Create(IncludeTrailingPathDelimiter(appPref_DirPref) + cClickFormsINI);
try
AssocRow := 0;
repeat
AssocRow := Succ(AssocRow);
RowStr := IntToStr(AssocRow);
theExt := ClfIniFile.ReadString(AssocSec, ('Extension' + RowStr), Err);
theDesc := ClfIniFile.ReadString(AssocSec, ('Description' + RowStr), Err);
if (theExt <> '') and
(theExt <> Err) and
(theDesc <> '') and
(theDesc <> Err) then
begin
tsGrid.Rows := tsGrid.Rows + 1;
tsGrid.Cell[colExt, tsGrid.Rows] := theExt;
tsGrid.Cell[colDesc, tsGrid.Rows] := theDesc;
tsGrid.CellCheckBoxState[colStatus, tsGrid.Rows] := cbChecked;
tsGrid.CellCheckBoxState[colDelete, tsGrid.Rows] := cbUnchecked;
end;
until (theExt = Err) or (theDesc = Err);
finally
ClfIniFile.Free;
end;
tsGrid.SelectRows(1, 1, True);
DisplayDataRow(1);
end;
end;
procedure TPrefAppFiletypes.SetFileAssociations;
const
AssocSec = 'FileAssoc';
var
reg: TRegistry;
index: Integer;
exePath: String;
regKey: String;
value: String;
extStr: String;
ClfIniFile: TIniFile;
AssocRow, MaxAddRows: Integer;
RowStr: String;
DelOccurred: Boolean;
function SetRegAssoc(theExt, theDocType: String; theReg: TRegistry; DelReg: Boolean): Boolean;
begin
Result := True;
with theReg do
begin
//set document type
RootKey := HKEY_CLASSES_ROOT;
//remove asterick from extension
regKey := StringReplace(theExt, asterisk, backslash,[]);
if DelReg then
theReg.DeleteKey(regKey)
else
begin
OpenKey(regKey, true);
WriteString('', theDocType);
//set executable path
CloseKey;
GetExePath(theDocType, exePath);
if not FileExists(exePath) then
begin
ShowAlert(atWarnAlert, 'Cannot set the association with ' + theExt + ' files!');
Result := False;
end
else
begin
regKey := Backslash + theDocType + exePathRegKey;
openKey(regKey,true);
value := '"' + exePath + '""%1"';
WriteString('', value);
//remove windows explore entry if exists
CloseKey;
RootKey := HKEY_CURRENT_USER;
//remove asterick from extension
extStr := StringReplace(theExt, asterisk, backslash,[]);
if OpenKey(WEFileExtRegKey + extStr, false) then
DeleteKey(WEFileExtRegKey + extStr);
end;
end;
end;
end;
begin
reg := TRegistry.Create;
try
with reg do
begin
// Establish the standard and additional associations in the registry. Only
// establish additional associations if the "Set Assoc" box is checked AND
// the "Del Assoc" box is unchecked.
for index := 1 to tsGrid.rows do
if (tsGrid.CellCheckBoxState[colStatus,index] = cbChecked) then
if (index <= MaxStdAssociations) then
SetRegAssoc(clfFileAssociations[index].extension, clfFileAssociations[index].docType, reg, False)
else
if tsGrid.CellCheckBoxState[colDelete, index] = cbUnchecked then
SetRegAssoc(tsGrid.Cell[colExt, index], docTypeClf, reg, False);
ClfIniFile := TIniFile.Create(IncludeTrailingPathDelimiter(appPref_DirPref) + cClickFormsINI);
try
DelOccurred := False;
// If the section exists remove it and we'll re-create the entire section
// if there are any additional associations
if ClfIniFile.SectionExists(AssocSec) then
ClfIniFile.EraseSection(AssocSec);
if tsGrid.Rows > MaxStdAssociations then
begin
// Delete the rows from the grid before updating the INI file so the
// Extension and Description ident numbers will be in 1..n order
AssocRow := tsGrid.Rows;
repeat
if tsGrid.CellCheckBoxState[colDelete, AssocRow] = cbChecked then
begin
DelOccurred := True;
SetRegAssoc(tsGrid.Cell[colExt, AssocRow], docTypeClf, reg, True);
tsGrid.DeleteRows(AssocRow, AssocRow);
end;
AssocRow := Pred(AssocRow);
until AssocRow = MaxStdAssociations;
MaxAddRows := tsGrid.Rows - MaxStdAssociations;
// If there are still rows beyond the standard associations then save
// the Extension and Description to the INI file.
if MaxAddRows > 0 then
begin
AssocRow := 0;
repeat
AssocRow := Succ(AssocRow);
RowStr := IntToStr(AssocRow);
if tsGrid.CellCheckBoxState[colDelete, (AssocRow + MaxStdAssociations)] = cbChecked then
begin
ClfIniFile.DeleteKey(AssocSec, ('Extension' + RowStr));
ClfIniFile.DeleteKey(AssocSec, ('Description' + RowStr));
end
else
begin
ClfIniFile.WriteString(AssocSec, ('Extension' + RowStr), tsGrid.Cell[colExt, (AssocRow + MaxStdAssociations)]);
ClfIniFile.WriteString(AssocSec, ('Description' + RowStr), tsGrid.Cell[colDesc, (AssocRow + MaxStdAssociations)]);
end;
until AssocRow = MaxAddRows;
end;
// If we deleted any rows then reposition to and display row number 1
if DelOccurred then
begin
tsGrid.SelectRows(1, 1, True);
DisplayDataRow(1);
end;
end;
finally
ClfIniFile.Free;
end;
end;
finally
reg.Free;
end;
end;
procedure TPrefAppFiletypes.tsGridClickCell(Sender: TObject; DataColDown,
DataRowDown, DataColUp, DataRowUp: Integer; DownPos,
UpPos: TtsClickPosition);
begin
DisplayDataRow(DataRowDown);
{gbAssociation.Tag := DataRowDown;
SetGrpAndBtns(0, DataRowDown);
edtExt.Text := tsGrid.Cell[colExt, DataRowDown];
edtDesc.Text := tsGrid.Cell[colDesc, DataRowDown];
if gbAssociation.Tag <= MaxStdAssociations then
tsGrid.Cell[colDelete, gbAssociation.Tag] := '';}
end;
procedure TPrefAppFiletypes.DisplayDataRow(DataRow: Integer);
begin
gbAssociation.Tag := DataRow;
SetGrpAndBtns(0, DataRow);
edtExt.Text := tsGrid.Cell[colExt, DataRow];
edtDesc.Text := tsGrid.Cell[colDesc, DataRow];
if gbAssociation.Tag <= MaxStdAssociations then
tsGrid.Cell[colDelete, gbAssociation.Tag] := '';
end;
procedure TPrefAppFiletypes.SetGrpAndBtns(ItemID:Integer; SelRow: Integer=0);
procedure EnDisBtns(AddState, EditState, SaveState: Boolean);
begin
bbtnAdd.Enabled := AddState;
bbtnEdit.Enabled := EditState;
bbtnSave.Enabled := SaveState;
edtExt.Enabled := SaveState;
edtDesc.Enabled := SaveState;
end;
begin
case ItemID of
0:
begin
gbAssociation.Caption := 'Displaying the Selected Association';
EnDisBtns(True, (SelRow > MaxStdAssociations), False);
end;
1:
begin
gbAssociation.Caption := 'Edit the Selected Association';
EnDisBtns(False, False, True);
edtExt.SetFocus;
end;
2:
begin
gbAssociation.Caption := 'Add a New Association';
edtExt.Text := '';
edtDesc.Text := '';
gbAssociation.Tag := 0;
EnDisBtns(False, False, True);
edtExt.SetFocus;
end;
end;
end;
procedure TPrefAppFiletypes.bbtnEditClick(Sender: TObject);
begin
SetGrpAndBtns(bbtnEdit.Tag);
end;
procedure TPrefAppFiletypes.bbtnAddClick(Sender: TObject);
begin
SetGrpAndBtns(bbtnAdd.Tag);
end;
procedure TPrefAppFiletypes.bbtnSaveClick(Sender: TObject);
begin
if gbAssociation.Tag > 0 then
begin
tsGrid.Cell[colExt, gbAssociation.Tag] := edtExt.Text;
tsGrid.Cell[colDesc, gbAssociation.Tag] := edtDesc.Text;
tsGrid.CellCheckBoxState[colStatus, gbAssociation.Tag] := cbChecked;
tsGrid.CellCheckBoxState[colDelete, gbAssociation.Tag] := cbUnchecked;
end
else
begin
tsGrid.Rows := tsGrid.Rows + 1;
tsGrid.Cell[colExt, tsGrid.Rows] := edtExt.Text;
tsGrid.Cell[colDesc, tsGrid.Rows] := edtDesc.Text;
tsGrid.CellCheckBoxState[colStatus, tsGrid.Rows] := cbChecked;
tsGrid.CellCheckBoxState[colDelete, tsGrid.Rows] := cbUnchecked;
end;
SetGrpAndBtns(0);
end;
end.
|
unit Core;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, BaseModel, JSON_Helper;
type
IBaseCore = interface(IBaseModel) ['{00F93490-4378-4E56-B193-B69B5B1B9ACE}']
function GetAsdsAttempts: LongWord;
function GetAsdsLandings: LongWord;
function GetBlock: LongWord;
function GetId: string;
function GetLastUpdate: string;
function GetLaunchesId: TStringList;
function GetReuseCount: LongWord;
function GetRtlsAttempts: LongWord;
function GetRtlsLandings: LongWord;
function GetSerial: string;
function GetStatus: string;
procedure SetAsdsAttempts(AValue: LongWord);
procedure SetAsdsLandings(AValue: LongWord);
procedure SetBlock(AValue: LongWord);
procedure SetId(AValue: string);
procedure SetLastUpdate(AValue: string);
procedure SetLaunchesId(AValue: TStringList);
procedure SetReuseCount(AValue: LongWord);
procedure SetRtlsAttempts(AValue: LongWord);
procedure SetRtlsLandings(AValue: LongWord);
procedure SetSerial(AValue: string);
procedure SetStatus(AValue: string);
end;
ICore = interface(IBaseCore) ['{63DB40A2-5215-4EB9-8B52-8BA3213D8A6A}']
property AsdsAttempts: LongWord read GetAsdsAttempts write SetAsdsAttempts;
property AsdsLandings: LongWord read GetAsdsLandings write SetAsdsLandings;
property Block: LongWord read GetBlock write SetBlock;
property Id: string read GetId write SetId;
property LastUpdate: string read GetLastUpdate write SetLastUpdate;
property LaunchesId: TStringList read GetLaunchesId write SetLaunchesId;
property ReuseCount: LongWord read GetReuseCount write SetReuseCount;
property RtlsAttempts: LongWord read GetRtlsAttempts write SetRtlsAttempts;
property RtlsLandings: LongWord read GetRtlsLandings write SetRtlsLandings;
property Serial: string read GetSerial write SetSerial;
property Status: string read GetStatus write SetStatus;
end;
ICoreList = interface(IBaseModelList) ['{6280AF36-5EE5-4714-ACC7-65787AA56325}']
end;
{ TCoreEnumerator }
TCoreEnumerator = class(TBaseModelEnumerator)
function GetCurrent: ICore;
property Current : ICore read GetCurrent;
end;
function NewCore: ICore;
function NewCoreList: ICoreList;
operator enumerator(AList: ICoreList): TCoreEnumerator;
implementation
uses
Variants;
type
{ TCore }
TCore = class(TBaseModel, ICore)
private
FAsdsAttempts: LongWord;
FAsdsLandings: LongWord;
FBlock: LongWord;
FId: string;
FLastUpdate: string;
FLaunchesId: TStringList;
FReuseCount: LongWord;
FRtlsAttempts: LongWord;
FRtlsLandings: LongWord;
FSerial: string;
FStatus: string;
function GetAsdsAttempts: LongWord;
function GetAsdsLandings: LongWord;
function GetBlock: LongWord;
function GetId: string;
function GetLastUpdate: string;
function GetLaunchesId: TStringList;
function GetReuseCount: LongWord;
function GetRtlsAttempts: LongWord;
function GetRtlsLandings: LongWord;
function GetSerial: string;
function GetStatus: string;
procedure SetAsdsAttempts(AValue: LongWord);
procedure SetAsdsAttempts(AValue: Variant);
procedure SetAsdsLandings(AValue: LongWord);
procedure SetAsdsLandings(AValue: Variant);
procedure SetBlock(AValue: LongWord);
procedure SetBlock(AValue: Variant);
procedure SetId(AValue: string);
procedure SetId(AValue: Variant);
procedure SetLastUpdate(AValue: string);
procedure SetLastUpdate(AValue: Variant);
procedure SetLaunchesId(AValue: TStringList);
procedure SetLaunchesId(AValue: Variant);
procedure SetReuseCount(AValue: LongWord);
procedure SetReuseCount(AValue: Variant);
procedure SetRtlsAttempts(AValue: LongWord);
procedure SetRtlsAttempts(AValue: Variant);
procedure SetRtlsLandings(AValue: LongWord);
procedure SetRtlsLandings(AValue: Variant);
procedure SetSerial(AValue: string);
procedure SetSerial(AValue: Variant);
procedure SetStatus(AValue: string);
procedure SetStatus(AValue: Variant);
public
constructor Create;
destructor Destroy; override;
function ToString(): string; override;
published
property asds_attempts: Variant write SetAsdsAttempts;
property asds_landings: Variant write SetAsdsLandings;
property block: Variant write SetBlock;
property id: Variant write SetId;
property last_update: Variant write SetLastUpdate;
property launches: Variant write SetLaunchesId;
property reuse_count: Variant write SetReuseCount;
property rtls_attempts: Variant write SetRtlsAttempts;
property rtls_landings: Variant write SetRtlsLandings;
property serial: Variant write SetSerial;
property status: Variant write SetStatus;
end;
{ TCoreList }
TCoreList = class(TBaseModelList, ICoreList)
function NewItem: IBaseModel; override;
end;
function NewCore: ICore;
begin
Result := TCore.Create;
end;
function NewCoreList: ICoreList;
begin
Result := TCoreList.Create;
end;
operator enumerator(AList: ICoreList): TCoreEnumerator;
begin
Result := TCoreEnumerator.Create;
Result.FList := AList;
end;
{ TCoreEnumerator }
function TCoreEnumerator.GetCurrent: ICore;
begin
Result := FCurrent as ICore;
end;
{ TCoreList }
function TCoreList.NewItem: IBaseModel;
begin
Result := NewCore;
end;
{ TCore }
function TCore.GetAsdsAttempts: LongWord;
begin
Result := FAsdsAttempts;
end;
function TCore.GetAsdsLandings: LongWord;
begin
Result := FAsdsLandings;
end;
function TCore.GetBlock: LongWord;
begin
Result := FBlock;
end;
function TCore.GetId: string;
begin
Result := FId;
end;
function TCore.GetLastUpdate: string;
begin
Result := FLastUpdate;
end;
function TCore.GetLaunchesId: TStringList;
begin
Result := FLaunchesId;
end;
function TCore.GetReuseCount: LongWord;
begin
Result := FReuseCount;
end;
function TCore.GetRtlsAttempts: LongWord;
begin
Result := FRtlsAttempts;
end;
function TCore.GetRtlsLandings: LongWord;
begin
Result := FRtlsLandings;
end;
function TCore.GetSerial: string;
begin
Result := FSerial;
end;
function TCore.GetStatus: string;
begin
Result := FStatus;
end;
procedure TCore.SetAsdsAttempts(AValue: LongWord);
begin
FAsdsAttempts := AValue;
end;
procedure TCore.SetAsdsAttempts(AValue: Variant);
begin
if VarIsNull(AValue) then begin
FAsdsAttempts := -0;
end else if VarIsNumeric(AValue) then
FAsdsAttempts := AValue;
end;
procedure TCore.SetAsdsLandings(AValue: LongWord);
begin
FAsdsLandings := AValue;
end;
procedure TCore.SetAsdsLandings(AValue: Variant);
begin
if VarIsNull(AValue) then begin
FAsdsLandings := -0;
end else if VarIsNumeric(AValue) then
FAsdsLandings := AValue;
end;
procedure TCore.SetBlock(AValue: LongWord);
begin
FBlock := AValue;
end;
procedure TCore.SetBlock(AValue: Variant);
begin
if VarIsNull(AValue) then begin
FBlock := -0;
end else if VarIsNumeric(AValue) then
FBlock := AValue;
end;
procedure TCore.SetId(AValue: string);
begin
FId := AValue;
end;
procedure TCore.SetId(AValue: Variant);
begin
if VarIsNull(AValue) then begin
FId := '';
end else if VarIsStr(AValue) then
FId := AValue;
end;
procedure TCore.SetLastUpdate(AValue: string);
begin
FLastUpdate := AValue;
end;
procedure TCore.SetLastUpdate(AValue: Variant);
begin
if VarIsNull(AValue) then begin
FLastUpdate := '';
end else if VarIsStr(AValue) then
FLastUpdate := AValue;
end;
procedure TCore.SetLaunchesId(AValue: TStringList);
begin
FLaunchesId := AValue;
end;
procedure TCore.SetLaunchesId(AValue: Variant);
begin
if VarIsNull(AValue) then begin
FLaunchesId := TStringList.Create;
end else if VarIsStr(AValue) then
FLaunchesId.AddDelimitedText(AValue);;
end;
procedure TCore.SetReuseCount(AValue: LongWord);
begin
FReuseCount := AValue;
end;
procedure TCore.SetReuseCount(AValue: Variant);
begin
if VarIsNull(AValue) then begin
FReuseCount := -0;
end else if VarIsNumeric(AValue) then
FReuseCount := AValue;
end;
procedure TCore.SetRtlsAttempts(AValue: LongWord);
begin
FRtlsAttempts := AValue;
end;
procedure TCore.SetRtlsAttempts(AValue: Variant);
begin
if VarIsNull(AValue) then begin
FRtlsAttempts := -0;
end else if VarIsNumeric(AValue) then
FRtlsAttempts := AValue;
end;
procedure TCore.SetRtlsLandings(AValue: LongWord);
begin
FRtlsLandings := AValue;
end;
procedure TCore.SetRtlsLandings(AValue: Variant);
begin
if VarIsNull(AValue) then begin
FRtlsLandings := -0;
end else if VarIsNumeric(AValue) then
FRtlsLandings := AValue;
end;
procedure TCore.SetSerial(AValue: string);
begin
FSerial := AValue;
end;
procedure TCore.SetSerial(AValue: Variant);
begin
if VarIsNull(AValue) then begin
FSerial := '';
end else if VarIsStr(AValue) then
FSerial := AValue;
end;
procedure TCore.SetStatus(AValue: string);
begin
FStatus := AValue;
end;
procedure TCore.SetStatus(AValue: Variant);
begin
if VarIsNull(AValue) then begin
FStatus := '';
end else if VarIsStr(AValue) then
FStatus := AValue;
end;
constructor TCore.Create;
begin
inherited Create;
FLaunchesId := TStringList.Create;
FLaunchesId.SkipLastLineBreak:=True;
end;
destructor TCore.Destroy;
begin
FreeAndNil(FLaunchesId);
inherited Destroy;
end;
function TCore.ToString(): string;
begin
Result := Format(''
+ 'Asds Attempts: %u' + LineEnding
+ 'Asds Landings: %u' + LineEnding
+ 'Block: %u' + LineEnding
+ 'ID: %s' + LineEnding
+ 'Last Update: %s' + LineEnding
+ 'Launches: %s' + LineEnding
+ 'Reuse Count: %u' + LineEnding
+ 'Rtls Attempts: %u' + LineEnding
+ 'Rtls Landings: %u' + LineEnding
+ 'Serial: %s' + LineEnding
+ 'Status: %s'
, [
GetAsdsAttempts,
GetAsdsLandings,
GetBlock,
GetId,
GetLastUpdate,
GetLaunchesId.Text,
GetReuseCount,
GetRtlsAttempts,
GetRtlsLandings,
GetSerial,
GetStatus
]);
end;
end.
|
program gadtoolsmenu;
{$IFNDEF HASAMIGA}
{$FATAL This source is compatible with Amiga, AROS and MorphOS only !}
{$ENDIF}
{$MODE OBJFPC}{$H+}{$HINTS ON}
{$UNITPATH ../../../Base/CHelpers}
{$UNITPATH ../../../Base/Trinity}
{$UNITPATH ../../../Base/Sugar}
{$IFDEF AMIGA} {$UNITPATH ../../../Sys/Amiga} {$ENDIF}
{$IFDEF AROS} {$UNITPATH ../../../Sys/AROS} {$ENDIF}
{$IFDEF MORPHOS} {$UNITPATH ../../../Sys/MorphOS} {$ENDIF}
{
Project : gadtoolsmenu
Source : RKRM
}
{*
** Example showing the basic usage of the menu system with a window.
** Menu layout is done with GadTools, as is recommended for applications.
*}
{$DEFINE INTUI_V36_NAMES_ONLY}
Uses
Exec, Intuition, Gadtools, Utility,
{$IFDEF AMIGA}
systemvartags,
{$ENDIF}
CHelpers,
Trinity;
const
mynewmenu : Array[0..16-1] of TNewMenu =
(
( nm_Type: NM_TITLE; nm_Label: 'Project'; nm_CommKey: nil; nm_Flags: 0; nm_MutualExclude: 0; nm_UserData: nil ),
( nm_Type: NM_ITEM; nm_Label: 'Open...'; nm_CommKey: 'O'; nm_Flags: 0; nm_MutualExclude: 0; nm_UserData: nil ),
( nm_Type: NM_ITEM; nm_Label: 'Save'; nm_CommKey: 'S'; nm_Flags: 0; nm_MutualExclude: 0; nm_UserData: nil ),
( nm_Type: NM_ITEM; nm_Label: 'Save As...'; nm_CommKey: 'A'; nm_Flags: 0; nm_MutualExclude: 0; nm_UserData: nil ),
( nm_Type: NM_ITEM; nm_Label: PChar(NM_BARLABEL); nm_CommKey: nil; nm_Flags: 0; nm_MutualExclude: 0; nm_UserData: nil ),
( nm_Type: NM_ITEM; nm_Label: 'Quit'; nm_CommKey: 'Q'; nm_Flags: 0; nm_MutualExclude: 0; nm_UserData: nil ),
( nm_Type: NM_TITLE; nm_Label: 'Edit'; nm_CommKey: nil; nm_Flags: 0; nm_MutualExclude: 0; nm_UserData: nil ),
( nm_Type: NM_ITEM; nm_Label: 'Mark'; nm_CommKey: 'B'; nm_Flags: 0; nm_MutualExclude: 0; nm_UserData: nil ),
( nm_Type: NM_ITEM; nm_Label: 'Cut'; nm_CommKey: 'X'; nm_Flags: 0; nm_MutualExclude: 0; nm_UserData: nil ),
( nm_Type: NM_ITEM; nm_Label: 'Copy'; nm_CommKey: 'C'; nm_Flags: 0; nm_MutualExclude: 0; nm_UserData: nil ),
( nm_Type: NM_ITEM; nm_Label: 'Paste'; nm_CommKey: 'V'; nm_Flags: 0; nm_MutualExclude: 0; nm_UserData: nil ),
( nm_Type: NM_TITLE; nm_Label: 'Settings'; nm_CommKey: nil; nm_Flags: 0; nm_MutualExclude: 0; nm_UserData: nil ),
( nm_Type: NM_ITEM; nm_Label: 'Reset to defaults'; nm_CommKey: 'D'; nm_Flags: 0; nm_MutualExclude: 0; nm_UserData: nil ),
( nm_Type: NM_ITEM; nm_Label: 'Reset to last saved'; nm_CommKey: 'L'; nm_Flags: 0; nm_MutualExclude: 0; nm_UserData: nil ),
( nm_Type: NM_ITEM; nm_Label: 'Previous settings'; nm_CommKey: 'P'; nm_Flags: 0; nm_MutualExclude: 0; nm_UserData: nil ),
( nm_Type: NM_END )
);
{*
** Watch the menus and wait for the user to select the close gadget
** or quit from the menus.
*}
procedure handle_window_events(win: PWindow; menuStrip: PMenu);
var
msg : PIntuiMessage;
done : boolean;
menuNumber : UWORD;
menuNum : UWORD;
itemNum : UWORD;
subNum : UWORD;
item : PMenuItem;
begin
done := FALSE;
while (FALSE = done) do
begin
{* we only have one signal bit, so we do not have to check which
** bit broke the Wait().
*}
Wait(1 shl win^.UserPort^.mp_SigBit);
while ( (FALSE = done) and (nil <> SetAndGet(msg, PIntuiMessage(GetMsg(win^.UserPort)))) ) do
begin
case (msg^.IClass) of
IDCMP_CLOSEWINDOW:
begin
done := TRUE;
end;
IDCMP_MENUPICK:
begin
menuNumber := msg^.Code;
while ((menuNumber <> UWORD(MENUNULL)) and not(done)) do
begin
item := ItemAddress(menuStrip, menuNumber);
//* process the item here! */
menuNum := Intuition.MENUNUM(menuNumber);
itemNum := Intuition.ITEMNUM(menuNumber);
subNum := Intuition.SUBNUM(menuNumber);
WriteLn('menunum = ', MenuNum, ' ', 'itemnum = ', ItemNum);
//* stop if quit is selected. */
//* FPC Note: there is a bug in original code, itemNum must be 4.
if ( (menuNum = 0) and (itemNum = 4) )
then done := TRUE;
menuNumber := item^.NextSelect;
end;
end;
end;
ReplyMsg(PMessage(msg));
end;
end;
end;
{*
** Open all of the required libraries and set-up the menus.
*}
procedure main(argc: integer; argv: PPChar);
var
win : PWindow;
my_VisualInfo : PAPTR;
menuStrip : PMenu;
begin
//* Open the Intuition Library */
{$IF DEFINED(MORPHOS)}
IntuitionBase := PIntuitionBase(OpenLibrary('intuition.library', 37));
if (IntuitionBase <> nil) then
{$ENDIF}
begin
//* Open the gadtools Library */
{$IF DEFINED(MORPHOS) or DEFINED(AMIGA)}
GadToolsBase := OpenLibrary('gadtools.library', 37);
if (GadToolsBase <> nil) then
{$ENDIF}
begin
if (nil <> SetAndGet(win, OpenWindowTags(nil,
[
TAG_(WA_Width) , 400,
TAG_(WA_Activate) , TAG_(TRUE),
TAG_(WA_Height) , 100,
TAG_(WA_CloseGadget) , TAG_(TRUE),
TAG_(WA_Title) , TAG_(PChar('Menu Test Window')),
TAG_(WA_IDCMP) , IDCMP_CLOSEWINDOW or IDCMP_MENUPICK,
TAG_END
]))) then
begin
if (nil <> SetAndGet(my_VisualInfo, GetVisualInfo(win^.WScreen, [TAG_END, 0]))) then
begin
if (nil <> SetAndGet(menuStrip, CreateMenus(@mynewmenu, [TAG_END, 0]))) then
begin
if (LayoutMenus(menuStrip, my_VisualInfo, [TAG_END, 0])) then
begin
if (SetMenuStrip(win, menuStrip)) then
begin
handle_window_events(win, menuStrip);
ClearMenuStrip(win);
end;
FreeMenus(menuStrip);
end;
end;
FreeVisualInfo(my_VisualInfo);
end;
CloseWindow(win);
end;
{$IF DEFINED(MORPHOS) or DEFINED(AMIGA)}
CloseLibrary(PLibrary(GadToolsBase));
{$ENDIF}
end;
{$IF DEFINED(MORPHOS)}
CloseLibrary(PLibrary(IntuitionBase));
{$ENDIF}
end;
end;
begin
Main(ArgC, ArgV);
end.
|
unit ThoughtWorks.QRCode.Codec.Util.ContentConverter;
interface
uses
System.SysUtils;
type
TContentConverter = class
public
class function convert(targetString: string): string;
private
class function convertDocomoBookmark(targetString: string): string;
class function convertDocomoAddressBook(targetString: string): string;
class function convertDocomoMailto(targetString: string): string;
class function replaceString(s, s1, s2: string): string;
class function removeString(s, s1: string): string;
end;
implementation
class function TContentConverter.convert(targetString: string): string;
begin
if targetString = '' then
begin
Result := targetString;
Exit;
end;
if targetString.IndexOf('MEBKM:') > -1 then
begin
targetString := convertDocomoBookmark(targetString);
end;
if targetString.IndexOf('MECARD:') > -1 then
begin
targetString := convertDocomoAddressBook(targetString);
end;
if targetString.IndexOf('MATMSG:') > -1 then
begin
targetString := convertDocomoMailto(targetString);
end;
if targetString.IndexOf('http\://') > -1 then
begin
targetString := replaceString(targetString, 'http\://', #13'http://');
end;
Result := targetString;
end;
class function TContentConverter.convertDocomoBookmark(targetString: string): string;
begin
targetString := removeString(targetString, 'MEBKM:');
targetString := removeString(targetString, 'TITLE:');
targetString := removeString(targetString, ';');
targetString := removeString(targetString, 'URL');
Result := targetString;
end;
class function TContentConverter.convertDocomoAddressBook(targetString: string): string;
begin
targetString := removeString(targetString, 'MECARD:');
targetString := removeString(targetString, ';');
targetString := replaceString(targetString, 'N:', 'NAME1:');
targetString := replaceString(targetString, 'SOUND:', #13'NAME1:');
targetString := replaceString(targetString, 'TEL:', #13'NAME1:');
targetString := replaceString(targetString, 'EMAIL:', #13'NAME1:');
targetString := targetString + #13;
Result := targetString;
end;
class function TContentConverter.convertDocomoMailto(targetString: string): string;
begin
targetString := removeString(targetString, 'MATMSG:');
targetString := removeString(targetString, ';');
targetString := replaceString(targetString, 'TO:', 'MAILTO:');
targetString := replaceString(targetString, 'SUB:', #13'SUBJECT:');
targetString := replaceString(targetString, 'BODY:', #13'BODY:');
targetString := targetString + #13;
Result := targetString;
end;
class function TContentConverter.replaceString(s: string; s1: string; s2: string): string;
var
I: Integer;
begin
Result := s.Replace(s1, s2);
end;
class function TContentConverter.removeString(s: string; s1: string): string;
begin
Result := replaceString(s, s1, '');
end;
end.
|
unit main;
interface
uses
Windows,
Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, Menus,
PasLibVlcUnit,vlcpl;
type
TMainForm = class(TForm)
OpenDialog: TOpenDialog;
MainMenu: TMainMenu;
MenuFile: TMenuItem;
MenuFileOpen: TMenuItem;
MenuFileQuit: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure MenuFileOpenClick(Sender: TObject);
procedure MenuFileQuitClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
p_li : libvlc_instance_t_ptr;
p_mi : libvlc_media_player_t_ptr;
procedure PlayerInit();
procedure PlayerPlay(fileName: WideString);
procedure PlayerStop();
procedure PlayerDestroy();
public
{ Public declarations }
end;
var
MainForm: TMainForm;
Player :tvlcpl;
implementation
{$R *.dfm}
procedure TMainForm.PlayerInit();
begin
if player.Init(self.Handle) <>0 then begin
MessageDlg(Player.error, mtError, [mbOK], 0);
exit;
end;
end;
procedure TMainForm.PlayerPlay(fileName: WideString);
begin
PlayerStop();
player.Play(PAnsiChar(UTF8Encode(fileName)));
end;
procedure TMainForm.PlayerStop();
begin
player.Stop;
end;
procedure TMainForm.PlayerDestroy();
begin
player.release;
end;
procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Player.Release;
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
Player:=TVlcPl.Create;
PlayerInit();
end;
procedure TMainForm.MenuFileOpenClick(Sender: TObject);
begin
if (player.p_li <> NIL) then
begin
if OpenDialog.Execute() then
begin
PlayerPlay(OpenDialog.FileName);
end;
end;
end;
procedure TMainForm.MenuFileQuitClick(Sender: TObject);
begin
Close();
end;
end.
|
unit UDragUtils;
{ ClickForms Application }
{ Bradford Technologies, Inc. }
{ All Rights Reserved }
{ Source Code Copyrighted © 2005 by Bradford Technologies, Inc. }
interface
uses
ActiveX, Types;
type
TDropTarget = class(TObject,IDropTarget)
protected
function DragEnter(const dataObj: IDataObject; grfKeyState: Longint;
pt: TPoint; var dwEffect: Longint): HResult; stdcall;
function DragOver(grfKeyState: Longint; pt: TPoint;
var dwEffect: Longint): HResult; stdcall;
function DragLeave: HResult; stdcall;
function Drop(const dataObj: IDataObject; grfKeyState: Longint; pt: TPoint;
var dwEffect: Longint): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
end;
function IsDropHasFiles(dataObj: IDataObject;fileExts: String): Boolean;
function GetDropData(dataObj: IDataObject;dataFrmt: Integer): THandle;
implementation
uses
Windows, SysUtils, shellAPI, Forms, UStatus, UGlobals, UContainer, UUtil1;
function TDropTarget.DragEnter(const dataObj: IDataObject; grfKeyState: Longint;
pt: TPoint; var dwEffect: Longint): HResult;
begin
Result := E_INVALIDARG;
end;
function TDropTarget.DragOver(grfKeyState: Longint; pt: TPoint;
var dwEffect: Longint): HResult;
begin
dwEffect :=DROPEFFECT_COPY;
result := S_OK;
end;
function TDropTarget.DragLeave: HResult;
begin
result := S_OK;
end;
function TDropTarget.Drop(const dataObj: IDataObject; grfKeyState: Longint; pt: TPoint; var dwEffect: Longint): HResult;
begin
result := S_OK;
end;
function TDropTarget._AddRef: Integer;
begin
result := 1;
end;
function TDropTarget._Release;
begin
result := 1;
end;
function TDropTarget.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
if GetInterface(IID,obj) then
result := S_OK
else
result := E_NoInterface;
end;
function IsDropHasFiles(dataObj: IDataObject;fileExts: String): Boolean;
var
aFmtEtc: TFORMATETC;
aStgMed: TSTGMEDIUM;
hDrop: THandle;
fl, nFiles: Integer;
fileName: array[0..MAX_PATH] of char;
begin
result := False;
with aFmtEtc do
begin
cfFormat := CF_HDROP;
ptd := nil;
dwAspect := DVASPECT_CONTENT;
lindex := -1;
tymed := TYMED_HGLOBAL;
end;
try
if dataObj.GetData(aFmtEtc,aStgMed) = S_OK then
begin
hDrop := aStgmed.hGlobal;
nFiles := DragQueryFile(hDrop, $FFFFFFFF,nil,0);
for fl := 0 to nFiles - 1 do
begin
DragQueryFile(hDrop,fl, fileName, sizeof(fileName));
if Pos(ExtractFileExt(fileName),fileExts) > 0 then
begin
result := True;
break;
end;
end;
end;
finally
ReleaseStgMedium(aStgMed);
end;
end;
function GetDropData(dataObj: IDataObject;dataFrmt: Integer): THandle;
var
aFmtEtc: TFORMATETC;
aStgMed: TSTGMEDIUM;
hCopyData: THandle;
pOleData, pCopyData: Pointer;
dataSize: Integer;
begin
result := 0;
if not assigned(dataObj) then
exit;
with aFmtEtc do
begin
cfFormat := dataFrmt;
ptd := nil;
dwAspect := DVASPECT_CONTENT;
lindex := -1;
tymed := TYMED_HGLOBAL;
end;
if dataObj.GetData(aFmtEtc,aStgMed) = S_OK then
try
try
pOleData := GlobalLock(aStgMed.hGlobal);
dataSize := GlobalSize(aStgMed.hGlobal);
hCopyData := GlobalAlloc(GHND,dataSize);
pcopyData := GlobalLock(hCopyData);
CopyMemory(pCopyData,pOleData,dataSize);
GlobalUnlock(aStgMed.hGlobal);
GlobalUnlock(HCopyData);
result := hCopyData;
except
on E:Exception do
begin
ShowNotice(E.Message);
exit;
end;
end;
finally
ReleaseStgMedium(aStgMed);
end;
end;
end.
|
unit uCadastroJuros;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.StdCtrls, Vcl.Mask, RxToolEdit, RxCurrEdit, Vcl.ComCtrls, Vcl.ToolWin,
Vcl.ExtCtrls, System.ImageList, Vcl.ImgList, PngImageList, RxLookup, DB,
ZAbstractRODataset, ZAbstractDataset, ZDataset, vcl.buttons, Juros, JurosRN,
TipoJuros;
type
TfrmCadastroJuros = class(TForm)
PngImageList1: TPngImageList;
Panel1: TPanel;
ToolBar1: TToolBar;
btnVoltar: TToolButton;
btnNovo: TToolButton;
btnEditar: TToolButton;
btnExcluir: TToolButton;
btnGravar: TToolButton;
btnCancelar: TToolButton;
btnPesquisar: TToolButton;
edtAcrescimo: TCurrencyEdit;
edtMora: TCurrencyEdit;
edtJuros: TCurrencyEdit;
lblTipoJuros: TLabel;
lblDiaAtraso: TLabel;
lblJurosMora: TLabel;
lblJuros: TLabel;
lblAcrescimo: TLabel;
dblTipoJuros: TRxDBLookupCombo;
edtDiaAtraso: TEdit;
btnFormTipoJuros: TSpeedButton;
dblStatusGrupo: TRxDBLookupCombo;
lblStatus: TLabel;
btnStringGrid: TButton;
procedure btnVoltarClick(Sender: TObject);
procedure btnNovoClick(Sender: TObject);
procedure btnEditarClick(Sender: TObject);
procedure btnExcluirClick(Sender: TObject);
procedure btnGravarClick(Sender: TObject);
procedure btnCancelarClick(Sender: TObject);
procedure btnPesquisarClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnFormTipoJurosClick(Sender: TObject);
procedure btnStringGridClick(Sender: TObject);
private
{ Private declarations }
bNovo, bAtualizar: boolean;
public
{ Public declarations }
idJuros: Integer;
procedure setDblValue();
procedure controleSHOW;
procedure controleNOVOALTERAR;
procedure controleGRAVAR;
procedure controleCANCELAR;
procedure controlePESQUISAR;
procedure controleEXCLUIR;
procedure setNovo;
procedure setJuros(var PJuros: TJuros);
procedure setFonteNegrito(bNegrito: boolean);
procedure excluir;
procedure gravar;
end;
var
frmCadastroJuros: TfrmCadastroJuros;
jurosRn : TJurosRN;
juros : TJuros;
tipoJuros : TTipoJuros;
implementation
{$R *.dfm}
uses uDMPrincipal, uPesquisaJuros, uCadastroTipoJuros,
uPesquisarJurosStringGrid;
procedure TfrmCadastroJuros.btnCancelarClick(Sender: TObject);
begin
controleCANCELAR;
end;
procedure TfrmCadastroJuros.btnEditarClick(Sender: TObject);
begin
bNovo := false;
bAtualizar := true;
controleNOVOALTERAR;
end;
procedure TfrmCadastroJuros.btnExcluirClick(Sender: TObject);
begin
excluir;
end;
procedure TfrmCadastroJuros.btnFormTipoJurosClick(Sender: TObject);
begin
if frmCadastroTipoJuros = nil then
begin
frmCadastroTipoJuros := TfrmCadastroTipoJuros.Create(frmCadastroTipoJuros);
frmCadastroTipoJuros.ShowModal;
end;
dblTipoJuros.LookupSource := JurosRN.getTipoJuros();
dblStatusGrupo.LookupSource := JurosRN.getStatusTipoJuros();
end;
procedure TfrmCadastroJuros.btnGravarClick(Sender: TObject);
begin
gravar;
end;
procedure TfrmCadastroJuros.btnNovoClick(Sender: TObject);
begin
bNovo := true;
bAtualizar := false;
edtAcrescimo.Clear;
edtMora.Clear;
edtJuros.Clear;
edtDiaAtraso.Clear;
dblTipoJuros.ResetField;
dblStatusGrupo.ResetField;
controleNOVOALTERAR;
end;
procedure TfrmCadastroJuros.btnPesquisarClick(Sender: TObject);
begin
if frmPesquisaJuros = nil then
begin
frmPesquisaJuros := TfrmPesquisaJuros.Create(frmPesquisaJuros);
frmPesquisaJuros.ShowModal;
end;
end;
procedure TfrmCadastroJuros.btnVoltarClick(Sender: TObject);
begin
close;
end;
procedure TfrmCadastroJuros.btnStringGridClick(Sender: TObject);
begin
if frmPesquisaJurosStringGrid = nil then
begin
frmPesquisaJurosStringGrid := TfrmPesquisaJurosStringGrid.Create(frmPesquisaJurosStringGrid);
frmPesquisaJurosStringGrid.ShowModal;
end;
end;
procedure TfrmCadastroJuros.controleCANCELAR;
begin
controleSHOW;
bNovo := false;
bAtualizar := false;
setFonteNegrito(false);
end;
procedure TfrmCadastroJuros.controleEXCLUIR;
begin
btnVoltar.Enabled := true;
btnNovo.Enabled := true;
btnEditar.Enabled := false;
btnExcluir.Enabled := false;
btnGravar.Enabled := false;
btnCancelar.Enabled := false;
btnPesquisar.Enabled := true;
Panel1.Enabled := false;
bNovo := false;
bAtualizar := false;
setFonteNegrito(false);
end;
procedure TfrmCadastroJuros.controleGRAVAR;
begin
btnVoltar.Enabled := true;
btnNovo.Enabled := true;
btnEditar.Enabled := true;
btnExcluir.Enabled := true;
btnGravar.Enabled := false;
btnCancelar.Enabled := true;
btnPesquisar.Enabled := true;
Panel1.Enabled := false;
bNovo := false;
bAtualizar := false;
setFonteNegrito(true);
end;
procedure TfrmCadastroJuros.controleNOVOALTERAR;
begin
btnVoltar.Enabled := false;
btnNovo.Enabled := false;
btnEditar.Enabled := false;
btnExcluir.Enabled := false;
btnGravar.Enabled := true;
btnCancelar.Enabled := true;
btnPesquisar.Enabled := false;
Panel1.Enabled := true;
if dblTipoJuros.CanFocus then
dblTipoJuros.SetFocus;
setFonteNegrito(false);
end;
procedure TfrmCadastroJuros.controlePESQUISAR;
begin
btnVoltar.Enabled := true;
btnNovo.Enabled := true;
btnEditar.Enabled := true;
btnExcluir.Enabled := true;
btnGravar.Enabled := false;
btnCancelar.Enabled := true;
btnPesquisar.Enabled := true;
Panel1.Enabled := false;
if dblTipoJuros.CanFocus then
dblTipoJuros.SetFocus;
setFonteNegrito(false);
end;
procedure TfrmCadastroJuros.controleSHOW;
begin
btnVoltar.Enabled := true;
btnNovo.Enabled := true;
btnPesquisar.Enabled := true;
btnCancelar.Enabled := false;
btnGravar.Enabled := false;
btnExcluir.Enabled := false;
btnEditar.Enabled := false;
Panel1.Enabled := false;
edtAcrescimo.Clear;
edtMora.Clear;
edtJuros.Clear;
edtDiaAtraso.Clear;
dblTipoJuros.ResetField;
dblStatusGrupo.ResetField;
end;
procedure TfrmCadastroJuros.excluir;
begin
try
if jurosRn.verificaExclusao(Juros) then
raise exception.Create('Não é possível excluir este ...um ou mais juros(s) já estão sendo utilizados!!!');
if Application.MessageBox(PChar('Deseja realmente excluir?'), 'Confirmação', MB_ICONQUESTION+MB_YESNO) = mrYes then
begin
JurosRN.excluir(Juros);
setNovo;
controleEXCLUIR;
end;
except
on E: Exception do
begin
Application.MessageBox(PChar(E.Message), 'Atenção', MB_ICONINFORMATION + MB_OK);
end;
end;
end;
procedure TfrmCadastroJuros.FormCreate(Sender: TObject);
begin
jurosRn := TJurosRN.Create;
juros := TJuros.Create;
tipoJuros := TTipoJuros.Create;
end;
procedure TfrmCadastroJuros.FormShow(Sender: TObject);
begin
dblTipoJuros.LookupDisplay := 'descricao';
dblTipoJuros.LookupField := 'id';
dblTipoJuros.LookupSource := JurosRN.getTipoJuros();
dblStatusGrupo.LookupDisplay := 'descricao';
dblStatusGrupo.LookupField := 'id';
dblStatusGrupo.LookupSource := JurosRN.getStatusTipoJuros();
controleSHOW();
end;
procedure TfrmCadastroJuros.gravar;
begin
try
if dblTipoJuros.Text = '' then
raise exception.Create('O campo Tipo Juros é Obrigatório!');
if edtJuros.Value < 0 then
raise exception.Create('O campo Juros é Obrigatório!');
if edtMora.Value < 0 then
raise exception.Create('O campo Juros Mora é Obrigatório!');
if edtMora.Value < 0 then
raise exception.Create('O campo Acrescimo é Obrigatório!');
if edtDiaAtraso.Text = '' then
raise exception.Create('O campo Dia Atraso é Obrigatório!');
if dblStatusGrupo.Text = '' then
raise exception.Create('O campo Status é Obrigatório!');
tipoJuros.setCodigo(StrToInt(dblTipoJuros.Value));
tipoJuros.setDescricao(dblTipoJuros.text);
juros.setTipoJuros(tipoJuros);
if jurosRn.existeCadastroTipoJuros(TipoJuros) then
raise exception.Create('Este Tipo de Juros já está CADASTRADO!');
juros.setCodigo(idJuros);
juros.setJuros(edtJuros.value);
juros.setMora(edtMora.value);
juros.setAcrescimo(edtAcrescimo.value);
juros.setStatusGrupo(StrToInt(dblStatusGrupo.Value));
juros.setDiaAtraso(StrToInt(edtDiaAtraso.Text));
if bNovo then
JurosRn.incluir(juros);
if bAtualizar then
begin
if Application.MessageBox(PChar('Deseja realmente Atualizar?'), 'Confirmação', MB_ICONQUESTION+MB_YESNO) = mrYes then
JurosRn.editar(juros);
end;
controleGRAVAR;
except
on E: Exception do
begin
Application.MessageBox(PChar(E.Message), 'Atenção', MB_ICONINFORMATION + MB_OK);
end;
end;
end;
procedure TfrmCadastroJuros.setDblValue;
begin
dblTipoJuros.LookupSource := JurosRN.getTipoJuros();
end;
procedure TfrmCadastroJuros.setFonteNegrito(bNegrito: boolean);
begin
if bNegrito then
begin
edtAcrescimo.Font.Style := [fsBold];
edtMora.Font.Style := [fsBold];
edtJuros.Font.Style := [fsBold];
edtDiaAtraso.Font.Style := [fsBold];
dblTipoJuros.Font.Style := [fsBold];
dblStatusGrupo.Font.Style := [fsBold];
end;
if not bNegrito then
begin
edtAcrescimo.Font.Style := [];
edtMora.Font.Style := [];
edtJuros.Font.Style := [];
edtDiaAtraso.Font.Style := [];
dblTipoJuros.Font.Style := [];
dblStatusGrupo.Font.Style := [];
end;
end;
procedure TfrmCadastroJuros.setNovo;
begin
edtAcrescimo.Clear;
edtMora.Clear;
edtJuros.Clear;
edtDiaAtraso.Clear;
dblTipoJuros.ResetField;
dblStatusGrupo.ResetField;
end;
procedure TfrmCadastroJuros.setJuros(var PJuros: TJuros);
begin
juros.setCodigo(Pjuros.getCodigo);
juros.setJuros(Pjuros.getJuros);
juros.setMora(Pjuros.getMora);
juros.setAcrescimo(Pjuros.getAcrescimo);
juros.setDiaAtraso(Pjuros.getDiaAtraso);
juros.setTipoJuros(Pjuros.getTipoJuros);
juros.setStatusGrupo(Pjuros.getStatusGrupo);
idJuros := Juros.getCodigo;
edtAcrescimo.Value := Juros.getAcrescimo;
edtMora.Value := Juros.getMora;
edtJuros.Value := Juros.getJuros;
edtDiaAtraso.Text := IntToStr(Juros.getDiaAtraso);
dblTipoJuros.Value := IntToStr(Juros.getTipoJuros.getCodigo);
dblStatusGrupo.Value := IntToStr(Juros.getStatusGrupo);
controlePESQUISAR;
end;
end.
|
unit LogErros;
interface
uses
Classes;
type
TLogErros = class
private
FDiretorioSistema :String;
FArquivo :TStrings;
private
function GetNomeArquivo: String;
private
procedure AdicionaSeparador;
procedure AdicionaQuebraDeLinha;
public
constructor Create(DiretorioSistema :String);
destructor Destroy; override;
public
procedure AdicionaErro(NomeDaUnit :String; ClasseDaExcecao :String; MensagemErro :String);
public
property NomeArquivo :String read GetNomeArquivo;
end;
implementation
uses
SysUtils,
StrUtils;
const
CAMINHO_ARQUIVO = 'log_erros.txt';
{ TLogErros }
procedure TLogErros.AdicionaErro(NomeDaUnit :String; ClasseDaExcecao :String; MensagemErro :String);
begin
self.AdicionaQuebraDeLinha;
self.AdicionaSeparador;
self.FArquivo.Insert(0, 'Mensagem de erro: ' + MensagemErro);
self.FArquivo.Insert(0, 'Data: ' + FormatDateTime('dd/mm/yyyy', Now) + ' - Hora: '+FormatDateTime('hh:mm:ss', Now));
self.FArquivo.Insert(0, 'Lançada exceção2 ' + ClasseDaExcecao + ' na unit ' + NomeDaUnit);
self.AdicionaSeparador;
self.FArquivo.SaveToFile(self.NomeArquivo);
end;
procedure TLogErros.AdicionaQuebraDeLinha;
begin
self.FArquivo.Insert(0, '');
end;
procedure TLogErros.AdicionaSeparador;
var
Separador :String;
begin
Separador := StringOfChar('=', 150);
self.FArquivo.Insert(0, Separador);
end;
constructor TLogErros.Create(DiretorioSistema :String);
begin
self.FDiretorioSistema := DiretorioSistema;
self.FArquivo := TStringList.Create;
try
self.FArquivo.LoadFromFile(self.NomeArquivo);
except
on E: EFOpenError do begin
self.FArquivo.SaveToFile(self.NomeArquivo);
self.FArquivo.LoadFromFile(self.NomeArquivo);
end;
end;
end;
destructor TLogErros.Destroy;
begin
FreeAndNil(self.FArquivo);
inherited;
end;
function TLogErros.GetNomeArquivo: String;
begin
result := self.FDiretorioSistema + CAMINHO_ARQUIVO;
end;
end.
|
unit uBatInputRockData;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.FileCtrl, Vcl.StdCtrls, StrUtils,
UMainDataModule,UMakeRuleClass, System.ImageList, Vcl.ImgList, Vcl.ComCtrls,
Vcl.ToolWin, Winapi.ActiveX
;
type
TReadDataClass =Class(TObject)
FileDir:String;
Count:Integer;
elapsedMilliseconds : cardinal;
Items:Array of TReadRecord;
CloseThread:Boolean;
ProcessStep:integer;
ExHandle:THandle;
procedure Add(tm:TReadRecord);
Procedure ClearItems;
procedure SetFileName(Value:String);
procedure SetCloseThread(Value:Boolean);
destructor Destroy; override;
constructor Create;
End;
TReadFileData= class (TThread)
private
MyDataSet:TMyDataSet;
MyCommand:TMyCommand;
MyRule:TMakeRuleClass;
Rule_id:integer;
WorkFace_id:string;
ReadClass:TReadDataClass;
procedure FillRuleClass(id:integer);
function ReadJinDaoBasicData: string;
function OneButtonDisposeData:Boolean;
public
procedure Execute ;override;
destructor Destroy; override;
constructor Create(ADOC: TMySqlConnection;Ru_id:integer;
Gzm_id:string;MYClass:TReadDataClass);
end;
TForm_BatInPutData = class(TForm)
GB_SelectFile: TGroupBox;
DriveComboBox1: TDriveComboBox;
DirectoryListBox1: TDirectoryListBox;
Splitter1: TSplitter;
Splitter2: TSplitter;
Panel1: TPanel;
GB_Select_Rule: TGroupBox;
CB_RuleName: TComboBox;
ToolBar1: TToolBar;
AddButton: TToolButton;
EditButton: TToolButton;
SaveButton: TToolButton;
ExitButton: TToolButton;
ImageList2: TImageList;
InputFileListBox: TFileListBox;
Memo_log: TMemo;
ProgressBar1: TProgressBar;
Speed_Label: TLabel;
Timer1: TTimer;
Button2: TButton;
Panel_GzmName: TPanel;
ToolButton1: TToolButton;
Label_Title: TLabel;
RG_JD_Basic: TRadioGroup;
GroupBox1: TGroupBox;
Edit_JD_support: TEdit;
Label39: TLabel;
RG_JD_Time: TRadioGroup;
Splitter3: TSplitter;
But_AutoDraw: TToolButton;
RD_CJ_Type: TRadioGroup;
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure CB_RuleNameClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure AddButtonClick(Sender: TObject);
procedure EditButtonClick(Sender: TObject);
procedure SaveButtonClick(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure ExitButtonClick(Sender: TObject);
procedure ToolButton1Click(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure RG_JD_BasicClick(Sender: TObject);
procedure Edit_JD_supportClick(Sender: TObject);
procedure Edit_JD_supportKeyPress(Sender: TObject; var Key: Char);
procedure But_AutoDrawClick(Sender: TObject);
private
{ Private declarations }
MyDataSet:TMYDataSet;
MyCommand:TMyCommand;
MyRule:TMakeRuleClass;
parentWid,ParentHig:Integer;
Selected_Ruleid:integer;
MyReadDataClass: TReadDataClass;
S_CoalName,S_WorkFaceName:String;
S_Coalid,S_WorkFaceid:string;
TotalTime:Double;
JinDaoBasicSupport:String;
EndSupNumber:integer;
ThreadProcessStep:integer;
ShowScreen:integer;
procedure FillCB_RuleName(CB_RuleName:TComboBox);
function SecectedRuleName(Str:String):Boolean;
function FillMyRuleData(id:Integer;Rule:TMakeRuleClass):Boolean;
function FillMyReadDataClass(Rd:TReadDataClass):Boolean;
procedure AddLOG(log_Str:String);
procedure RefreshTotalTime(Coun:integer;tim:double);
function ReadJinDaoBasicData(Rd:TReadDataClass):Boolean;
function SeekMyRuleJinDaoChanged:Boolean;
function CreateSaveBmpPath:String;
function DelAllSaveFile(aDir:string;Gzmid:integer):Boolean;
procedure FromSaveToBmp(pic_path:string);
procedure SetFromWidthAndHeigth(flag:integer);
public
{ Public declarations }
function MakeJinDaoBasicData:Boolean;
function MakeOtherSupportDate: Boolean;
procedure OneButtonDisposeData;
function GetCloseState:Integer;
end;
var
Form_BatInPutData: TForm_BatInPutData;
MYReadDataThread:TReadFileData;
function IsExsitReadThread(ClassName:String):Boolean;
function CreateBatInputData_inn(AHandle:THandle;ACaption:string;Wid,Hi,Flag:integer):THandle;stdcall;
implementation
{$R *.dfm}
uses MakeDataRule, Lu_Public_BasicModual, StopWatch, PStope_GzmGuidClass,
UFormModifyJinDao, UFormEditPressData, UForm_ContourGraph, RockPresstool,
UForm_LineGraph, UForm_Brand_Bar;
//--------------------------------
function IsExsitReadThread(ClassName:String):Boolean;
var
exitCode: DWord;
begin
if ClassName='MYReadDataThread' then begin
if Assigned(MYReadDataThread) then
GetExitCodeThread(MYReadDataThread.Handle, exitCode);
end else if ClassName='Form_ContourGraph' then begin
if Assigned(Form_ContourGraph) then
GetExitCodeThread(Form_ContourGraph.Handle, exitCode);
end else if ClassName='FormPressTool' then begin
if Assigned(FormPressTool) then
GetExitCodeThread(FormPressTool.Handle, exitCode);
end;
if exitCode = STILL_ACTIVE then begin
Result:=True;
end else begin
Result:=False;
end;
end;
//-------------------------------
function CreateBatInputData_inn(AHandle:THandle;ACaption:string;Wid,Hi,Flag:integer):THandle;stdcall;
begin
if Assigned(Form_BatInPutData) then FreeAndNil(Form_BatInPutData);
Application.Handle:=AHandle;
Form_BatInPutData:=TForm_BatInPutData.Create(Application);
try
with Form_BatInPutData do begin
Caption:=ACaption;
ParentWindow:=Ahandle;
if Hi >Height then
Top :=Round((Hi-Height)/3) else Top :=0;
if Wid> Width then
Left:=Round((Wid-Width)/2) else Left:=0;
//
parentWid:=Wid;
ParentHig:=Hi;
//
SetFromWidthAndHeigth(Flag);
Result:=Form_BatInPutData.Handle ;//函数值
end ;
except
FreeAndNil(Form_BatInPutData);
end;
end;
procedure TForm_BatInPutData.AddButtonClick(Sender: TObject);
var
i:integer;
begin
for I := 0 to InputFileListBox.Count -1 do
InputFileListBox.Selected[i]:=true;
end;
procedure TForm_BatInPutData.AddLOG(log_Str: String);
begin
Memo_Log.Lines.Add(log_str);
end;
procedure TForm_BatInPutData.Button2Click(Sender: TObject);
begin
Self.SaveButton.Click ;
end;
procedure TForm_BatInPutData.But_AutoDrawClick(Sender: TObject);
begin
Create_ConTourGrap(application.Handle,'自动绘图窗体',0,0,1);
FormPressTool.Close ;
// 深度分析
Form_ContourGraph.But_Start_KYFX.Click ;
// 打开 曲线图 绘制界面
CreateLineGraph(application.Handle,'',0,0,0);
Form_ContourGraph.DrawGzm.GraphClass.CycleDataEfficient:=False;//代表从云图中传递数据
Form_LineGraph.SetOpenFormVar(Form_ContourGraph.DrawGzm,
'',
true, // 是否有步距信息
true// 是否打开工具菜单
);
FormPressTool.Close ;
// 变成深度曲线模式
Form_LineGraph.Main_Line_DrawClass.GraphClass.YAxisType :=1;
Form_LineGraph.DrawLineGraph.NextDataDisp:=0; // 第一屏
Form_LineGraph.DrawLineGraph.MarkerStep:=true;
Form_LineGraph.RefreshMyGraphChart(true);
Form_LineGraph.DrawLineGraph.NextDataDisp:=1; //第二屏
Form_LineGraph.RefreshMyGraphChart(true);
Form_LineGraph.DrawLineGraph.NextDataDisp:=2; //第三屏
Form_LineGraph.RefreshMyGraphChart(true);
Form_LineGraph.Close ;
//打开直方图模式
CreateBand_Bar(ExHandle,'',0,0,0);
Form_ContourGraph.DrawGzm.BarMarks.Fromcontour:=true;;//代表从云图中传递数据
if Assigned(Form_Band_Bar) then begin
Form_Band_Bar.InitForm(Form_ContourGraph.DrawGzm) ;
Form_Band_Bar.SetOpenFormVar( '',
False,
true// 是否打开工具菜单
);
end;
FormPressTool.Close ;
// while IsExsitReadThread('FormPressTool') do
// Sleep(100);
Form_Band_Bar.Main_panel.Refresh;
Form_Band_Bar.AutoSaveOnesupportOneBMP(-1) ;
Form_Band_Bar.Close ;
Form_ContourGraph.Close ;
end;
procedure TForm_BatInPutData.CB_RuleNameClick(Sender: TObject);
begin
if SecectedRuleName(CB_RuleName.Text ) then begin
self.SaveButton.Enabled :=true;
end else begin
if InputFileListBox.SelCount <1 then begin
messagebox(self.Handle,'数据规则可能有问题,请通过测试后再来!','系统提示',mb_iconerror+mb_ok);
exit;
end;
self.SaveButton.Enabled :=False;
end;
end;
function TForm_BatInPutData.CreateSaveBmpPath: String;
var
BmpPath:WideString;
begin
BmpPath:=Public_Basic.Get_MyModulePath+'SaveBmp\KYFX\';
if not DirectoryExists(BmpPath) then
ForceDirectories(BmpPath);
Result:=BmpPath;
end;
function TForm_BatInPutData.DelAllSaveFile(aDir:string;Gzmid: integer): Boolean;
var
vSearch: TSearchRec;
vRet: integer;
vKey: string;
begin
if aDir[Length(aDir)] <> '\' then
aDir := aDir + '\';
vKey := aDir + '*.*';
vRet := FindFirst(vKey, faanyfile, vSearch);
while vRet = 0 do begin
if ((vSearch.Attr and fadirectory) = fadirectory) then begin
if (vSearch.Name <> '.') and (vSearch.name <> '..') then
DelAllSaveFile(aDir + vSearch.name,0);
end
else begin
if ((vSearch.Attr and fadirectory) <> fadirectory) then begin
{System.Sysutils.}DeleteFile(aDir + vSearch.name);
end;
end;
vRet := FindNext(vSearch);
end; //while
{System.SysUtils.}FindClose(vSearch);
// Removedir(aDir); // 如果需要删除文件夹则添加
result := True;
end;
procedure TForm_BatInPutData.EditButtonClick(Sender: TObject);
var
i:integer;
begin
for I := 0 to InputFileListBox.Count -1 do
InputFileListBox.Selected[i]:=False;
end;
procedure TForm_BatInPutData.Edit_JD_supportClick(Sender: TObject);
begin
Edit_JD_support.SetFocus;
end;
procedure TForm_BatInPutData.Edit_JD_supportKeyPress(Sender: TObject;
var Key: Char);
begin
if not (key in ['0'..'9',#8]) then key:=#0 ;
end;
procedure TForm_BatInPutData.ExitButtonClick(Sender: TObject);
begin
CloseQuery ;
end;
procedure TForm_BatInPutData.FillCB_RuleName(CB_RuleName: TComboBox);
var
Sql:String;
begin
CB_RuleName.Clear ;
try
sql:='select id,RuleName from inputRule ';
MyDataSet.Close ;
MyDataSet.CommandText :=sql;
if MyDataSet.Open then
while not MyDataSet.Eof do begin
CB_RuleName.Items.Add(MyDataSet.FieldByName('id').AsString + '_' +
MyDataSet.FieldByName('RuleName').AsString );
MyDataSet.Next ;
end;
finally
MyDataSet.Close ;
if CB_RuleName.Items.Count >0 then begin
CB_RuleName.ItemIndex :=0;
SaveButton.Enabled :=true;
SecectedRuleName(CB_RuleName.Text )
end;
end;
end;
function TForm_BatInPutData.FillMyReadDataClass(Rd: TReadDataClass): Boolean;
var
i:integer;
tm: TReadRecord;
begin
Result:=False;
Rd.FileDir :=self.DirectoryListBox1.Directory ;
for I := 0 to InputFileListBox.Count -1 do begin
if not InputFileListBox.Selected[i] then continue;
if InputFileListBox.Items[i]= Rd.Items[0].FileName then continue;
tm.FileName:=InputFileListBox.Items[i];
tm.elapsedMilliseconds :=0;
tm.RecordNumber :=0;
tm.ReadFin :=False;
tm.printed :=False;
tm.Processing :=0;
Rd.Add(tm);
end;
end;
function TForm_BatInPutData.FillMyRuleData(id: Integer;
Rule: TMakeRuleClass): Boolean;
var
Sql:string;
tmp:TBasicDataParm;
begin
{
inputRule RuleName,FileSufix,LineSplitStr,SupProFlag,SupUpper, ' +
' TimeProFlag,TimeUpper,TimeString )
InputRule_DataType Ruleid,DataType,DataBh,DataProFlag,DataUpper) values ( ';
}
try
sql:='select * from inputRule where id= ' +IntTostr(id);
Rule.ClearDataS ;
MyDataSet.Close ;
MyDataSet.CommandText :=sql;
if MyDataSet.Open then begin
Rule.RuleId:=MyDataSet.FieldByName('id').AsInteger;
Rule.RuleName :=MyDataSet.FieldByName('RuleName').AsString;
Rule.FileSuffix :=MyDataSet.FieldByName('FileSufix').AsString;
Rule.LineSplitTag :=MyDataSet.FieldByName('LineSplitStr').AsString;
Rule.SupProRec.TagStr :=MyDataSet.FieldByName('SupProFlag').AsString;
Rule.SupProRec.UpperCase :=MyDataSet.FieldByName('SupUpper').AsInteger;
Rule.DTProRec.TagStr :=MyDataSet.FieldByName('TimeProFlag').AsString;
Rule.DTProRec.UpperCase :=MyDataSet.FieldByName('TimeUpper').AsInteger;
Rule.DataTimeStr :=MyDataSet.FieldByName('TimeString').AsString;
if MyDataSet.FieldByName('MoveSupTag').AsInteger=1 then begin
Rule.MoveSuppFlag:=true;
Rule.MoveProRec.UpperCase:=MyDataSet.FieldByName('MoveSuP_Upper').AsInteger;
Rule.MoveSupp_Equal :=MyDataSet.FieldByName('MoveSup_Equal').AsString;
Rule.MoveProRec.TagStr :=MyDataSet.FieldByName('MoveSup_ProFlag').AsString;
Rule.MoveSupp_Value:=MyDataSet.FieldByName('MoveSup_Value').AsInteger;
end else begin
Rule.MoveSuppFlag:=False;
Rule.MoveProRec.UpperCase:=0;
Rule.MoveSupp_Equal :='';
Rule.MoveProRec.TagStr :='';
Rule.MoveSupp_Value:=0;
end;
Rule.MuleData_MAX_AGV:= MyDataSet.FieldByName('Mult_Max_AGV').AsInteger;
end;
MyDataSet.Close ;
sql:='select * from InputRule_DataType where Ruleid= ' +IntTostr(Rule.RuleId);
MyDataSet.CommandText :=sql;
if MyDataSet.Open then
while not MyDataSet.Eof do begin
tmp.DataName :=MyDataSet.FieldByName('DataType').AsString;
tmp.DataBh :=MyDataSet.FieldByName('DataBh').AsInteger ;
tmp.TagStr :=MyDataSet.FieldByName('DataProFlag').AsString;
tmp.UpperCase :=MyDataSet.FieldByName('DataUpper').AsInteger ;
tmp.DataUnit:=MyDataSet.FieldByName('DataUnit').AsString;
Rule.AddBasicDataS(tmp);
MyDataSet.Next ;
end;
finally
MyDataSet.Close ;
end;
end;
procedure TForm_BatInPutData.FormActivate(Sender: TObject);
begin
FillCB_RuleName(self.CB_RuleName );
Label_Title.AutoSize :=False;
Label_Title.WordWrap :=False;
Label_Title.Caption :='当前操作的是【'+s_CoalName+'】所属的【'+S_WorkFaceName+'】工作面';
Label_Title.WordWrap :=true;
//判断与工作面相关的数据表是否创建,如果没有创建,再此创建
if not MainDataModule.IsExsitTableName('D_'+S_WorkFaceid+'_BasicData') then begin
MainDataModule.CreateTable('2',MainDataModule.DataType,S_WorkFaceid,'') ;
end;
end;
procedure TForm_BatInPutData.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
var
t_s:string;
pic_Path:string;
begin
t_s:='正在处理导入数据界面不能关闭,'+#13#10 +'如果关闭,导入将终止,你确认么?';
if IsExsitReadThread('MYReadDataThread') then begin
if Application.MessageBox(Pwidechar(t_s),'提示',MB_OKCANCEL+MB_ICONQUESTION) =1 then begin
{发出关闭线程的指令}
MyReadDataClass.SetCloseThread(true);
while IsExsitReadThread('MYReadDataThread') do begin
MYReadDataThread.Terminate;
MyReadDataClass.SetCloseThread(true);
sleep(500);
end;
ShowScreen:=0;
end else begin
CanClose:=False;
exit;
end;
end;
Pic_Path :=Public_Basic.Get_MyModulePath+'saveBmp\CoalBMP\OneCoal'+'_8_1.BMP';
FromSaveToBmp(Pic_Path);
{关闭窗体,还得需要发出Close命令}
if Assigned(Form_BatInPutData) then FreeAndNil(Form_BatInPutData);
end;
procedure TForm_BatInPutData.FormCreate(Sender: TObject);
begin
if not Assigned(MyRule) then
MyRule:=TMakeRuleClass.Create(MainDataModule.ExConn); ;
if not Assigned(MyReadDataClass) then
MyReadDataClass:=TReadDataClass.Create ;
MyDataSet:=TMYDataSet.Create(nil);
MyCommand:=TMyCommand.Create(nil);
MyDataSet.MySqlConnection :=MainDataModule.ExConn;
MyCommand.MySqlConnection :=MainDataModule.ExConn;
//
MainDataModule.ReadPublicUsedMkInfoFromFile;
s_CoalName :=MainDataModule.Coal_Name;
S_WorkFaceName :=MainDataModule.WorkFace_Name;
S_Coalid:=MainDataModule.Coal_id ;
S_WorkFaceid:=MainDataModule.WorkFace_id;
//
Selected_Ruleid:=-1;
//判断与工作面相关的数据表是否创建,如果没有创建,再此创建
if not MainDataModule.IsExsitTableName('D_'+S_WorkFaceid+'_BasicData') then begin
MainDataModule.CreateTable('2',MainDataModule.DataType,S_WorkFaceid,'') ;
end;
end;
procedure TForm_BatInPutData.FormDestroy(Sender: TObject);
begin
if Assigned(MyRule) then FreeAndNil(MyRule);
if Assigned(MyReadDataClass) then FreeAndNil(MyReadDataClass);
FreeAndNil(MyDataSet);
FreeAndNil(MyCommand);
end;
procedure TForm_BatInPutData.FormShow(Sender: TObject);
begin
MyRule.DisPoseCycleDataS.Set_WorkFaceId(S_WorkFaceid);
MyRule.DisPoseCycleDataS.ReadWorkFaceInforMation ;
RG_JD_Basic.ItemIndex :=MyRule.DisPoseCycleDataS.MyWokFace_Info.JinDao_Basic;
Edit_JD_support.Text:=intTostr(MyRule.DisPoseCycleDataS.MyWokFace_Info.JinDao_Support);
RG_JD_time.ItemIndex:=MyRule.DisPoseCycleDataS.MyWokFace_Info.JinDao_Time;
RD_CJ_Type.ItemIndex:=MyRule.DisPoseCycleDataS.MyWokFace_Info.Jindao_DataType;
EndSupNumber:= MyRule.DisPoseCycleDataS.GetFGzmEndSupNumber(S_WorkFaceid);
end;
procedure TForm_BatInPutData.FromSaveToBmp(pic_path: string);
var
BitRect: TRect;
Bitmap: TBitmap;
FScreenCanvas: TCanvas;
begin
Bitmap := TBitmap.Create;
try
Bitmap.SetSize(Self.ClientWidth, Self.ClientHeight);
BitRect.Left := 0;
BitRect.Top := 0;
BitRect.Right := BitRect.Left + Bitmap.Width;
BitRect.Bottom := BitRect.Top + Bitmap.Height;
FScreenCanvas := TCanvas.Create;
FScreenCanvas.Handle := Self.Canvas.Handle;
Bitmap.Canvas.Lock;
Bitmap.Canvas.CopyRect(BitRect, FScreenCanvas, Self.ClientRect);
Bitmap.Canvas.Unlock;
Bitmap.SaveToFile(pic_path);
finally
Bitmap.Free;
end;
end;
function TForm_BatInPutData.GetCloseState: Integer;
begin
Result:=ShowScreen;
end;
function TForm_BatInPutData.MakeJinDaoBasicData: Boolean;
var
t_s:string;
tm: TReadRecord;
begin
Result:=true;
MyRule.SetUsed_WorkFaceId(S_WorkFaceid);
if not ReadJinDaoBasicData(MyReadDataClass ) then begin
t_s:='你选择的文件夹里面没有支架编号为【'+JinDaoBasicSupport+'】的数据' +#13#10
+'该支架数据为提取进刀数,如确实没有请到进刀录入界面进行修改!';
Application.MessageBox(Pwidechar(t_s),'提示',MB_OK+MB_ICONQUESTION);
Result:=False;
end else begin
MyReadDataClass.ClearItems ;
tm.FileName:=ChangeFileExt(JinDaoBasicSupport,'.'+MyRule.FileSuffix);
tm.elapsedMilliseconds :=0;
tm.RecordNumber :=0;
tm.ReadFin :=False;
tm.printed :=False;
tm.Processing :=0;
MyReadDataClass.Add(tm);
MakeOtherSupportDate;
end;
end;
function TForm_BatInPutData.MakeOtherSupportDate: Boolean;
var
sql:string;
t_s:string;
begin
Result:=False;
if InputFileListBox.SelCount <1 then begin
messagebox(self.Handle,'你没有选中任何文件,无法导入数据!','系统提示',mb_iconerror+mb_ok);
exit;
end;
t_s:=' 你确定要对选中的【'+IntToStr(self.InputFileListBox.SelCount)+'】个数据文件进行导入分析操作么?' + #13#10 +
'导入数据会花费很长时间,如数据导入开始,请尽量不要停止, ' + #13#10 +
'也不要对该工作面的矿压数据进行相关操作,多谢合作!';
if Application.MessageBox(Pwidechar(t_s),'提示',MB_OKCANCEL+MB_ICONWARNING) =2 then exit;
// 开始导入数据
// 填充读入数据的类
FillMyReadDataClass(MyReadDataClass);
{发出执行指令}
MyReadDataClass.SetCloseThread(False);
// 制定 处理过程的 阶段
ThreadProcessStep:=5;
MyReadDataClass.ProcessStep :=ThreadProcessStep;
MyReadDataClass.ExHandle :=Application.Handle ;
MYReadDataThread:=TReadFileData.Create(MainDataModule.ExConn,Selected_Ruleid,
S_WorkFaceid,MyReadDataClass);
MYReadDataThread.FreeOnTerminate:=true;
MYReadDataThread.Resume;
Memo_Log.Clear ;
Timer1.Enabled :=true;
self.AddLOG('数据分析开始....');
Result:=True;
end;
procedure TForm_BatInPutData.OneButtonDisposeData;
begin
end;
function TForm_BatInPutData.ReadJinDaoBasicData(Rd:TReadDataClass): Boolean;
var
i:integer;
tm: TReadRecord;
FiLeName:String;
begin
Result:=False;
JinDaoBasicSupport:= MyRule.DisPoseCycleDataS.GetJinDaoBasicSupport;
//
Rd.ClearItems ;
Rd.FileDir :=self.DirectoryListBox1.Directory ;
for I := 0 to InputFileListBox.Count -1 do begin
FiLeName:= ExtractFileName(ChangeFileExt(InputFileListBox.Items[i],''));
if FiLeName = UpperCase(Trim(JinDaoBasicSupport)) then begin
tm.FileName:=InputFileListBox.Items[i];
tm.elapsedMilliseconds :=0;
tm.RecordNumber :=0;
tm.ReadFin :=False;
tm.printed :=False;
tm.Processing :=0;
Rd.Add(tm);
Result:=true;
break;
end;
end;
end;
procedure TForm_BatInPutData.RefreshTotalTime(Coun: integer; tim: double);
var
Min,Sec:integer;
begin
if TotalTime < (Coun-2)*30 + ThreadProcessStep*10 then TotalTime:=(Coun-2)*30+ThreadProcessStep*10;
if TotalTime > (Coun)*30 +ThreadProcessStep*10 then TotalTime:=(Coun)*30+ThreadProcessStep*10;
TotalTime:= TotalTime-tim;
if TotalTime <0 then TotalTime:=30;
Min:=trunc(TotalTime) div 60;
Sec:=trunc(TotalTime ) mod 60;
if Min>0 then begin
Speed_Label.Caption :='预计数据导入还需【'+IntToStr(Min)+'】分【'+IntToStr(Sec)+'】秒';
end else begin
Speed_Label.Caption :='预计数据导入还需【'+IntToStr(Sec)+'】秒';
end;
end;
procedure TForm_BatInPutData.RG_JD_BasicClick(Sender: TObject);
begin
if RG_JD_Basic.ItemIndex =0 then begin
self.Edit_JD_support.Text:='10';
end else if RG_JD_Basic.ItemIndex =1 then begin
Edit_JD_support.Text:=intToStr(EndSupNumber div 2 );
end else begin
Edit_JD_support.Text:=intToStr(EndSupNumber-10 );
end;
end;
procedure TForm_BatInPutData.SaveButtonClick(Sender: TObject);
begin
TotalTime:=10000;
//看 MyRule 里面的数据是否改变
if SeekMyRuleJinDaoChanged then
MyRule.DisPoseCycleDataS.SaveWorkFaceInforMation ;
if Selected_Ruleid <1 then
if not SecectedRuleName(CB_RuleName.Text ) then exit;
if not MakeJinDaoBasicData then exit ;
ShowScreen:=2;
end;
function TForm_BatInPutData.SecectedRuleName(Str: String):Boolean;
begin
Result:=False;
Selected_Ruleid:=public_Basic.StrToInt_lu(LeftStr(Str,pos('_',Str)-1));
if Selected_Ruleid >0 then begin
FillMyRuleData(Selected_Ruleid,MyRule);
InputFileListBox.Mask :='*.' +MyRule.FileSuffix;
REsult:=True;
end;
end;
function TForm_BatInPutData.SeekMyRuleJinDaoChanged: Boolean;
var
tmpSup:integer;
begin
Result:=False;
tmpSup:=public_Basic.StrToInt_lu(Trim(Edit_JD_support.Text)) ;
if tmpSup <1 then begin
exit;
end;
if RG_JD_Basic.ItemIndex <> MyRule.DisPoseCycleDataS.MyWokFace_Info.JinDao_Basic then begin
MyRule.DisPoseCycleDataS.MyWokFace_Info.JinDao_Basic:=RG_JD_Basic.ItemIndex ;
Result:=true;
end;
if tmpSup <> MyRule.DisPoseCycleDataS.MyWokFace_Info.JinDao_Support then begin
MyRule.DisPoseCycleDataS.MyWokFace_Info.JinDao_Support:=tmpSup ;
Result:=true;
end;
if RG_JD_time.ItemIndex <> MyRule.DisPoseCycleDataS.MyWokFace_Info.JinDao_Time then begin
MyRule.DisPoseCycleDataS.MyWokFace_Info.JinDao_Time:=RG_JD_time.ItemIndex ;
Result:=true;
end;
if RD_CJ_Type.ItemIndex <> MyRule.DisPoseCycleDataS.MyWokFace_Info.Jindao_DataType then begin
MyRule.DisPoseCycleDataS.MyWokFace_Info.Jindao_DataType:=RD_CJ_Type.ItemIndex ;
Result:=true;
end;
end;
procedure TForm_BatInPutData.SetFromWidthAndHeigth(flag: integer);
begin
if Flag=1 then begin
WindowState:= wsNormal;
ShowScreen:=1;
Show;
SetFocus;
end else begin
ShowScreen:=0;
WindowState:= wsNormal;
Show;
SetFocus;
end;
end;
procedure TForm_BatInPutData.Timer1Timer(Sender: TObject);
var
i:integer;
Hou,Min,sec:integer;
st:String;
LabDisp:Boolean;
begin
Hou:=0;Min:=0; LabDisp:=False;
self.ProgressBar1.StepIt ;
for I := 0 to MyReadDataClass.count -1 do begin
if (not MyReadDataClass.Items[i].printed ) and (MyReadDataClass.Items[i].ReadFin) then begin
St:='& 文件['+MyReadDataClass.Items[i].FileName+']导入成功!' + ' / 导入记录['+Inttostr(MyReadDataClass.Items[i].RecordNumber)+']条'
+ ' / 历时['+FormatFloat('0.00',MyReadDataClass.Items[i].elapsedMilliseconds/1000)+']秒' ;
AddLOG(St);
MyReadDataClass.Items[i].printed:=true;
end else if (not MyReadDataClass.Items[i].printed ) and (not MyReadDataClass.Items[i].ReadFin) and
(MyReadDataClass.Items[i].Processing > 0) then begin
if MyReadDataClass.Items[i].PrintProc <> trunc(MyReadDataClass.Items[i].Processing) div 30 then begin
AddLOG(' --导入数据文件['+MyReadDataClass.Items[i].FileName+']进展['+FormatFloat('0',MyReadDataClass.Items[i].Processing)+'%]');
MyReadDataClass.Items[i].PrintProc := trunc(MyReadDataClass.Items[i].Processing) div 30 ;
end;
end;
if ( MyReadDataClass.Items[i].printed=False ) and (not LabDisp) then begin
RefreshTotalTime(MyReadDataClass.count -i,0.5);
LabDisp:=true;
end;
end;
// 判断过程
if ThreadProcessStep<> MyReadDataClass.ProcessStep then begin
if MyReadDataClass.ProcessStep=4 then begin
AddLOG('=======================================');
AddLOG('& 系统正在处理进刀数据,也可以到【进尺维护】界面修改!');
end;
if MyReadDataClass.ProcessStep=3 then begin
AddLOG('& 进刀数据处理完成!');
AddLOG('=======================================');
AddLOG('& 系统正在提取每一刀的数据,也可以到【数据维护】界面修改!');
end;
if MyReadDataClass.ProcessStep=2 then begin
AddLOG('& 每一刀压力数据处理完成处理完成!');
AddLOG('=======================================');
//AddLOG('& 系统正在提取每一刀的数据,也可以到【数据维护】界面修改!');
end;
RefreshTotalTime(0,0.5);
ThreadProcessStep:= MyReadDataClass.ProcessStep ;
end;
//数据导入完成
if (not IsExsitReadThread('MYReadDataThread') ) then begin
AddLOG('=======================================');
AddLOG('& 所有文件导入完成!');
sec:=Round(MyReadDataClass.elapsedMilliseconds/1000);
Min:=trunc(Sec/60);
if Min >0 then Sec:= Sec mod 60;
Hou:= Trunc(Min /60);
if Hou >0 then Min:=MIn mod 60;
if Hou >0 then begin
AddLOG('& 导入文件历时['+IntTostr(hou)+']小时['+IntTostr(Min)+']分钟['+IntTostr(Sec)+']秒');
Speed_Label.Caption :='导入数据完成,共历时['+IntTostr(hou)+']小时['+IntTostr(Min)+']分钟['+IntTostr(Sec)+']秒';
end else if Min >0 then begin
AddLOG('& 导入文件历时['+IntTostr(Min)+']分钟['+IntTostr(Sec)+']秒');
Speed_Label.Caption :='导入数据完成,共历时['+IntTostr(Min)+']分钟['+IntTostr(Sec)+']秒';
end else begin
AddLOG('& 导入文件历时['+IntTostr(Sec)+']秒');
Speed_Label.Caption :='导入数据完成,共历时['+IntTostr(Sec)+']秒';
end;
Timer1.Enabled :=False;
ProgressBar1.Position := ProgressBar1.Max ;
But_AutoDraw.Enabled :=true;
end;
end;
procedure TForm_BatInPutData.ToolButton1Click(Sender: TObject);
begin
CreateMakeRule_inn(Application.Handle,'数据规则补充界面',ParentWid,ParentHig);
end;
{ TReadFileData }
constructor TReadFileData.Create(ADOC: TMySqlConnection;Ru_id:integer;Gzm_id:string;MYClass:TReadDataClass);
{
ADOC:数据库的连接
id: 数据规则的编号,便于到数据库中查找
MYClass: 读取数据的规则 类
}
begin
inherited Create(true) ;
FreeOnTerminate := True;
MyDataSet:=TMyDataSet.Create(nil);
MyDataSet.MySqlConnection:=ADOC;
MyCommand:=TMyCommand.Create(nil);
MyCommand.MySqlConnection :=ADOC;
if not Assigned(MyRule) then
MyRule:=TMakeRuleClass.Create(ADOC) ;
//
ReadClass:=MYClass;;
Rule_id:=Ru_id;
WorkFace_id:=Gzm_id;
//Fill
FillRuleClass(Rule_id);
end;
destructor TReadFileData.Destroy;
begin
if Assigned(MyRule) then FreeAndNil(MyRule);
FreeAndNil(MyDataSet);
FreeAndNil(MyCommand);
inherited;
end;
procedure TReadFileData.Execute;
var
i,S_C:Integer;
Sw1,sw2:TStopWatch;
BasicSupport:Integer;
begin
inherited;
CoInitialize(nil);
Sw1:=TstopWatch.Create(); Sw2:=TstopWatch.Create();
ReadClass.elapsedMilliseconds:=0;
SW1.Start;
MyRule.SetUsed_WorkFaceId(WorkFace_id);
//把进刀数进行确认
BasicSupport:=Public_Basic.StrToInt_lu(ReadJinDaoBasicData);
MyRule.DisPoseCycleDataS.BasicJindao.StartTime :=-1;
// 继续其他数据
for I := 0 to ReadClass.Count -1 do begin
{如果系统退出}
if ReadClass.CloseThread then exit;
SW2.Start;
S_C:=-1;
// 清除这个类里面的数据
MyRule.ClearAnal_DataS ;
//处理第一个支架 该支架是 判定进刀的基本支架
if i=0 then begin
S_C:= MyRule.LoadDataFromFlie(ReadClass.Items[i],ReadClass.FileDir + '\' +ReadClass.Items[i].FileName,-1);
end else begin
// 把该文件中的记录追加到类
S_C:= MyRule.LoadDataFromFlie(ReadClass.Items[i],ReadClass.FileDir + '\' +ReadClass.Items[i].FileName,BasicSupport);
end;
if S_C>=0 then begin
SW2.stop;
ReadClass.Items[i].RecordNumber:=S_C;
ReadClass.Items[i].elapsedMilliseconds:=sw2.ElapsedMilliseconds;
ReadClass.Items[i].ReadFin :=true;
end;
end;
// 继续处理下一个阶段
OneButtonDisposeData;
SW1.Stop;
ReadClass.elapsedMilliseconds := sw1.ElapsedMilliseconds;
FreeAndNil(sw1);
FreeAndNil(sw2);
CoUnInitialize;
end;
procedure TReadFileData.FillRuleClass(id: integer);
var
Sql:string;
tmp:TBasicDataParm;
begin
{
inputRule RuleName,FileSufix,LineSplitStr,SupProFlag,SupUpper, ' +
' TimeProFlag,TimeUpper,TimeString )
InputRule_DataType Ruleid,DataType,DataBh,DataProFlag,DataUpper) values ( ';
}
try
sql:='select * from inputRule where id= ' +IntTostr(id);
MyRule.ClearDataS ;
MyDataSet.Close ;
MyDataSet.CommandText :=sql;
if MyDataSet.Open then begin
MyRule.RuleId:=MyDataSet.FieldByName('id').AsInteger;
MyRule.RuleName :=MyDataSet.FieldByName('RuleName').AsString;
MyRule.FileSuffix :=MyDataSet.FieldByName('FileSufix').AsString;
MyRule.LineSplitTag :=MyDataSet.FieldByName('LineSplitStr').AsString;
MyRule.SupProRec.TagStr :=MyDataSet.FieldByName('SupProFlag').AsString;
MyRule.SupProRec.UpperCase :=MyDataSet.FieldByName('SupUpper').AsInteger;
MyRule.DTProRec.TagStr :=MyDataSet.FieldByName('TimeProFlag').AsString;
MyRule.DTProRec.UpperCase :=MyDataSet.FieldByName('TimeUpper').AsInteger;
MyRule.DataTimeStr :=MyDataSet.FieldByName('TimeString').AsString;
if MyDataSet.FieldByName('MoveSupTag').AsInteger=1 then begin
MyRule.MoveSuppFlag:=true;
MyRule.MoveProRec.UpperCase:=MyDataSet.FieldByName('MoveSuP_Upper').AsInteger;
MyRule.MoveSupp_Equal :=MyDataSet.FieldByName('MoveSup_Equal').AsString;
MyRule.MoveProRec.TagStr :=MyDataSet.FieldByName('MoveSup_ProFlag').AsString;
MyRule.MoveSupp_Value:=MyDataSet.FieldByName('MoveSup_Value').AsInteger;
end else begin
MyRule.MoveSuppFlag:=False;
MyRule.MoveProRec.UpperCase:=0;
MyRule.MoveSupp_Equal :='';
MyRule.MoveProRec.TagStr :='';
MyRule.MoveSupp_Value:=0;
end;
MyRule.MuleData_MAX_AGV:= MyDataSet.FieldByName('Mult_Max_AGV').AsInteger;
end;
MyDataSet.Close ;
sql:='select * from InputRule_DataType where Ruleid= ' +IntTostr(MyRule.RuleId);
MyDataSet.CommandText :=sql;
if MyDataSet.Open then
while not MyDataSet.Eof do begin
tmp.DataName :=MyDataSet.FieldByName('DataType').AsString;
tmp.DataBh :=MyDataSet.FieldByName('DataBh').AsInteger ;
tmp.DataType :=TSupportDataType(tmp.DataBh);
tmp.TagStr :=MyDataSet.FieldByName('DataProFlag').AsString;
tmp.UpperCase :=MyDataSet.FieldByName('DataUpper').AsInteger ;
tmp.DataUnit:=MyDataSet.FieldByName('DataUnit').AsString;
MyRule.AddBasicDataS(tmp);
MyDataSet.Next ;
end;
finally
MyDataSet.Close ;
end;
end;
function TReadFileData.OneButtonDisposeData: Boolean;
var
tmp_JinDao:TModifyJinDao_From ;
tmp_RockPress:TEdit_PressDataForm;
tmp_ContourGraph:TForm_ContourGraph;
tmp_tool: TFormPressTool;
tmp_LineGrahp:TForm_LineGraph;
tmp_Band_Bar:TForm_Band_Bar;
begin
// 完成了一个阶段
Dec(ReadClass.ProcessStep);
{ 把进尺 的信息自动完成}
try
tmp_JinDao:=TModifyJinDao_From.Create(nil) ;
with tmp_jinDao do begin
InitForm;
AutoLoadInputJinDao(0);
SaveJinDaoIntoDAtaBase(0);
end;
finally
FreeAndNil(tmp_JinDao);
end;
// 完成了一个阶段
Dec(ReadClass.ProcessStep);
{把数据维护信息自动完成}
try
tmp_RockPress:=TEdit_PressDataForm.Create(nil);
with tmp_RockPress do begin
InitForm;
UpdateBatInputData(0);
end;
finally
FreeAndNil(tmp_RockPress);
end;
// 完成了一个阶段
Dec(ReadClass.ProcessStep);
end;
function TReadFileData.ReadJinDaoBasicData: string;
begin
Result:='';
if not MyRule.DisPoseCycleDataS.ReadWorkFaceInforMation then
exit;
Result:= MyRule.DisPoseCycleDataS.GetJinDaoBasicSupport;
end;
{ TReadDataClass }
procedure TReadDataClass.Add(tm: TReadRecord);
begin
inc(Count);
setlength(Items,Count);
Items[Count-1]:=tm;
Items[Count-1].CloseThread:=False;
end;
procedure TReadDataClass.ClearItems;
begin
setlength(Items,0);
Count:=0;
end;
constructor TReadDataClass.Create;
begin
Count:=0;
ProcessStep:=0;
CloseThread:=False;
end;
destructor TReadDataClass.Destroy;
begin
inherited;
end;
procedure TReadDataClass.SetCloseThread(Value: Boolean);
var
i:integer;
begin
CloseThread:=Value;
for I := 0 to Count-1 do
Items[i].CloseThread:=Value;
end;
procedure TReadDataClass.SetFileName(Value: String);
begin
self.FileDir :=Value;
end;
end. // end unit
|
unit Delphi.Mocks.Tests.MethodData;
interface
uses
SysUtils,
DUnitX.TestFramework,
Rtti,
Delphi.Mocks,
Delphi.Mocks.Interfaces;
type
{$M+}
ISimpleInterface = interface
function MissingArg(Value: Integer): Integer;
end;
{$M-}
TObjectToTest = class
private
FPropertyToTest: Integer;
public
FieldToTest: Integer;
property PropertyToTest: Integer read FPropertyToTest write FPropertyToTest;
end;
TAnotherObject = class(TObjectToTest);
TAndAnotherObject = class(TObjectToTest);
{$M+}
[TestFixture]
TTestMethodData = class
published
[Test, Ignore]
procedure Expectation_Before_Verifies_To_True_When_Prior_Method_Called_Atleast_Once;
[Test]
procedure AllowRedefineBehaviorDefinitions_IsTrue_RedefinedIsAllowed;
[Test]
procedure AllowRedefineBehaviorDefinitions_IsFalse_ExceptionIsThrown_WhenRedefining;
[Test]
procedure AllowRedefineBehaviorDefinitions_IsFalse_NoExceptionIsThrown_WhenAddingNormal;
[Test]
procedure AllowRedefineBehaviorDefinitions_IsTrue_OldBehaviorIsDeleted;
[Test]
procedure BehaviourMustBeDefined_IsFalse_AndBehaviourIsNotDefined_RaisesNoException;
[Test]
procedure BehaviourMustBeDefined_IsTrue_AndBehaviourIsNotDefined_RaisesException;
[Test]
procedure AllowRedefineBehaviorDefinitions_IsTrue_NoExceptionIsThrown_WhenMatcherAreDifferent;
[Test]
procedure Expectations_NoExceptionIsThrown_WhenMatcherAreDifferent;
end;
{$M-}
implementation
uses
Delphi.Mocks.Helpers,
Delphi.Mocks.MethodData,
classes, System.TypInfo, StrUtils, Delphi.Mocks.ParamMatcher;
{ TTestMethodData }
procedure TTestMethodData.Expectations_NoExceptionIsThrown_WhenMatcherAreDifferent;
var
methodData : IMethodData;
someParam,
someValue1,
someValue2 : TValue;
LObjectToTest : TObjectToTest;
LAnotherObject: TAnotherObject;
LAndAnotherObject: TAndAnotherObject;
begin
LObjectToTest := TObjectToTest.Create;
LAnotherObject := TAnotherObject.Create;
LAndAnotherObject := TAndAnotherObject.Create;
try
someValue1 := TValue.From<TAnotherObject>(LAnotherObject);
someValue2 := TValue.From<TAndAnotherObject>(LAndAnotherObject);
someParam := TValue.From<TObjectToTest>(LObjectToTest);
methodData := TMethodData.Create('x', 'x', TSetupMethodDataParameters.Create(FALSE, FALSE, FALSE));
methodData.NeverWhen([nil, someParam], [TMatcher<TAnotherObject>.Create(function(value : TAnotherObject) : boolean
begin
result := true;
end)]);
Assert.WillNotRaise(procedure
begin
methodData.NeverWhen([nil, someParam], [TMatcher<TAndAnotherObject>.Create(function(value : TAndAnotherObject) : boolean
begin
result := true;
end)]);
end, EMockSetupException);
finally
LObjectToTest.Free;
LAnotherObject.Free;
LAndAnotherObject.Free;
end;
end;
procedure TTestMethodData.Expectation_Before_Verifies_To_True_When_Prior_Method_Called_Atleast_Once;
begin
Assert.IsTrue(False, 'Not implemented');
end;
procedure TTestMethodData.AllowRedefineBehaviorDefinitions_IsTrue_RedefinedIsAllowed;
var
methodData : IMethodData;
someValue1,
someValue2 : TValue;
begin
someValue1 := TValue.From<Integer>(1);
someValue2 := TValue.From<Integer>(2);
methodData := TMethodData.Create('x', 'x', TSetupMethodDataParameters.Create(FALSE, False, TRUE));
methodData.WillReturnWhen(TArray<TValue>.Create(someValue1), someValue1, nil);
methodData.WillReturnWhen(TArray<TValue>.Create(someValue1), someValue2, nil);
// no exception is raised
Assert.IsTrue(True);
end;
procedure TTestMethodData.AllowRedefineBehaviorDefinitions_IsFalse_ExceptionIsThrown_WhenRedefining;
var
methodData : IMethodData;
someValue1,
someValue2 : TValue;
begin
someValue1 := TValue.From<Integer>(1);
someValue2 := TValue.From<Integer>(2);
methodData := TMethodData.Create('x', 'x', TSetupMethodDataParameters.Create(FALSE, FALSE, FALSE));
methodData.WillReturnWhen(TArray<TValue>.Create(someValue1), someValue1, nil);
Assert.WillRaise(procedure
begin
methodData.WillReturnWhen(TArray<TValue>.Create(someValue1), someValue2, nil);
end, EMockSetupException);
end;
procedure TTestMethodData.AllowRedefineBehaviorDefinitions_IsFalse_NoExceptionIsThrown_WhenAddingNormal;
var
methodData : IMethodData;
someValue1,
someValue2 : TValue;
begin
someValue1 := TValue.From<Integer>(1);
someValue2 := TValue.From<Integer>(2);
methodData := TMethodData.Create('x', 'x', TSetupMethodDataParameters.Create(FALSE, FALSE, FALSE));
methodData.WillReturnWhen([nil, someValue1], someValue1, nil);
methodData.WillReturnWhen([nil, someValue2], someValue2, nil);
Assert.IsTrue(True);
end;
procedure TTestMethodData.AllowRedefineBehaviorDefinitions_IsTrue_NoExceptionIsThrown_WhenMatcherAreDifferent;
var
methodData : IMethodData;
someParam,
someValue1,
someValue2 : TValue;
LObjectToTest : TObjectToTest;
LAnotherObject: TAnotherObject;
LAndAnotherObject: TAndAnotherObject;
begin
LObjectToTest := TObjectToTest.Create;
LAnotherObject := TAnotherObject.Create;
LAndAnotherObject := TAndAnotherObject.Create;
try
someValue1 := TValue.From<TAnotherObject>(LAnotherObject);
someValue2 := TValue.From<TAndAnotherObject>(LAndAnotherObject);
someParam := TValue.From<TObjectToTest>(LObjectToTest);
methodData := TMethodData.Create('x', 'x', TSetupMethodDataParameters.Create(FALSE, FALSE, FALSE));
methodData.WillReturnWhen([nil, someParam], someValue1, [TMatcher<TAnotherObject>.Create(function(value : TAnotherObject) : boolean
begin
result := true;
end)]);
Assert.WillNotRaise(procedure
begin
methodData.WillReturnWhen([nil, someParam], someValue2, [TMatcher<TAndAnotherObject>.Create(function(value : TAndAnotherObject) : boolean
begin
result := true;
end)]);
end, EMockSetupException);
finally
LAnotherObject.Free;
LAndAnotherObject.Free;
end;
end;
procedure TTestMethodData.AllowRedefineBehaviorDefinitions_IsTrue_OldBehaviorIsDeleted;
var
methodData : IMethodData;
someValue1,
someValue2 : TValue;
outValue : TValue;
begin
someValue1 := TValue.From<Integer>(1);
someValue2 := TValue.From<Integer>(2);
methodData := TMethodData.Create('x', 'x', TSetupMethodDataParameters.Create(TRUE, TRUE, TRUE));
methodData.WillReturnWhen(TArray<TValue>.Create(someValue1), someValue1, nil);
methodData.WillReturnWhen(TArray<TValue>.Create(someValue1), someValue2, nil);
methodData.RecordHit(TArray<TValue>.Create(someValue1), TrttiContext.Create.GetType(TypeInfo(integer)), nil, outValue);
Assert.AreEqual(someValue2.AsInteger, outValue.AsInteger );
end;
procedure TTestMethodData.BehaviourMustBeDefined_IsFalse_AndBehaviourIsNotDefined_RaisesNoException;
var
methodData : IMethodData;
someValue : TValue;
begin
methodData := TMethodData.Create('x', 'x', TSetupMethodDataParameters.Create(FALSE, FALSE, FALSE));
methodData.RecordHit(TArray<TValue>.Create(), nil, nil, someValue);
// no exception should be raised
Assert.IsTrue(True);
end;
procedure TTestMethodData.BehaviourMustBeDefined_IsTrue_AndBehaviourIsNotDefined_RaisesException;
var
methodData : IMethodData;
someValue : TValue;
begin
methodData := TMethodData.Create('x', 'x', TSetupMethodDataParameters.Create(FALSE, TRUE, FALSE));
Assert.WillRaise(procedure
begin
methodData.RecordHit(TArray<TValue>.Create(), TRttiContext.Create.GetType(TypeInfo(Integer)), nil, someValue);
end, EMockException);
end;
initialization
TDUnitX.RegisterTestFixture(TTestMethodData);
end.
|
unit GraphicsCheckButton;
interface
uses
System.SysUtils, System.Classes, Vcl.Controls, Vcl.Buttons,
Winapi.GDIPAPI, Winapi.GDIPOBJ;
type
TGraphicsCheckButton = class(TSpeedButton)
private
{ Private declarations }
FDownImage: TGPBitmap;
FUpImage : TGPBitmap;
protected
{ Protected declarations }
procedure Paint; override;
public
{ Public declarations }
procedure SetImages(DownImage, UpImage: TGPBitmap);
published
{ Published declarations }
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Samples', [TGraphicsCheckButton]);
end;
procedure TGraphicsCheckButton.Paint();
var
x, y : Integer;
image: TGPBitmap;
Graphics: TGPGraphics;
begin
inherited;
if (Self.Down) then
begin
image := FDownImage;
end else begin
image := FUpImage;
end;
if image <> Nil then
begin
x := (Width - image.GetWidth()) div 2;
y := (Height - image.GetHeight()) div 2;
Graphics := TGPGraphics.Create(Self.Canvas.Handle);
Graphics.DrawImage(image, x, y, image.GetWidth(), image.GetHeight());
Graphics.Free();
end;
end;
procedure TGraphicsCheckButton.SetImages(DownImage, UpImage: TGPBitmap);
begin
FDownImage := DownImage;
FUpImage := UpImage;
end;
end.
|
unit COMTestUnit;
interface
uses DB, TestFramework;
type
// Класс тестирует поведение класса TELOLAPSalers.
TCOMTest = class(TTestCase)
protected
// подготавливаем данные для тестирования
procedure SetUp; override;
// возвращаем данные после тестирования}
procedure TearDown; override;
published
// запускаем КОМ объект
procedure CreateCOMApplication;
procedure InsertUpdate_Movement_OrderExternal_1C;
end;
implementation
{ TCOMTest }
uses ComObj, SysUtils;
procedure TCOMTest.CreateCOMApplication;
var OleObject: OleVariant;
begin
OleObject := CreateOleObject('ProjectCOM.dsdCOMApplication');
end;
procedure TCOMTest.InsertUpdate_Movement_OrderExternal_1C;
var OleObject: OleVariant;
ioId, ioMovementItemId: Integer;
begin
OleObject := CreateOleObject('ProjectCOM.dsdCOMApplication');
OleObject.InsertUpdate_Movement_OrderExternal_1C(ioId, ioMovementItemId,
'1D1', '2D2',
Date,
1001, 1002,
506.56,
605.65);
Check((ioId <> 0) and (ioMovementItemId <>0), 'АШИБКА!!!');
end;
procedure TCOMTest.SetUp;
begin
inherited;
end;
procedure TCOMTest.TearDown;
begin
inherited;
end;
initialization
TestFramework.RegisterTest('Компоненты', TCOMTest.Suite);
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.