Pascal Attempt to invoke interface method - pascal

I'm using android to run this pascal program in Pascal N-IDE app and then these error show up:
Attempt to invoke interface method
'com.duy.pascal.interperter.declaration.Name
com.duy.pascal.interperter.declaration.lang.types.Type.getName()' on a null object reference
then I tried to run this program in the Pascal online compiler via browser and it's work well idk what's the problem.
here's the code:
program testing;
uses crt;
type
ngantri = ^node;
node = record
isi : string[10];
next : ngantri;
end;
var
dpn, blk : ngantri;
pointer : string;
x : string;
cr : string;
pil : char;
// procedure baru digunakan untuk inisialisasi awal list
procedure baru(x : string; var tunjuk : ngantri) ;
begin
new(tunjuk);
tunjuk^.isi := x;
tunjuk^.next := nil;
end;
// function isempty digunakan untu mengecek apakah suatu list kosong atau tidak
function isempty(depan, belakang : ngantri) : boolean;
begin
isempty := (depan = nil) and (belakang = nil) = true
end;
// procedure tambah ngantri digunakan untuk menambakan jumlah orang dalam antrian
procedure tambahngantri(var belakang : ngantri);
var
x : string;
tunjuk : ngantri;
begin
write('Masukkan nama orang yang mau masuk antrian : ');
readln(x);
baru(x, tunjuk);
belakang^.next := tunjuk;
belakang := tunjuk;
end;
// prosedure hapusdpn digunakan untuk menghapus list dalam ngantri
procedure hapusdpn(var depan, belakang : ngantri);
var
bantu : ngantri;
begin
if isempty(depan, belakang) then
writeln('Antrian Kosong')
else if depan = belakang then
begin
depan := nil;
belakang:=nil
end
else
begin
bantu := depan^.next;
depan := bantu;
end;
end;
// prosedure selesaiantri digunakan untuk mengambil orang yang telah selesai antri
procedure slesaingantri(var depan, belakang : ngantri; var x : string);
begin
if dpn = nil then
x := 'Antrian Kosong'
else
begin
x := dpn^.isi;
hapusdpn(depan, belakang);
end;
end;
// procedure buatngantrian untuk membangun ngantri dengan input data secara interaktif
procedure buatngantrian(var depan, belakang : ngantri);
var
c : char;
tunjuk : ngantri;
i : integer;
begin
i := 0;
depan := nil;
belakang := nil;
repeat
i := i+1;
write('masukan nama ke-',i ,' =');
readln(x);
baru(x, tunjuk);
if isempty(depan, belakang) then
begin
depan := tunjuk;
belakang := tunjuk;
end
else
begin
belakang^.next := tunjuk;
belakang := tunjuk;
end;
repeat
write('tambah data yang antri [Y/T] = ');
readln(c);
until c in ['T','t','y','Y'];
until c in ['T','t'];
end;
// procedure cetak untuk mencetak isi Antrian, pintu keluar antrian disebelah kanan dan pintu masuk antrian disebelah kiri
procedure cetak(depan : ngantri; var output : string);
var
bantu : ngantri;
y : string;
begin
bantu := depan;
output := ' Loket Pendaftaran';
if isempty(dpn, blk) then
output := 'Antrian Kosong'
else
begin
while bantu<>nil do
begin
y := bantu^.isi;
output := y + '->>' + output;
bantu := bantu^.next;
end;
output := 'pintu masuk antrian ->>' + output;
end;
end;
begin
buatngantrian(dpn, blk);
repeat
repeat
// menu utama
writeln;
writeln('-----------------------------------');
writeln('[1] Buat Antrian Baru ');
writeln('[2] Tambah Antrian Pendaftar ');
writeln('[3] Ambil Orang yang selesai daftar');
writeln('[4] Loket Pendaftaran ditutup ');
writeln('-----------------------------------');
write('Pilihan anda : '); pil := readkey; writeln(pil);
writeln;
until (pil >= '1') and (pil <= '4');
// case pil of mengacu pada menu pilihan yang akan mengaktifkan salah satu procedure yang dipilih
case pil of
'1' : begin
buatngantrian(dpn, blk);
writeln;
writeln;
writeln;
end;
'2' : begin
tambahngantri(blk);
writeln;
writeln('setelah ditambah antrian menjadi : ');
cetak(dpn, pointer);
writeln(pointer);
writeln;
writeln;
writeln;
end;
'3' : begin
slesaingantri(dpn, blk, x);
writeln('',x ,' Telah selesai mendaftar,maka ia keluar dari antrian');
writeln;
writeln('Antrian menjadi :');
cetak(dpn, pointer);
writeln(pointer);
writeln;
writeln;
writeln;
end;
'4' : begin
writeln(' Loket telah ditutup ');
writeln('Antrian dilanjutkan hari berikutnya');
exit;
end;
end;
until (pil = '8');
end.
end.

Related

Pascal Text Menu Music Player

