Here is the code:
Uses crt;
Type
mang = array[1..255] of Integer;
Var
N, X, Y : Integer;
A : mang;
Procedure Nhap(Var A : mang; Var N : Integer);
Var
i : Integer;
Begin
Clrscr;
Write('So luong phan tu: ');
Readln(N);
For i := 1 to N do begin
Write('Nhap phan tu thu ', i, ': ');
Readln(A[I]);
end;
End;
Procedure Xuat(Var A: mang; Var N: Integer);
Var
i : Integer;
Begin
For i := 1 to N do write(A[i], ' ');
Writeln;
End;
Function KTMangTang(Var A : mang; Var N : Integer) : Boolean;
Var
i, j : Integer;
Var
kt : Boolean;
Begin
kt := True;
i := 0;
For i := 1 to N-1 do
for j := i+1 to N do
if A[i] > A[j] then
kt := False;
KTMangTang := kt;
End;
Function KTMangDX(Var A : mang; Var N : Integer) : Boolean;
Var
i, j : Integer;
Var
kt : Boolean;
Begin
kt := True;
i := 0;
For i := 1 to N do
for j := N-i downto 1 do
if A[i] <> A[j] then
kt := False;
KTMangDX := kt;
End;
begin
Nhap(A, N);
Xuat(A, N);
if KTMangTang then
Writeln('Mang tang')
else
Writeln('Mang khong tang');
if KTMangDX then
Writeln('Mang doi xung')
else
Writeln('Mang khong doi xung');
readln;
End.
The boolean value KTMangTang and KTMangDX were supposed to work but they returned these errors:
Free Pascal Compiler version 3.2.2 [2021/05/15] for i386
Copyright (c) 1993-2021 by Florian Klaempfl and others
Target OS: Win32 for i386
Compiling 34.pas
34.pas(53,4) Error: Wrong number of parameters specified for call to "KTMangTang"
34.pas(28,10) Error: Found declaration: KTMangTang(var mang;var SmallInt):Boolean;
34.pas(55,4) Error: Wrong number of parameters specified for call to "KTMangDX"
34.pas(39,10) Error: Found declaration: KTMangDX(var mang;var SmallInt):Boolean;
34.pas(58,4) Fatal: There were 4 errors compiling module, stopping
Fatal: Compilation aborted
Error: C:\FPC\3.2.2\bin\i386-Win32\ppc386.exe returned an error exitcode
I tried not to use the "kt" boolean variable but it returned other errors.
P/S: I use Visual Studio Code with Free Pascal Compiler (32 bit). If anyone knows how to install the 64 bit Free Pascal IDE, please help me.
You have declared KTMangTang and KTMangDX as functions taking two parameters and returning a BOOLEAN. You have called them with no parameters. This doesn’t work. The errors in the compilation specifically tell you this.
Related
I have the following code, where I can draw several rectangles and make a hole to each.
How can I send the RectList object over a socket (TServerSocket) and recover (receive in a TClientSocket) this object directly to a variable of same type (var RectList: TList<TRect>)?
type
TForm1 = class(TForm)
ComboBox1: TComboBox;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure FormMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure FormPaint(Sender: TObject);
private
{ Private declarations }
Drawing: Boolean;
RectList: TList<TRect>;
Rectangle: TRect;
FormRegion, HoleRegion: HRGN;
function ClientToWindow(const P: TPoint): TPoint;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
function TForm1.ClientToWindow(const P: TPoint): TPoint;
begin
Result := ClientToScreen(P);
Dec(Result.X, Left);
Dec(Result.Y, Top);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
RectList := TList<TRect>.Create;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
RectList.Free;
end;
procedure TForm1.FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
Rectangle.Left := X;
Rectangle.Top := Y;
Drawing := True;
end;
procedure TForm1.FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
begin
if Drawing then
begin
Rectangle.Right := X;
Rectangle.Bottom := Y;
Invalidate;
end;
end;
procedure TForm1.FormMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
I: Integer;
begin
Drawing := false;
Rectangle.Right := X;
Rectangle.Bottom := Y;
Invalidate;
if RectList.Count < StrToInt(ComboBox1.Text) then
begin
Rectangle.NormalizeRect;
if not Rectangle.IsEmpty then
RectList.Add(Rectangle)
else
SetWindowRgn(Handle, 0, True);
end
else
begin
FormRegion := CreateRectRgn(0, 0, Width, Height);
for I := 0 to Pred(RectList.Count) do
begin
HoleRegion := CreateRectRgn(ClientToWindow(RectList.Items[I].TopLeft).X, ClientToWindow(RectList.Items[I].TopLeft).Y, ClientToWindow(RectList.Items[I].BottomRight).X, ClientToWindow(RectList.Items[I].BottomRight).Y);
CombineRgn(FormRegion, FormRegion, HoleRegion, RGN_DIFF);
end;
SetWindowRgn(Handle, FormRegion, True);
RectList.Clear;
end;
end;
procedure TForm1.FormPaint(Sender: TObject);
var
R: TRect;
begin
Canvas.Brush.Style := bsClear;
Canvas.Pen.Style := psSolid;
Canvas.Pen.Color := clRed;
Canvas.Rectangle(Rectangle);
for R in RectList do
Canvas.Rectangle(R);
end;
end.
I made some code to show you how to do it.
In your code, I added a TClientSocketon the form and assigned a few events. Also added a TButton to send the RectList to the other side (server side) thru the TClientSocket.
I designed a new simple server application having a TServerSocket set to listen for client connection and accepting commands from the client. I implemented two commands: rectangle and clear. Obviously clear command is implemented to clear the display on the rectangle list. The rectangle command is used to sent a rectangle (Left, top, right and bottom as coma delimited integers).
Since client and server must understand each other, I designed a very simple communication protocol. Data is exchanged between client and server using ASCII lines. A line is any character collection terminated by a CRLF pair. TCP port 2500 (Almost any other would do) is used.
For example, the command
rectangle 10,20,30,40
will sent a rectangle from client to server (The line above is terminated by CRLF).
If the server receive a valid command, it act on it and then send
OK
The line above is terminated by CRLF. In case of an error, an error message is sent back to the client.
When a client establish a connection, the first thing the server does is to send a welcome banner. That is a line terminated by CRLF.
The client wait to receive the banner before sending any command. Then it send the clear command, wait for OK, then send a rectangle command with first item in RectList and wait for OK, then loop sending all rectangle commands and waiting for OK acknowledge until all RectList has been sent. The the client close the connection.
I'm not completely correct when I say wait for. Actually the socket is event driven. That means everything is done thry events. For example, when a line comes in - sent by the other side - the socket triggers an OnRead event. In the corresponding event handler, you receive the line that is already received.
I used this line oriented protocol because it is really simple, easy to debug and cross platform. Actually, if looks much like the SMTP protocol which is used to send an email! Sending binary data is surely faster but has a lot of difficulties. Binary data format is compiler and platform specific. This result in difficulties. Binary data is diffcult to read for a human and so it is difficult to debug.
Below you'll find your enhanced source code and DFM (This is the client), then the server source code and DFM.
Client source code:
unit SktSocketClientDemoMain;
interface
uses
Winapi.Windows, Winapi.Messages,
System.SysUtils, System.Variants, System.Classes,
System.Generics.Collections,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
System.Win.ScktComp;
type
TSktSocketClientMainForm = class(TForm)
ComboBox1 : TComboBox;
SocketSendButton : TButton;
ClientSocket1 : TClientSocket;
Memo1 : TMemo;
procedure ClientSocket1Connect(
Sender : TObject;
Socket : TCustomWinSocket);
procedure ClientSocket1Connecting(
Sender : TObject;
Socket : TCustomWinSocket);
procedure ClientSocket1Read(
Sender : TObject;
Socket : TCustomWinSocket);
procedure FormCreate(Sender : TObject);
procedure FormDestroy(Sender : TObject);
procedure FormMouseDown(
Sender : TObject;
Button : TMouseButton;
Shift : TShiftState;
X, Y : Integer);
procedure FormMouseMove(
Sender : TObject;
Shift : TShiftState;
X, Y : Integer);
procedure FormMouseUp(
Sender : TObject;
Button : TMouseButton;
Shift : TShiftState;
X, Y : Integer);
procedure FormPaint(Sender : TObject);
procedure SocketSendButtonClick(Sender : TObject);
private
Drawing : Boolean;
RectList : TList<TRect>;
Rectangle : TRect;
FormRegion, HoleRegion : HRGN;
FBanner : string;
FSendIndex : Integer;
function ClientToWindow(const P : TPoint) : TPoint;
end;
var
SktSocketClientMainForm : TSktSocketClientMainForm;
implementation
{$R *.dfm}
function TSktSocketClientMainForm.ClientToWindow(const P : TPoint) : TPoint;
begin
Result := ClientToScreen(P);
Dec(Result.X, Left);
Dec(Result.Y, Top);
end;
procedure TSktSocketClientMainForm.FormCreate(Sender : TObject);
begin
RectList := TList<TRect>.Create;
end;
procedure TSktSocketClientMainForm.FormDestroy(Sender : TObject);
begin
RectList.Free;
end;
procedure TSktSocketClientMainForm.FormMouseDown(
Sender : TObject;
Button : TMouseButton;
Shift : TShiftState;
X, Y : Integer);
begin
Rectangle.Left := X;
Rectangle.Top := Y;
Drawing := True;
end;
procedure TSktSocketClientMainForm.FormMouseMove(
Sender : TObject;
Shift : TShiftState;
X, Y : Integer);
begin
if Drawing then begin
Rectangle.Right := X;
Rectangle.Bottom := Y;
Invalidate;
end;
end;
procedure TSktSocketClientMainForm.FormMouseUp(
Sender : TObject;
Button : TMouseButton;
Shift : TShiftState;
X, Y : Integer);
var
I : Integer;
begin
Drawing := false;
Rectangle.Right := X;
Rectangle.Bottom := Y;
Invalidate;
if RectList.Count < StrToInt(ComboBox1.Text) then begin
Rectangle.NormalizeRect;
if not Rectangle.IsEmpty then
RectList.Add(Rectangle)
else
SetWindowRgn(Handle, 0, True);
end
else begin
FormRegion := CreateRectRgn(0, 0, Width, Height);
for I := 0 to Pred(RectList.Count) do
begin
HoleRegion :=
CreateRectRgn(ClientToWindow(RectList.Items[I].TopLeft).X,
ClientToWindow(RectList.Items[I].TopLeft).Y,
ClientToWindow(RectList.Items[I].BottomRight).X,
ClientToWindow(RectList.Items[I].BottomRight).Y);
CombineRgn(FormRegion, FormRegion, HoleRegion, RGN_DIFF);
end;
SetWindowRgn(Handle, FormRegion, True);
RectList.Clear;
end;
end;
procedure TSktSocketClientMainForm.FormPaint(Sender : TObject);
var
R : TRect;
begin
Canvas.Brush.Style := bsClear;
Canvas.Pen.Style := psSolid;
Canvas.Pen.Color := clRed;
Canvas.Rectangle(Rectangle);
for R in RectList do
Canvas.Rectangle(R);
end;
procedure TSktSocketClientMainForm.SocketSendButtonClick(Sender : TObject);
begin
FBanner := '';
FSendIndex := 0;
ClientSocket1.Port := 2500; // Must be the same as server side
ClientSocket1.Address := '127.0.0.1';
ClientSocket1.Active := True;
end;
procedure TSktSocketClientMainForm.ClientSocket1Connect(
Sender : TObject;
Socket :
TCustomWinSocket);
begin
Memo1.Lines.Add('Connected');
end;
procedure TSktSocketClientMainForm.ClientSocket1Connecting(
Sender : TObject;
Socket : TCustomWinSocket);
begin
Memo1.Lines.Add('Connecting...');
end;
procedure TSktSocketClientMainForm.ClientSocket1Read(
Sender : TObject;
Socket : TCustomWinSocket);
var
Line : string;
CmdLine : string;
R : TRect;
begin
Line := Trim(string(Socket.ReceiveText));
Memo1.Lines.Add('Rcvd: "' + Line + '"');
if FBanner = '' then begin
FBanner := Line;
Socket.SendText('Clear' + #13#10);
Exit;
end;
if Line <> 'OK' then begin
Memo1.Lines.Add('Expected "OK", received "' + Line + '"');
Socket.Close;
Exit;
end;
if FSendIndex >= RectList.Count then begin
// We have sent everything in RectList
Memo1.Lines.Add('Send completed OK');
Socket.Close;
Exit;
end;
// Send next item in RectList
R := RectList[FSendIndex];
CmdLine := Format('Rectangle %d,%d,%d,%d' + #13#10,
[R.Left, R.Top, R.Right, R.Bottom]);
Inc(FSendIndex);
Socket.SendText(AnsiString(CmdLine));
end;
end.
Client DFM:
object SktSocketClientMainForm: TSktSocketClientMainForm
Left = 0
Top = 0
Caption = 'SktSocketClientMainForm'
ClientHeight = 299
ClientWidth = 635
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
OnCreate = FormCreate
OnDestroy = FormDestroy
OnMouseDown = FormMouseDown
OnMouseMove = FormMouseMove
OnMouseUp = FormMouseUp
OnPaint = FormPaint
DesignSize = (
635
299)
PixelsPerInch = 96
TextHeight = 13
object ComboBox1: TComboBox
Left = 24
Top = 12
Width = 145
Height = 21
Style = csDropDownList
ItemIndex = 4
TabOrder = 0
Text = '5'
Items.Strings = (
'1'
'2'
'3'
'4'
'5'
'6'
'7'
'8'
'9')
end
object SocketSendButton: TButton
Left = 188
Top = 8
Width = 75
Height = 25
Caption = 'Send'
TabOrder = 1
OnClick = SocketSendButtonClick
end
object Memo1: TMemo
Left = 8
Top = 192
Width = 621
Height = 101
Anchors = [akLeft, akTop, akRight, akBottom]
Lines.Strings = (
'Memo1')
TabOrder = 2
end
object ClientSocket1: TClientSocket
Active = False
ClientType = ctNonBlocking
Port = 0
OnConnecting = ClientSocket1Connecting
OnConnect = ClientSocket1Connect
OnRead = ClientSocket1Read
Left = 44
Top = 148
end
end
Server source code:
unit SktSocketServerDemoMain;
interface
uses
Winapi.Windows, Winapi.Messages,
System.SysUtils, System.Variants, System.Classes,
System.Generics.Collections,
Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.Win.ScktComp,
Vcl.ExtCtrls;
type
TCmdProc = procedure (Socket : TCustomWinSocket;
const Params : String) of object;
TCmdItem = record
Cmd : String;
Proc : TCmdProc;
constructor Create(const ACmd : String; AProc : TCmdProc);
end;
TServerMainForm = class(TForm)
ServerSocket1 : TServerSocket;
Memo1 : TMemo;
ServerStartButton : TButton;
PaintBox1 : TPaintBox;
ServerStopButton : TButton;
procedure PaintBox1Paint(Sender : TObject);
procedure ServerSocket1ClientConnect(
Sender : TObject;
Socket : TCustomWinSocket);
procedure ServerSocket1ClientDisconnect(
Sender : TObject;
Socket :
TCustomWinSocket);
procedure ServerSocket1ClientRead(
Sender : TObject;
Socket : TCustomWinSocket);
procedure ServerSocket1Listen(
Sender : TObject;
Socket : TCustomWinSocket);
procedure ServerStartButtonClick(Sender : TObject);
procedure ServerStopButtonClick(Sender : TObject);
private
RectList : TList<TRect>;
CmdList : TList<TCmdItem>;
procedure ProcessCmd(
Socket : TCustomWinSocket;
const CmdLine : string);
procedure CmdNoop(
Socket : TCustomWinSocket;
const Params : string);
procedure CmdClear(
Socket : TCustomWinSocket;
const Params : string);
procedure CmdRectangle(
Socket : TCustomWinSocket;
const Params : string);
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
end;
var
ServerMainForm: TServerMainForm;
implementation
{$R *.dfm}
function SkipOverWhiteSpaces(const CmdLine : String; Index : Integer) : Integer;
var
I : Integer;
begin
I := Index;
while (I <= Length(CmdLine)) and
CharInSet(CmdLine[I], [' ', #13, #10, #9]) do
Inc(I);
Result := I;
end;
function SkipToNextWhiteSpace(const CmdLine : String; Index : Integer) : Integer;
var
I : Integer;
begin
I := Index;
while (I <= Length(CmdLine)) and
(not CharInSet(CmdLine[I], [' ', #13, #10, #9])) do
Inc(I);
Result := I;
end;
function SkipToNextDelimiter(
const CmdLine : String;
Index : Integer;
Delimiters : array of const) : Integer;
var
I : Integer;
nArg : Integer;
V : TVarRec;
begin
I := Index;
while I <= Length(CmdLine) do begin
nArg := 0;
while nArg <= High(Delimiters) do begin
V := Delimiters[nArg];
case (V.VType and varTypeMask) of
vtWideChar:
begin
if CmdLine[I] = V.VWideChar then begin
Result := I;
Exit;
end;
end;
end;
Inc(nArg);
end;
Inc(I);
end;
Result := I;
end;
function GetInteger(
const CmdLine : String;
Index : Integer;
out Value : Integer) : Integer;
var
I : Integer;
begin
Value := 0;
I := SkipOverWhiteSpaces(CmdLine, Index);
while (I <= Length(CmdLine)) and
CharInSet(CmdLine[I], ['0'..'9']) do begin
Value := Value * 10 + Ord(CmdLine[I]) - Ord('0');
Inc(I);
end;
Result := I;
end;
procedure TServerMainForm.CmdClear(Socket: TCustomWinSocket; const Params: String);
begin
RectList.Clear;
PaintBox1.Invalidate;
Socket.SendText('OK' + #13#10);
end;
procedure TServerMainForm.CmdNoop(Socket: TCustomWinSocket; const Params: String);
begin
Socket.SendText('OK' + #13#10);
end;
procedure TServerMainForm.CmdRectangle(Socket: TCustomWinSocket; const Params: String);
var
Param : array [0..3] of Integer;
I, J, K : Integer;
begin
// Clear all parameters
for K := Low(Param) to High(Param) do
Param[K] := 0;
// Parse all parameters
J := 1;
K := Low(Param);
while K <= High(Param) do begin
I := GetInteger(Params, J, Param[K]);
J := SkipOverWhiteSpaces(Params, I);
if J > Length(Params) then
break;
if K = High(Param) then // Check if we got all
break;
if Params[J] <> ',' then // Check for coma delimiter
break;
Inc(J); // Skip over coma
Inc(K);
end;
if K <> High(Param) then begin
Socket.SendText('Rectangle requires 4 parameters.'#13#10);
Exit;
end;
RectList.Add(TRect.Create(Param[0], Param[1], Param[2], Param[3]));
PaintBox1.Invalidate;
Socket.SendText('OK'#13#10);
end;
constructor TServerMainForm.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
RectList := TList<TRect>.Create;
RectList.Add(TRect.Create(10, 10, 50, 50));
RectList.Add(TRect.Create(20, 30, 80, 100));
CmdList := TList<TCmdItem>.Create;
CmdList.Add(TCmdItem.Create('', CmdNoop));
CmdList.Add(TCmdItem.Create('Clear', CmdClear));
CmdList.Add(TCmdItem.Create('Rectangle', CmdRectangle));
end;
destructor TServerMainForm.Destroy;
begin
FreeAndNil(CmdList);
FreeAndNil(RectList);
inherited Destroy;
end;
procedure TServerMainForm.PaintBox1Paint(Sender: TObject);
var
R: TRect;
ACanvas : TCanvas;
begin
ACanvas := (Sender as TPaintBox).Canvas;
ACanvas.Brush.Style := bsClear;
ACanvas.Pen.Style := psSolid;
ACanvas.Pen.Color := clRed;
for R in RectList do
ACanvas.Rectangle(R);
end;
procedure TServerMainForm.ServerSocket1ClientConnect(
Sender: TObject;
Socket: TCustomWinSocket);
begin
Memo1.Lines.Add('Client connected');
Socket.SendText('Welcome to myServer' + #13#10);
end;
procedure TServerMainForm.ServerSocket1ClientRead(Sender: TObject; Socket:
TCustomWinSocket);
var
CmdLine : String;
begin
CmdLine := String(Socket.ReceiveText);
Memo1.Lines.Add('Rcvd: "' + CmdLine + '"');
ProcessCmd(Socket, CmdLine);
end;
procedure TServerMainForm.ProcessCmd(
Socket : TCustomWinSocket;
const CmdLine : String);
var
Cmd : String;
Params : String;
I, J : Integer;
begin
I := SkipOverWhiteSpaces(CmdLine, 1);
J := SkipToNextWhiteSpace(CmdLine, I);
// Split command and parameters
Cmd := UpperCase(Copy(CmdLine, I, J - I));
Params := Copy(CmdLine, J, MAXINT);
Memo1.Lines.Add(Format('Cmd="%s" Params="%s"', [Cmd, Params]));
for I := 0 to CmdList.Count - 1 do begin
if CmdList[I].Cmd = Cmd then begin
CmdList[I].Proc(Socket, Params);
Exit;
end;
end;
Socket.SendText('Unknown command' + #13#10);
end;
procedure TServerMainForm.ServerSocket1ClientDisconnect(Sender: TObject; Socket:
TCustomWinSocket);
begin
Memo1.Lines.Add('Client disconnected');
end;
procedure TServerMainForm.ServerSocket1Listen(Sender: TObject; Socket: TCustomWinSocket);
begin
Memo1.Lines.Add('Waiting for client connection');
end;
procedure TServerMainForm.ServerStartButtonClick(Sender: TObject);
begin
ServerSocket1.Port := 2500; // Almost any (free) port is OK
ServerSocket1.Open; // Start listening for clients
end;
procedure TServerMainForm.ServerStopButtonClick(Sender: TObject);
begin
ServerSocket1.Close;
Memo1.Lines.Add('Server stopped');
end;
{ TCmdItem }
constructor TCmdItem.Create(const ACmd: String; AProc: TCmdProc);
begin
Cmd := UpperCase(ACmd);
Proc := AProc;
end;
end.
Server DFM:
object ServerMainForm: TServerMainForm
Left = 0
Top = 0
Caption = 'ServerMainForm'
ClientHeight = 498
ClientWidth = 635
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
DesignSize = (
635
498)
PixelsPerInch = 96
TextHeight = 13
object PaintBox1: TPaintBox
Left = 8
Top = 48
Width = 617
Height = 273
Anchors = [akLeft, akTop, akRight, akBottom]
OnPaint = PaintBox1Paint
end
object Memo1: TMemo
Left = 8
Top = 329
Width = 617
Height = 161
Anchors = [akLeft, akTop, akRight, akBottom]
Lines.Strings = (
'Memo1')
TabOrder = 0
end
object ServerStartButton: TButton
Left = 12
Top = 8
Width = 75
Height = 25
Caption = 'Server Start'
TabOrder = 1
OnClick = ServerStartButtonClick
end
object ServerStopButton: TButton
Left = 93
Top = 8
Width = 75
Height = 25
Caption = 'Server Stop'
TabOrder = 2
OnClick = ServerStopButtonClick
end
object ServerSocket1: TServerSocket
Active = False
Port = 0
ServerType = stNonBlocking
OnListen = ServerSocket1Listen
OnClientConnect = ServerSocket1ClientConnect
OnClientDisconnect = ServerSocket1ClientDisconnect
OnClientRead = ServerSocket1ClientRead
Left = 64
Top = 196
end
end
I have created a REST server in Delphi using WebBroker. My intention is to use it as a label printer. A client prepares and sends a JSON request detailing the printer name, Fast Report & variables. The server reads the JSON, creates a tFrxReport object loads the requisite report and populates the variables.
This all works admirably, except it will not print to a physical printer. If I select OneNote as my destination, the label is saved to the desktop. If I select a network attached printer, no label emerges.
I have tried PrintOptions.ShowDialog:=True The print dialog shows, indicating the correct printer, but it does not print.
If anyone has any experience, could you point me in the right direction please?
function processJson(itm : sat; jtr : tJsonTextReader): sat;
var
idx : integer;
//itm : sat; // simple array type [idx, 'val1', 'val2']
begin
setlength(itm,0);
idx:=0;
while jtr.Read do
begin
if jtr.TokenType = tJsonToken.PropertyName then
begin
setlength(itm, length(itm)+1);
itm[idx].st_idx := idx;
itm[idx].st_code := jtr.Value.ToString; // property name
jtr.Read;
itm[idx].st_desc := jtr.Value.AsString; // property value
inc(idx);
end;
end;
processJson := itm;
end;
function getPrinterInfo(pnam: string):printinfo_type;
var
ptr : printinfo_type;
idx : integer;
begin
ptr.idx := -1; //default printer
ptr.name := trim(pnam);
for idx := 0 to Printer.Printers.Count - 1 do
if AnsiContainsText(Printer.Printers[idx], ptr.name) then
ptr.idx := idx;
result := ptr;
end;
procedure Ttfdq.tfdqactLabelAction(Sender: TObject; Request: TWebRequest;
Response: TWebResponse; var Handled: Boolean);
var
post : simpleArray_type;
pdx, idx, iitm : integer;
jtr : tJsonTextReader;
sr : tStringReader;
pish : string;
fr : tFrxReport;
thePtr : printinfo_type;
itm : sat;
tstprt : boolean;
begin
d.myHost := 'http://' + Request.host + ':' + intToStr(Request.ServerPort);
d.hostIP := Request.host;
d.Request := Request;
d.Response := Response;
d.remAddr := Request.RemoteAddr;
post := explode(Request.Content);
tstprt := false;
pdx := isset(post, 'json');
pish:='';
if (pdx >=0) then
begin
sr := tStringReader.Create(post[pdx].st_desc);
jtr := tJsonTextReader.Create(sr);
while jtr.read do
begin
if jtr.TokenType = tJsonToken.StartObject then
itm := processJson(itm, jtr);
end;
if fileexists(itm[2].st_desc) then
begin
thePtr := getPrinterInfo(itm[1].st_desc);
fr := tFrxReport.Create(nil);
fr.LoadFromFile(itm[2].st_desc);
// pre load any vars so report does not fail
for idx := 0 to fr.Variables.Count-1 do
fr.Variables.Items[iitm].Value := frText('');
for idx := 4 to High(itm) do
begin
pish := pish + 'index of '+itm[idx].st_code+' = '+ intToStr (fr.Variables.IndexOf(itm[idx].st_code))+'<br>';
iitm := fr.Variables.IndexOf(itm[idx].st_code);
if iitm > -1 then
fr.Variables.Items[iitm].Value := frText(itm[idx].st_desc);
end;
if fr.PrepareReport then
begin
//fr.ShowPreparedReport;
fr.PrintOptions.Printer := thePtr.name;
fr.PrintOptions.PrnOutFileName := 'Trace Label';
fr.PrintOptions.ShowDialog := tstprt;
fr.ShowProgress := tstprt;
fr.Print;
end;
fr.Free;
end;
Response.Content := pish ;
end
else
begin
Response.Content := '<html>' +
'<head><title>Label List</title></head>' +
'<body>This is only used by print serve clients</p>'+
'</body>' +
'</html>';
end;
end;
The problem lies here:
fr.PrintOptions.PrnOutFileName := 'Trace Label';
I erroneously thought that would add a description in the print queue. What it actually did is send the report into limbo :)
So I need to understand what this code is doing. I don't know pascal or cryptography, and am struggling to understand what is going on in here. I need to reverse engineer SHA1DigestToHex into scala and am totally lost beyond learning pascal. Can you tell me what this function is doing? Or how I can go about figuring it out?
Function SHA1DigestToHex (const Digest : T160BitDigest) : String;
Begin
Result := DigestToHex (Digest, Sizeof (Digest));
End;
Function DigestToHex (const Digest; const Size : Integer) : String;
Begin
SetLength (Result, Size * 2);
DigestToHexBuf (Digest, Size, Pointer (Result)^);
End;
Procedure DigestToHexBuf (const Digest; const Size : Integer; const Buf);
const s_HexDigitsLower : String [16] = '0123456789abcdef';
var I : Integer;
P : PChar;
Q : PByte;
Begin
P := #Buf;;
Assert (Assigned (P), 'Assigned (Buf)');
Q := #Digest;
Assert (Assigned (Q), 'Assigned (Digest)');
For I := 0 to Size - 1 do
begin
P^ := s_HexDigitsLower [Q^ shr 4 + 1];
Inc (P);
P^ := s_HexDigitsLower [Q^ and 15 + 1];
Inc (P);
Inc (Q);
end;
End;
UPDATE
type
PByte = ^Byte;
PWord = ^Word;
PLongWord = ^LongWord;
T128BitDigest = record
case integer of
0 : (Int64s : Array [0..1] of Int64);
1 : (Longs : Array [0..3] of LongWord);
2 : (Words : Array [0..7] of Word);
3 : (Bytes : Array [0..15] of Byte);
end;
P128BitDigest = ^T128BitDigest;
T160BitDigest = record
case integer of
0 : (Longs : Array [0..4] of LongWord);
1 : (Words : Array [0..9] of Word);
2 : (Bytes : Array [0..19] of Byte);
end;
P160BitDigest = ^T160BitDigest;
const
MaxHashDigestSize = Sizeof (T160BitDigest);
Procedure DigestToHexBuf (const Digest; const Size : Integer; const Buf);
Function DigestToHex (const Digest; const Size : Integer) : String;
Function Digest128Equal (const Digest1, Digest2 : T128BitDigest) : Boolean;
Function Digest160Equal (const Digest1, Digest2 : T160BitDigest) : Boolean;
It merely converts the bytes of the binary buffer passed in as Buf into a string of hexadecimal digits representing the same bytes in Digest.
So e.g. if Buf is the byte array (0x12, 0x34, 0x56), then afterwards Digest will be '123456'.
Here's a simpler Pascal (Delphi) version that does the same thing:
function SHA1DigestToHex2(const Digest : T160BitDigest) : string;
const s_HexDigitsLower : array[0..15] of char = '0123456789abcdef';
var
i, j: Integer;
Begin
SetLength(Result, sizeof(Digest) * 2);
i := 1;
j := 0;
while j < sizeof(Digest) do begin
Result[i] := s_HexDigitsLower[Digest.Bytes[j] shr 4];
Result[i+1] := s_HexDigitsLower[Digest.Bytes[j] and $F];
inc(i, 2);
inc(j);
end;
End;
I have a problem which occurs only in a very small customer range and I would like to ask if you might give me a hint where the problem might be. The program works for 98% of the customers. Alas, it is not possible that I work with the customers to debug the issue, because their knowledge of Windows and computers is very basic. It is also not possible that I send multiple versions of the product to them, since they don't even know how to install software (the admins do all the stuff).
First of all, I translate all RT_STRING resources on-the-fly, so that the language-switching in the program also affects hardcoded stuff like "Yes", "No", "Cancel" etc., which would only be possible by compiling 2 EXE files.
The code (I have tried to left away as much unnecessary stuff as possible, but since I don't know where the problem is, I provided as much details for the bug as possible):
The ony-the-fly resource translation
procedure TranslateResources;
var
i: integer;
s: string;
{$IF NOT Declared(FILE_ATTRIBUTE_NOT_CONTENT_INDEXED)}
const
FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = $2000;
{$IFEND}
begin
// I copy all resources in a dummy DLL (without code), because
// 1) The resources are the only thing we need when changing the resource module
// 2) If the EXE code/debug sections are too long, BeginUpdateResource() will ruin the performance heavily
FTempFile := IncludeTrailingPathDelimiter(GetTempDirectory) + GetRandomString(8)+'.dll';
// Transfers all resources from ParamStr(0) into the dummy DLL at FTempFile
ReGenerateResourceFile(FTempFile);
// if necessary, remove readonly flag
SetFileAttributes(PChar(FTempFile), FILE_ATTRIBUTE_OFFLINE or
FILE_ATTRIBUTE_NOT_CONTENT_INDEXED or
FILE_ATTRIBUTE_TEMPORARY );
for i := 0 to Length(RTLResStringTranslationArray)-1 do
begin
s := Translate(RTLResStringTranslationArray[i].TranslationID);
if s <> '' then
begin
// Translate the string
UpdateResString(RTLResStringTranslationArray[i].ResStrDescriptor.Identifier, s);
end;
end;
LoadNewResourceModule(FTempFile):
end;
procedure ReGenerateResourceFile(OutputFile: string);
var
hUpd: Cardinal;
rs: TResourceStream;
fs: TFileStream;
begin
// As template we use a dummy DLL which contains no code.
// We will implement all resources from ParamStr(0) into it, before we translate the strings.
rs := TResourceStream.Create(HInstance, 'DUMMYDLL', 'DLL');
fs := TFileStream.Create(OutputFile, fmCreate or fmOpenWrite);
try
fs.CopyFrom(rs, rs.Size)
finally
rs.Free;
fs.Free;
end;
// Transfer resources from our EXE into the dummy DLL file
hUpd := BeginUpdateResource(PChar(OutputFile), true);
try
EnumResourceTypes(hInstance, #_enumResTypesProc, hUpd);
finally
EndUpdateResource(hUpd, false)
end;
end;
// This is based on reinit.pas from Borland's RichEdit example; slightly modified
function LoadNewResourceModule(PatchedFile: string): LongInt;
var
NewInst: Longint;
CurModule: PLibModule;
begin
Result := 0;
// Win95: "Initialization routine failed"
// NewInst := LoadLibrary(PChar(PatchedFile));
NewInst := LoadLibraryEx(PChar(PatchedFile), 0, LOAD_LIBRARY_AS_DATAFILE);
CurModule := LibModuleList;
Result := 0;
while CurModule <> nil do
begin
if CurModule.Instance = HInstance then
begin
if CurModule.ResInstance <> CurModule.Instance then
FreeLibrary(CurModule.ResInstance);
// Win95: ERangeError
CurModule^.ResInstance := NewInst;
Result := NewInst;
Exit;
end;
CurModule := CurModule.Next;
end;
end;
// Based on http://stackoverflow.com/questions/1498658/modifying-a-string-in-resource-of-an-exe
// Modified
procedure UpdateResString(const AStringIdent: Integer; const ANewString: WideString);
var
ResData, TempData: TWordArray;
iSection, iIndexInSection: Integer;
i, iLen, iSkip, iPos: Integer;
begin
// Calculate the resource string area and the string index in that area
iSection := AStringIdent div 16 + 1;
iIndexInSection := AStringIdent mod 16;
ResData := ReadSectionCached(iSection);
// Calculate the position of the string
iLen := Length(ANewString);
iPos := 0;
for i := 0 to iIndexInSection do
begin
if iPos > High(ResData) then
begin
SetLength(ResData, iPos + 1);
ResData[iPos] := 0;
end;
if i <> iIndexInSection then
begin
iSkip := ResData[iPos] + 1;
Inc(iPos, iSkip);
end;
end;
// Put data behind strings into TempData
iSkip := 1{size} + ResData[iPos];
SetLength(TempData, Length(ResData) - (iPos + iSkip));
if Length(TempData) > 0 then
begin
CopyMemory(#TempData[0], #ResData[iPos + iSkip], Length(TempData)*SizeOf(TempData[0]));
end;
SetLength(ResData, iPos + (iLen + 1{size}) + Length(TempData));
// Overwrite string
ResData[iPos] := iLen;
Inc(iPos);
if iLen > 0 then
begin
CopyMemory(#ResData[iPos], #ANewString[1], iLen*SizeOf(ANewString[1]));
Inc(iPos, iLen);
end;
// Append TempData after our new string
if Length(TempData) > 0 then
begin
CopyMemory(#ResData[iPos], #TempData[0], Length(TempData)*SizeOf(TempData[0]));
end;
CacheSet(iSection, ResData);
end;
type
TGlobalData = record
GlobalPtr: Pointer;
Length: integer;
end;
function LoadResourcePtr(hModule: HMODULE; restype, resname: PChar; wIDLanguage: WORD): TGlobalData;
var
hFind, hRes: THandle;
begin
result.GlobalPtr := nil;
result.Length := -1;
hFind := Windows.FindResourceEx(hModule, restype, resname, wIDLanguage);
if hFind = 0 then RaiseLastOSError;
hres := Windows.LoadResource(hModule, hFind);
if hres = 0 then RaiseLastOSError;
result.GlobalPtr := Windows.LockResource(hres);
result.Length := Windows.SizeofResource(hModule, hFind);
end;
function _enumResLangsProc(hmodule: HMODULE; restype, resname: PChar; wIDLanguage: WORD;
lParam: LongInt): BOOL; stdcall;
var
rs: TGlobalData;
begin
rs := LoadResourcePtr(hmodule, restype, resname, wIDLanguage);
UpdateResource(lParam, restype, resname, wIDLanguage, rs.GlobalPtr, rs.Length);
result := true;
end;
function _enumResNamesProc(hmodule: HMODULE; restype, resname: PChar;
lParam: LongInt): BOOL; stdcall;
begin
EnumResourceLanguages(hmodule, restype, resname, #_enumResLangsProc, lParam);
result := true;
end;
function _enumResTypesProc(hmodule: HMODULE; restype: PChar;
lParam: LongInt): BOOL; stdcall;
begin
EnumResourceNames(hmodule, restype, #_enumResNamesProc, lParam);
result := true;
end;
{$R '..\dummydll\dummydll.RES'}
Then I use a wait form:
unit Wait;
interface
uses
...
type
TWaitForm = class(TForm)
...
end;
var
WaitForm: TWaitForm;
implementation
{$R *.dfm}
...
end;
The wait form will be called by dynamically showing the form:
procedure ShowWaitForm;
begin
...
{ I use my own _CreateForm function because it solves many workarounds for
juicy stuff like half-modal windows (which can be hidden without user action),
miscellaneous deadlocks etc. and to allow the form to be shown in a shared PAS file
without the requirement to add it to every DPR file where the WaitForm API is used. }
WaitForm := _CreateForm(TWaitForm, {Application.MainForm}AParent) as TWaitForm;
WaitForm.Show;
...
end;
function _CreateForm(InstanceClass: TCustomFormClass; AParent: TCustomForm): TCustomForm;
var
LOwner: TComponent;
begin
if Assigned(AParent) then
begin
LOwner := AParent;
end
else if Assigned(Application) then
begin
LOwner := Application;
end
else
begin
LOwner := nil;
end;
result := InstanceClass.Create(LOwner);
end;
The error message at 2% of the customers:
Resource TWaitForm was not found
However, other forms are working.
There are 2 theories I can think of:
1) Did the resource translation corrupt the DLL file / part of the RCData section? (Maybe a bug in the WinAPI's UpdateResource ?)
2) Is there a problem with the dynamic showing of the wait form (since other "static" forms are shown?)
I was just wondering why this certain problem happens to me. If you can help me, I will appreciate it.
Program factorial;
uses crt;
var
f, i: Integer;
begin
f:=1;
for i:=1 to 5 do
f:= f * i;
write(f);
readkey;
end.
Okay, That works fine and the result is 120. And it's true.
Now, here's the problem. If I asked the user to enter the value of the number, it won't work.
Program factorial;
uses crt;
var
i,r: Integer;
begin
write('Enter the number');
read(r);
for i:=1 to r do
r:= r * i;
write(r);
readkey;
end.
If I wrote 5, the output will be 600.
You are using the value r as the stopping condition of the loop and modifying the value in the loop.
Program factorial;
uses crt;
var
i,r, f: Integer;
begin
write('Enter the number');
read(r);
f := 1;
for i:=1 to r do
f:= f * i;
write(f);
readkey;
end.
You reuse the r variable. If you input 5 for r your program will in effect one to many times. You should start with 1 as the first f.
Program factorial;
uses crt;
var
i,r, f: Integer;
begin
write('Enter the number');
read(r);
f:=1
for i:=1 to r do
f:= f * i;
write(r);
readkey;
end.
try:
Program factorial;
uses crt;
var
i,r,x: Integer;
begin
write('Enter the number');
read(x);
r:=1
for i:=1 to x do
r:= r * i;
write(r);
readkey;
end.