I need help with creating my music player, I'm receiving the same error and can't seem to get past it. Thank you.
I've attached my code below, as well as my errors.
Errors:
Free Pascal Compiler version 2.6.4 [2014/02/26] for i386 Copyright (c)
1993-2014 by Florian Klaempfl and others Target OS: Darwin for i386
Compiling MusicPlayer.pas
MusicPlayer.pas(82,37) Error: Incompatible type for arg no. 1: Got "ShortString", expected "Album"
MusicPlayer.pas(138,31) Error: Incompatible type for arg no. 1: Got
"albumArray", expected "Album"
MusicPlayer.pas(164,44) Error: Incompatible type for arg no. 1: Got "albumArray", expected "Album"
MusicPlayer.pas(174) Fatal: There were 3 errors compiling module,
stopping Fatal: Compilation aborted Error: /usr/local/bin/ppc386
returned an error exitcode (normal if you did not specify a source
file to be compiled)
program MusicPlayer;
uses TerminalUserInput;
type
Track = record
trackName: String;
location: String;
end;
TrackArray = array of Track;
Album = record
albumName: String;
artistName: String;
genre: String;
track: TrackArray;
// key: Integer;
trackNum: Integer;
fileName: String;
end;
albumArray = array of Album;
function GetAlbums(): albumArray;
var
// anAlbum: Album;
//albums: albumArray;
fileName: String;
myFile: TextFile;
numOfAlb: Integer;
trackNum: Integer;
i: Integer;
j: Integer;
begin
fileName := ReadString('Enter filename: ');
AssignFile(myFile, fileName);
// AssignFile(myFile, 'albums.dat');
Reset(myFile);
ReadLn(myFile, numOfAlb);
setLength(result, numOfAlb);
for i:= 0 to High(result) do
begin
ReadLn(myFile, result[i].albumname);
ReadLn(myFile, result[i].artistName);
ReadLn(myFile, result[i].genre);
ReadLn(myFile, trackNum);
setLength(result[i].track, trackNum);
for j:= 0 to trackNum -1 do
begin
ReadLn(myFile, result[i].track[j].trackName);
ReadLn(myFile, result[i].track[j].location);
end;
end;
end;
procedure DisplayAlbum(a: Album);
var
//t: Track;
i: Integer;
begin
WriteLn('Album name is: ', a.albumName);
WriteLn('Album artist name is: ', a.artistName);
WriteLn('Album genre is: ', a.genre);
WriteLn('Number of tracks are: ', a.trackNum);
for i:= 0 to High(a.track) do
begin
WriteLn('Track name is: ', a.track[i].trackName);
WriteLn('Album name is: ', a.track[i].location);
end;
end;
function PrintAllGenres(albums: albumArray): albumArray;
var
i: Integer;
begin
for i := 0 to High(albums) do
begin
DisplayAlbum(albums[i].genre);
end;
end;
procedure SelectAlbum(const albums: albumArray);
var
val: Integer;
i: Integer;
begin
WriteLn('<< Welcome to the Track Player >>');
val := ReadInteger('Enter an Album''s key number: ');
for i := 0 to High(albums) do
begin
WriteLn('Album is now playing.');
end;
if (i > High(albums)) then
begin
WriteLn('Album was not found, now returning to Main Menu ');
end;
end;
function UpdateAlbum(a: Album): Album;
begin
a.albumName := ReadString('Please enter a new name for this album: ');
a.genre := ReadString('Please enter a new genre for this album: ');
end;
// function UpdateAlbums(): albumArray;
// var
// val: Integer;
// i: Integer;
// begin
// WriteLn('<< Album Updater >>');
// val := ReadInteger('Enter an Album''s key number: ');
// if (val = True) then
// WriteLn('Album was found.')
// else
// WriteLn('Album was not found, now returning to Main Menu ');
// end;
procedure DisplayAlbums(albums: albumArray);
var
val: Integer;
begin
repeat
WriteLn('<< Displaying Albums >>');
WriteLn('1. Display all albums');
WriteLn('2. Display genre');
WriteLn('3. Return to main menu');
val := ReadInteger('Enter a number to enter menu: ');
case val of
1: DisplayAlbum(albums);
2: PrintAllGenres(albums);
end;
until val = 3;
end;
procedure Main();
var
albums: albumArray;
val: Integer;
begin
repeat
WriteLn('<< Text Music Player Menu >>');
WriteLn('1. Read in Albums');
WriteLn('2. Display Albums');
WriteLn('3. Select an Album to play');
WriteLn('4. Update an existing Album');
WriteLn('5. Quit');
val := ReadInteger('Enter a number to enter menu: ');
case val of
1: albums := GetAlbums();
2: DisplayAlbums(albums);
3: SelectAlbum(albums);
4: albums := UpdateAlbum(albums);
end;
until val = 5;
end;
begin
Main();
end.
In your code you have written
procedure DisplayAlbum(a: Album);
which means that you need to pass an Album to the procedure, but on line 82 you have written
DisplayAlbum(albums[i].genre);
genre is a field of an Album while you should pass a whole Album
Change line 82 to
DisplayAlbum(albums[i]);
I leave the other errors for you yourself to work out, the errors are very similar, and you should now be able to sort them out.
As I told you yesterday, you may want to (or actually, need to) speak with your tutor to get a better understanding.

Pascal: Error trying to rewrite array and assistance with printing my array

So i'm working on this pascal application which has a menu where you can do multiple things.
After entering an album (which is what my program does) and trying to edit it by writing over the current album I get an error as shown in the image.
There have been no errors when compiling except the warning:
(100,9) Warning: Function result variable does not seem to initialized
Here is my code:
program MusicPlayer;
uses TerminalUserInput;
type
// You should have a track record
TrackRec = record
name: String;
location: String;
end;
type TrackArray = array of TrackRec;
GenreType = (Pop, Rap, Rock, Classic);
AlbumRec = Record
name: String;
genre: GenreType;
location: array of TrackRec; // this and track should be track: array of TrackRec
numberOfTracks: Integer;
tracks: TrackArray;
end;
type AlbumArray = array of AlbumRec; // this should be an array of AlbumRec
function ReadGenre(prompt: String): GenreType;
var
option: Integer;
begin
WriteLn('Press 1 for Pop');
WriteLn('Press 2 for Rap');
WriteLn('Press 3 for Rock');
WriteLn('Press 4 for Classic');
option := ReadInteger(prompt);
while (option<1) or (option>3) do
begin
WriteLn('Please enter a number between 1-4');
option := ReadInteger(prompt);
end;
case option of
1: result := Pop;
2: result := Rap;
3: result := Rock;
else
result := Classic;
end;
end;
function CheckLength(prompt: string): Integer;
var
i: Integer;
begin
i := ReadInteger(prompt);
while (i < 0) or (i > 20) do
begin
WriteLn('Please enter a number between 1-20');
i := ReadInteger(prompt);
end;
result := i;
end;
function ReadTracks(count: Integer): TrackArray;
var
i: Integer;
begin
setLength(result, count);
for i := 0 to High(result) do
begin
result[i].name := ReadString('Track Name: ');
result[i].location := ReadString('Track Location: ');
end;
end;
function ReadAlbum(): AlbumRec;
begin
result.name := ReadString('What is the name of the album?');
result.genre := ReadGenre('What is the genre of the album?');
result.numberOfTracks := CheckLength('How many tracks are in the album?');
result.tracks := ReadTracks(result.numberOfTracks);
end;
function ReadAlbums(count: Integer): AlbumArray;
var
i: Integer;
begin
SetLength(result, count);
for i := 0 to High(result) do
begin
result[i] := ReadAlbum();
end;
end;
function ChangeAlbum(count: Integer): AlbumArray;
var
i: Integer;
begin
for i := count to count do
begin
result[i] := ReadAlbum();
end;
end;
procedure PrintAlbum(count: Integer; album: array of AlbumRec);
var
i: Integer;
begin
if count = 1 then
begin
for i := 0 to High(album) do
begin
WriteLn('Album Number: ', i);
WriteLn('Album name is: ', album[i].name);
WriteLn('Album genre is: ', album[i].genre);
end
end;
for i := 1 to count - 1 do
begin
WriteLn('Album name is: ', album[i].name);
WriteLn('Album genre is: ', album[i].genre);
end;
end;
procedure PrintTrack(tracks: TrackArray);
var
i: Integer;
begin
i := ReadInteger('Which track number do you wish to play?');
i := i - 1;
WriteLn('Now playing track: ', tracks[i].name);
WriteLn('Track location: ', tracks[i].location);
end;
function CheckIfFinished(): Boolean;
var answer: String;
begin
WriteLn('Do you want to enter another set of tracks? ');
ReadLn(answer);
LowerCase(answer);
case answer of
'no': result := true;
'n': result := true;
'x': result := true;
else
result := false;
end;
end;
procedure Main();
var
i, count, select, change: Integer;
albums: AlbumArray;
begin
WriteLn('Please select an option: ');
WriteLn('-------------------------');
WriteLn('1. Read Albums');
WriteLn('2. Display Albums');
WriteLn('3. Select an Album');
WriteLn('4. Update an Album');
WriteLn('5. Exit');
WriteLn('-------------------------');
repeat
i := ReadInteger('Your Option:');
case i of
1:
begin
count := ReadInteger('How many albums: ');
albums := ReadAlbums(count);
end;
2:
begin
WriteLn('1. Display All Albums');
WriteLn('2. Display All Albums by Genre');
select := ReadInteger('Your Option: ');
if i = 1 then
begin
PrintAlbum(select, albums);
end;
// if i = 2 then
// WriteLn('1. Pop');
// WriteLn('2. Rap');
// WriteLn('3. Rock');
// WriteLn('4. Classic');
// albums := ReadAlbums(count);
end;
3:
begin
select := ReadInteger('Which album would you like to play? ');
PrintAlbum(select, albums);
PrintTrack(albums[select-1].tracks);
end;
4:
begin
change := ReadInteger('Which album would you like to edit?');
albums := ChangeAlbum(change);
end;
end;
until i = 5;
end;
begin
Main();
end.
The function that the warning refers to, on line 100, is
function ChangeAlbum(count: Integer): AlbumArray;
var
i: Integer;
begin
for i := count to count do
begin
result[i] := ReadAlbum();
end;
end;
The warning says:
Warning: Function result variable does not seem to initialized
And indeed the result variable has not been initialized.
The design of the function is wrong though. You are trying to modify an existing element in an array. You should not be returning a new array. The function is not necessary though. You should simply remove it. Then you need to look at the one place where you call the function.
change := ReadInteger('Which album would you like to edit?');
albums := ChangeAlbum(change);
You should instead code that like this:
change := ReadInteger('Which album would you like to edit?');
albums[change] := ReadAlbum();
I've not checked anything else in your program. I would not be surprised if there are other problems. I've just tried to address the specific question that you asked.

Why does my button click event handler not do what I expect?

so I found a blackjack source code on this forum, but I have a problem to make it work. I had made the form myself for the code and I think that is the problem. The game should start when I click the "new button", but nothing happen when I click on it.
Here is the source code:
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
ExtCtrls, Buttons;
type
{ TForm1 }
TForm1 = class(TForm)
BetCount: TLabel; //not used
MoneyEdit: TEdit; //not used
BetEdit: TEdit; //not used
HitBtn: TButton;
MoneyCountLbl: TLabel; //not used
NewBtn: TButton;
StandBtn: TButton;
PlayerEdit: TEdit;
DealerEdit: TEdit;
MemoDealer: TMemo;
MemoPlayer: TMemo;
procedure PickASuit;
procedure PickACard;
procedure CardName;
procedure LookAtHands;
procedure newDeal;
procedure DoIt(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
var
suitNum, cardNum, current, total1, total2 : Integer;
suitStr, cardStr : String[8];
procedure TForm1.PickASuit;
begin
suitNum := random(4)+1;
Case suitNum of
1 : suitStr := 'Spades';
2 : suitStr := 'Clubs';
3 : suitStr := 'Diamonds';
4 : suitStr := 'Hearts';
end;
end;
procedure TForm1.CardName;
begin
Case cardNum of
1 : cardStr := 'Ace';
2 : cardStr := 'Two';
3 : cardStr := 'Three';
4 : cardStr := 'Four';
5 : cardStr := 'Five';
6 : cardStr := 'Six';
7 : cardStr := 'Seven';
8 : cardStr := 'Eight';
9 : cardStr := 'Nine';
10 : cardStr := 'Ten';
11 : cardStr := 'Jack';
12 : cardStr := 'Queen';
13 : cardStr := 'King';
end;
Case cardNum of
1 : cardNum := 11;
10..13 : cardNum := 10;
end;
end;
procedure TForm1.PickACard;
begin
cardNum := random(13)+1;
PickASuit; {runs pickasuit procedure}
CardName; {runs cardnume procedure}
Case current of {tells the program what its doing}
1 : begin
MemoPlayer.Lines.Add(cardStr + ' of ' + suitStr );
total1 := total1 + cardNum;
PlayerEdit.Text := IntToStr(total1);
end;
2 : begin
MemoDealer.Lines.Add(cardStr + ' of ' + suitStr );
total2 := total2 + cardNum;
DealerEdit.Text := IntToStr(total2);
end;
end;
end;
procedure TForm1.LookAtHands;
Begin
If total2 > 21 then ShowMessage('House Busted')
Else if total1 > total2 then ShowMessage('You win')
Else if total1 = total2 then ShowMessage('Draw')
Else ShowMessage('You lose');
newDeal;
End;
procedure TForm1.newDeal;
Begin
MemoDealer.Clear;
MemoPlayer.Clear;
total1 := 0;
total2 := 0;
current := 1;
PickACard;
current := 2;
PickACard;
end;
procedure TForm1.DoIt(Sender: TObject);
begin
current := (Sender as TButton).Tag;
Case current of
1 : Begin
PickACard;
If total1 > 21 then
begin ShowMessage('Busted');
newDeal;
end;
end;
2 : begin While total2 < 17 do PickACard;
LookAtHands;
end;
3 : newDeal;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Randomize;
end;
end.
I set hit, new, and stand buttons to execute the procedure 'DoIt'
Do I make a mistake ? I'm just starting to learn delphi, so I hope you guys can understand if I do something "stupid" .
You probably did not fill the tag properties of the Buttons on the form. Look in the list of properties of each button for the Tag property. The HitBtn should have a Tag of 1. There's at least one other button that should have a Tag of 2.

Why My server application freeze after several clients connected?

i am using indy TidTcpserver inside my server application its working good but some times after 10 clients connected my server application got a deadlock and stop from response here is my server execute and broadcast protocol codes
Tcp server execute
procedure TfMain.TCPServerExecute(AContext: TIdContext);
var
Connection: TConnection;
Command: String;
Params: array[1..10] of String;
ParamsCount, P: Integer;
PackedParams: TPackedParams;
IdBytes: TIdBytes;
MS: TMemoryStream;
ReceiveParams, ReceiveStream: Boolean;
Size: Int64;
begin
Connection := Pointer(AContext.Data);
MS := TMemoryStream.Create;
ReceiveParams := False;
ReceiveStream := False;
Command := AContext.Connection.Socket.ReadLn; //read command
if Command[1] = '1' then //command with params
begin
Command := Copy(Command, 2, Length(Command));
ReceiveParams := True;
end
else if Command[1] = '2' then //command + memorystream
begin
Command := Copy(Command, 2, Length(Command));
ReceiveStream := True;
MS.Position := 0;
end
else if Command[1] = '3' then //command with params + memorystream
begin
Command := Copy(Command, 2, Length(Command));
ReceiveParams := True;
ReceiveStream := True;
end;
if ReceiveParams then //params is incomming
begin
AContext.Connection.Socket.ReadBytes(IdBytes, SizeOf(PackedParams), False);
BytesToRaw(IdBytes, PackedParams, SizeOf(PackedParams));
ParamsCount := 0;
repeat
Inc(ParamsCount);
p := Pos(Sep, String(PackedParams.Params));
Params[ParamsCount] := Copy(String(PackedParams.Params), 1, P - 1);
Delete(PackedParams.Params, 1, P + 4);
until PackedParams.Params = '';
end;
if ReceiveStream then //stream is incomming
begin
Size := AContext.Connection.Socket.ReadInt64;
AContext.Connection.Socket.ReadStream(MS, Size, False);
MS.Position := 0;
end;
if Command = 'LOGIN' then
begin
usrnm := Params[1];
passwd := params[2];
if not userexists(usrnm, passwd) then
AContext.Connection.Socket.WriteLn('INVALIDPASSWORD')
else
begin
userslq.Close;
userslq.SQL.Clear;
userslq.SQL.Add('SELECT * FROM `users` WHERE `username` = "'+ trim(usrnm) +'" AND `password` = "' + trim(passwd) + '"');
userslq.Open;
if NOT userslq.IsEmpty then
begin
SendCommandWithParams(Connection, 'SENDYOURINFO', IntToStr(Connection.UniqueID) + Sep);
userslq.Close;
end;
userslq.Close;
userslq.SQL.Clear;
userslq.SQL.Add('UPDATE `users` SET `lastlogin` = :Date, `timeslogin`=(`timeslogin`+1) WHERE `users`.`username` = :uname;');
userslq.ParamByName('uname').AsString := trim(usrnm);
userslq.ParamByName('Date').AsDate := Now;
userslq.ExecSQL;
userslq.Close;
end;
end;
if Command = 'TAKEMYINFO' then //login ok, add to listview
begin
Connection.Name := Params[1];
Connections.Add(Connection);
AddConnectionToListView(Connection);
end;
if Command = 'TEXTMESSAGE' then
begin
BroadCastTextMessage(Params[1], Connection.UniqueID, Connection.Name, Connection.IP);
end;
if Command = 'DISCONNECTED' then
begin
DeleteConnectionFromList(Connection.UniqueID);
DeleteConnectionFromListView(Connection.UniqueID);
end;
MS.Free;
end;
broadcast Protocol and used procedures
procedure TfMain.AddConnectionToListView(Connection: TConnection);
begin
with lwConnections.Items.Add do
begin
Caption := Connection.Name;
SubItems.Add(Connection.IP);
SubItems.Add(FormatDateTime('hh:mm:ss', Connection.Connected));
SubItems.Add(IntToStr(Connection.UniqueID));
end;
end;
procedure TfMain.DeleteConnectionFromListView(UniqueID: DWord);
var
I: Integer;
begin
for I := 0 to lwConnections.Items.Count - 1 do
begin
if lwConnections.Items.Item[I].SubItems.Strings[2] = IntToStr(UniqueID) then
begin
lwConnections.Items.Delete(I);
Break;
end;
end;
end;
procedure TfMain.DeleteConnectionFromList(UniqueID: DWord);
var
I, Pos: Integer;
begin
Pos := -1;
for I := 0 to Connections.Count - 1 do
begin
if TConnection(Connections.Items[I]).UniqueID = UniqueID then
begin
Pos := I;
Break;
end;
end;
if Pos <> -1 then
Connections.Delete(Pos);
end;
procedure TfMain.BroadCastTextMessage(const TextMessage: String; const FromUniqueID: DWord;
const FromName: string; const dip: string);
var
I: Integer;
Connection: TConnection;
begin
for I := 0 to Connections.Count - 1 do
begin
Connection := Connections.Items[I];
if Connection.UniqueID <> FromUniqueID then
SendCommandWithParams(Connection, 'TEXTMESSAGE', FromName + Sep + TextMessage + Sep + dip + Sep);
end;
end;
procedure TfMain.SendCommandWithParams(Connection: TConnection; Command, Params:String);
var
PackedParams: TPackedParams;
begin
if not TIdContext(Connection.Thread).Connection.Socket.Connected then
Exit;
TCPServer.Contexts.LockList;
try
PackedParams.Params := ShortString(Params);
with TIdContext(Connection.Thread).Connection.Socket do
begin
WriteLn('1' + Command);
Write(RawToBytes(PackedParams, SizeOf(PackedParams)));
end;
finally
TCPServer.Contexts.UnlockList;
end;
end;
on connect server event
procedure Tfmain.TcpServerConnect(AContext: TIdContext);
var
Connection : TConnection;
begin
Connection := TConnection.Create;
Connection.IP := AContext.Connection.Socket.Binding.PeerIP;
Connection.Connected := Now;
Connection.UniqueID := GetTickCount;
if Connection.UniqueID = LastUniqueID then
Connection.UniqueID := GetTickCount + 1000;
LastUniqueID := Connection.UniqueID;
Connection.Thread := AContext;
AContext.Data := Connection;
end;
Updated
by following remy answer and his great details i started to do synchronize but in remy answer i am confused about TCriticalSection also i will have to rewrite the client code to be able to do same as his code doing , so i had to go with thread synchronize first here is example of what i did by following remy code i did some manage and removed database temporarily to avoid confusing here is the code of trying synchronization UI inside server execute
if Command = 'LOGIN' then
begin
if Password <> Params[1] then
AContext.Connection.Socket.WriteLn('INVALIDPASSWORD')
else
SendCommandWithParams(Connection, 'SENDYOURINFO', IntToStr(Connection.UniqueID) + Sep);
end;
if Command = 'TAKEMYINFO' then //login ok, add to listview
begin
Connection.Name := Params[1];
Connections.Add(Connection);
AddConnectionToListView(Connection);// this is not safe i know and thats what makes me confused so in this procedure call i do same as remy doing
end;
procedure TfMain.AddConnectionToListView(Connection: TConnection);
begin
TThread.Queue(nil,
procedure
var
Item: TListItem;
begin
Item := lwConnections.Items.Add;
try
Item.Caption := Connection.Name;
Item.SubItems.Add(Connection.IP);
Item.SubItems.Add(FormatDateTime('hh:mm:ss', Connection.Connected));
Item.SubItems.Add(IntToStr(Connection.UniqueID));
except
Item.Delete;
raise;
end;
end
);
end;
is this correct to synchronize ? whats makes me confused is this thread synchronize by itself ? i mean there is no thread class to execute and synchronize is this correct way ?
Updates about synchronize
Remy answer helps me i thanks him too much , but iam trying to understand thus synchronize part i found some ways on google as example include
idsync in my uses
and call it like this as example
uses
idsync;
// and in server execute i call TiDNotify To synchronize what ever i want ?
procedure TfMain.DeleteConnectionFromListView;
var
I: Integer;
begin
for I := 0 to lwConnections.Items.Count - 1 do
begin
if lwConnections.Items.Item[I].SubItems.Strings[2] = IntToStr(linetToID) then
begin
DeleteConnectionFromList(linetToID);
lwConnections.Items.Delete(I);
Break;
end;
end;
end;
procedure TfMain.TCPServerExecute(AContext: TIdContext);
var
Connection: TConnection;
Command: String;
Params: array[1..10] of String;
ParamsCount, P: Integer;
PackedParams: TPackedParams;
IdBytes: TIdBytes;
MS: TMemoryStream;
ReceiveParams, ReceiveStream: Boolean;
Size: Int64;
begin
Connection := Pointer(AContext.Data);
MS := TMemoryStream.Create;
ReceiveParams := False;
ReceiveStream := False;
Command := AContext.Connection.Socket.ReadLn; //read command
if Command[1] = '1' then //command with params
begin
Command := Copy(Command, 2, Length(Command));
ReceiveParams := True;
end
else if Command[1] = '2' then //command + memorystream
begin
Command := Copy(Command, 2, Length(Command));
ReceiveStream := True;
MS.Position := 0;
end
else if Command[1] = '3' then //command with params + memorystream
begin
Command := Copy(Command, 2, Length(Command));
ReceiveParams := True;
ReceiveStream := True;
end;
if ReceiveParams then //params is incomming
begin
AContext.Connection.Socket.ReadBytes(IdBytes, SizeOf(PackedParams), False);
BytesToRaw(IdBytes, PackedParams, SizeOf(PackedParams));
ParamsCount := 0;
repeat
Inc(ParamsCount);
p := Pos(Sep, String(PackedParams.Params));
Params[ParamsCount] := Copy(String(PackedParams.Params), 1, P - 1);
Delete(PackedParams.Params, 1, P + 4);
until PackedParams.Params = '';
end;
if ReceiveStream then //stream is incomming
begin
Size := AContext.Connection.Socket.ReadInt64;
AContext.Connection.Socket.ReadStream(MS, Size, False);
MS.Position := 0;
end;
if Command = 'LOGIN' then
begin
if Password <> Params[1] then
AContext.Connection.Socket.WriteLn('INVALIDPASSWORD')
else
SendCommandWithParams(Connection, 'SENDYOURINFO', IntToStr(Connection.UniqueID) + Sep);
end;
if Command = 'TAKEMYINFO' then //login ok, add to listview
begin
Connection.Name := Params[1];
Connections.Add(Connection);
TIdNotify.NotifyMethod(Connection.AddToListView);
end;
if Command = 'TEXTMESSAGE' then
begin
BroadCastTextMessage(Params[1], Connection.UniqueID);
end;
if Command = 'GETLIST' then
begin
SendClientsListTo(Connection.UniqueID);
end;
if Command = 'DISCONNECTED' then
begin
linetToID := Connection.UniqueID;// fmain private string variable
TIdNotify.NotifyMethod(DeleteConnectionFromListView);
end;
MS.Free;
end;
TIdTCPServer is a multi-threaded component. Its OnExecute event is triggered in the context of a worker thread. But your TAKEMYINFO and DISCONNECTED command handlers are directly accessing UI controls without synchronizing with the main UI thread. That can easily cause deadlocks (amongst other problems, including crashes, killing the UI, etc). You MUST sync!
Also, is userexists() thread-safe? Is userslq? Your use of the Connections list is definitely not thread-safe.
Why is SendCommandWithParams() locking the server's Contexts list, especially when called by OnExecute? You don't need to do that. You should be locking it in BroadCastTextMessage() instead.
Try something more like this:
type
TConnnection = class(TIdServerContext)
private
WriteLock: TCriticalSection;
public
Name: String;
IP: String;
Connected: TDateTime;
UniqueID: Dword;
constructor Create(AConnection: TIdTCPConnection; AYarn: TIdYarn; AList: TIdContextThreadList = nil); override;
destructor Destroy; override;
procedure AddToListView;
procedure DeleteFromListView;
procedure BroadcastTextMessage(const TextMessage: String);
procedure SendCommandWithParams(const Command, Params: String);
procedure SendLn(const S: String);
function UserExists(const User, Passwd: string): Boolean;
procedure UpdateLastLogin(const User: String);
end;
constructor TConnection.Create(AConnection: TIdTCPConnection; AYarn: TIdYarn; AList: TIdContextThreadList = nil);
begin
inherited;
WriteLock := TCriticalSection.Create;
end;
destructor TConnection.Destroy;
begin
WriteLock.Free;
inherited;
end;
procedure TConnection.AddToListView;
var
LName: string;
LIP: string;
LConnected: TDateTime;
LUniqueID: Dword;
begin
// in case the client disconnects and destroys this object before
// TThread.Queue() can update the ListView, capture the values so
// this object's fields are not accessed directly...
//
LName := Self.Name;
LIP := Self.IP;
LConnected := Self.Connected;
LUniqueID := Self.UniqueID;
TThread.Queue(nil,
procedure
var
Item: TListItem;
begin
if (fMain = nil) or (fMai.lwConnections = nil) then Exit;
Item := fMain.lwConnections.Items.Add;
try
Item.Data := Self;
Item.Caption := LName;
Item.SubItems.Add(LIP);
Item.SubItems.Add(FormatDateTime('hh:mm:ss', LConnected));
Item.SubItems.Add(IntToStr(LUniqueID));
except
Item.Delete;
raise;
end;
end
);
end;
procedure TConnection.DeleteFromListView;
begin
TThread.Queue(nil,
procedure
var
Item: TListItem;
begin
if (fMain = nil) or (fMai.lwConnections = nil) then Exit;
Item := fMain.lwConnections.FindData(0, Self, True, False);
if Item <> nil then Item.Delete;
end
);
end;
procedue TConnection.BroadCastTextMessage(const TextMessage: String);
var
List: TList; // or TIdContextList if using a modern Indy version
I: Integer;
Connection: TConnection;
begin
List := Server.Contexts.LockList;
try
for I := 0 to List.Count - 1 do
begin
Connection := TConnection(List.Items[I]);
if Connection <> Self then
begin
try
Connection.SendCommandWithParams('TEXTMESSAGE', FromName + Sep + TextMessage + Sep + dip + Sep);
except
end;
end;
finally
Server.Contexts.UnlockList;
end;
end;
procedure TConnection.SendCommandWithParams(const Command, Params: String);
var
PackedParams: TPackedParams;
begin
PackedParams.Params := ShortString(Params);
WriteLock.Enter;
try
with Connection.Socket do
begin
WriteLn('1' + Command);
Write(RawToBytes(PackedParams, SizeOf(PackedParams)));
end;
finally
WriteLock.Leave;
end;
end;
procedure TConnection.SendLn(const S: String);
begin
WriteLock.Enter;
try
Connection.Socket.WriteLn(S);
finally
WriteLock.Leave;
end;
end;
function TConnection.UserExists(const User, Passwd: string): Boolean;
var
Exists: Boolean;
begin
// if you give each client its own DB connection, or use
// a thread-safe DB pool, you don't have to sync this ...
//
TThread.Synchronize(nil,
procedure
if (fMain = nil) or (fMai.userslq = nil) then Exit;
with fMain.userslq do
begin
Close;
SQL.Text := 'SELECT * FROM `users` WHERE `username` = :uname AND `password` = :passwd;';
ParamByName('uname').AsString := Trim(User);
ParamByName('passwd').AsString := Trim(Passwd);
Open;
try
Exists := not IsEmpty;
finally
Close;
end;
end;
end
);
Result := Exists;
end;
procedure TConnection.UpdateLastLogin(const User: String);
begin
// if you give each client its own DB connection, or use
// a thread-safe DB pool, you don't have to sync this ...
//
TThread.Synchronize(nil,
procedure
if (fMain = nil) or (fMai.userslq = nil) then Exit;
with fMain.userslq do
begin
Close;
SQL.Text := 'UPDATE `users` SET `lastlogin` = :Date, `timeslogin`=(`timeslogin`+1) WHERE `users`.`username` = :uname;';
ParamByName('uname').AsString := Trim(User);
ParamByName('Date').AsDate := Now;
ExecSQL;
Close;
end;
end
);
end;
procedure TfMain.FormCreate(Sender: TObject);
begin
// set this before activating the server
TCPServer.ContextClass := TConnection;
end;
procedure TfMain.TCPServerConnect(AContext: TIdContext);
var
Connection: TConnection;
begin
Connection := AContext as TConnection;
Connection.Name := '';
Connection.IP := AContext.Binding.PeerIP;
Connection.Connected := Now;
Connection.UniqueID := ...;
end;
procedure TfMain.TCPServerDisconnect(AContext: TIdContext);
var
Connection: TConnection;
begin
Connection := AContext as TConnection;
Connection.DeleteFromListView;
end;
procedure TfMain.TCPServerExecute(AContext: TIdContext);
var
Connection: TConnection;
Command: String;
Params: array[1..10] of String;
ParamsCount, P: Integer;
PackedParams: TPackedParams;
IdBytes: TIdBytes;
MS: TMemoryStream;
ReceiveParams, ReceiveStream: Boolean;
S: String;
begin
Connection := AContext as TConnection;
Command := AContext.Connection.Socket.ReadLn; //read command
if Command = '' then Exit;
ReceiveParams := False;
ReceiveStream := False;
if Command[1] = '1' then //command with params
begin
Command := Copy(Command, 2, MaxInt);
ReceiveParams := True;
end
else if Command[1] = '2' then //command + memorystream
begin
Command := Copy(Command, 2, MaxInt);
ReceiveStream := True;
end
else if Command[1] = '3' then //command with params + memorystream
begin
Command := Copy(Command, 2, MaxInt);
ReceiveParams := True;
ReceiveStream := True;
end;
if ReceiveParams then //params is incomming
begin
AContext.Connection.Socket.ReadBytes(IdBytes, SizeOf(PackedParams), False);
BytesToRaw(IdBytes, PackedParams, SizeOf(PackedParams));
S := String(PackedParams.Params);
ParamsCount := 0;
while (S <> '') and (ParamsCount < 10) do
begin
Inc(ParamsCount);
p := Pos(Sep, S);
if p = 0 then
Params[ParamsCount] := S
else
begin
Params[ParamsCount] := Copy(S, 1, P - 1);
Delete(S, 1, P + 4);
end;
end;
end;
MS := nil;
try
if ReceiveStream then //stream is incomming
begin
MS := TMemoryStream.Create;
AContext.Connection.Socket.LargeStream := True;
AContext.Connection.Socket.ReadStream(MS, -1, False);
MS.Position := 0;
end;
if Command = 'LOGIN' then
begin
if ParamsCount <> 2 then
begin
Connection.SendLn('INVALIDPARAMS');
Exit;
end;
if not Connection.UserExists(Params[1], Params[2]) then
begin
Connection.SendLn('INVALIDPASSWORD');
Exit;
end;
Connection.UpdateLastLogin(Params[1]);
Connection.SendCommandWithParams('SENDYOURINFO', IntToStr(Connection.UniqueID) + Sep);
end
else if Command = 'TAKEMYINFO' then //login ok, add to listview
begin
if ParamsCount <> 1 then
begin
Connection.SendLn('INVALIDPARAMS');
Exit;
end;
Connection.Name := Params[1];
Connection.AddToListView;
end
else if Command = 'TEXTMESSAGE' then
begin
if ParamsCount <> 1 then
begin
Connection.SendLn('INVALIDPARAMS');
Exit;
end;
Connection.BroadCastTextMessage(Params[1]);
end
else if Command = 'DISCONNECTED' then
begin
AContext.Connection.Disconnect;
Exit;
end;
finally
MS.Free;
end;
end;

ClientDataSet TBCDField rounding

I'm using Delphi 5 + BDE + Oracle. I have the following function:
class function TClientDataSetFactory.GetClientDataSet(
const qryGen: TDataSet): TClientDataSet;
var
dspDados: TDataSetProvider;
begin
Result := nil;
try
try
Result := TClientDataSet.Create(nil);
dspDados := TDataSetProvider.Create(Result);
dspDados.DataSet := qryGen;
qryGen.Active := True;
qryGen.First;
Result.Data := dspDados.Data;
Result.First;
except
on E: Exception do
begin
raise;
end;
end;
finally
end;
end;
so, when a run this:
var
qryGen: TQuery;
cdsGen: TClientDataSet;
begin
qryGen := nil;
try
try
qryGen := CriaQuery();
qryGen.SQL.Text :=
'SELECT SUM(TOTAL) AS TOTAL FROM MYTABLE';
cdsGen := TClientDataSetFactory.GetClientDataSet(qryGen);
ShowMessageFmt('Total: %f', [cdsGen.FieldByName('TOTAL').AsFloat]);
except
on E: Exception do
begin
raise;
end;
end;
finally
if Assigned(qryGen) then FreeAndNil(qryGen);
end;
end;
i got "159,00" but, if i run this:
ShowMessageFmt('Total: %f', [qryGen.FieldByName('TOTAL').AsFloat]);
i got "159,25".
can someone help me?
I solved the problem with another solution.
type
TInternalQuery = class(TQuery)
protected
procedure InternalInitFieldDefs; override;
public
constructor Create(AOwner: TComponent; const qryGen: TQuery); reintroduce;
end;
constructor TInternalQuery.Create(AOwner: TComponent; const qryGen: TQuery);
var
intCont: Integer;
begin
inherited Create(AOwner);
Self.DatabaseName := qryGen.DatabaseName;
Self.UpdateObject := qryGen.UpdateObject;
Self.SQL.Text := qryGen.SQL.Text;
for intCont := 0 to Self.ParamCount - 1 do
begin
Self.Params[intCont].Value := qryGen.Params[intCont].Value;
end;
end;
procedure TInternalQuery.InternalInitFieldDefs;
var
intCont: Integer;
begin
inherited InternalInitFieldDefs;
for intCont := 0 to FieldDefs.Count - 1 do
begin
if (FieldDefs[intCont].Size = 0) and (FieldDefs[intCont].DataType = ftBCD) then
begin
FieldDefs[intCont].Precision := 64;
FieldDefs[intCont].Size := 32;
end;
end;
end;
the problem is ((FieldDefs[intCont].Size = 0) and (FieldDefs[intCont].DataType = ftBCD)). when ClientDataSet is created, the field is truncated, because when oracle has a function like "SUM(TOTAL)" the result field is created with size 0, so the clientdataset handle the field as Integer field.
Try with
ShowMessageFmt('Total: %n', [cdsGen.FieldByName('TOTAL').AsFloat])
or this
cdsGen := TClientDataSetFactory.GetClientDataSet(qryGen);
**(cdsGen.FieldByName('Total') as TFloatField).DisplayFormat := '0.00';**
ShowMessageFmt('Total: %f', [cdsGen.FieldByName('TOTAL').AsFloat])

Resources