ORA-01403 "no data found" - UTL_FILE - oracle10g

I have the following script to create 3 files:
set serveroutput on
declare
nombreArchivo varchar2(30);
f_out UTL_FILE.FILE_TYPE;
begin
nombreArchivo :='fich_fseek.txt';
dbms_output.put_line('Abrir el fichero '||nombrearchivo||' en modo escritura.');
f_out:=UTL_FILE.FOPEN('TEMPORAL',nombreArchivo,'w');
UTL_FILE.PUT_LINE(f_out,'Hola, me llamo Álvaro.');
UTL_FILE.PUT_LINE(f_out,'Esto es una prueba para ver cómo funcionan las funciones FSEEK y FGETPOS.');
UTL_FILE.PUT_LINE(f_out,'Espero que te diviertas.');
UTL_FILE.NEW_LINE(f_out,1);
UTL_FILE.PUT_LINE(f_out,'Atentamente,');
UTL_FILE.PUT_LINE(f_out,'el que esto escribe');
UTL_FILE.FCLOSE(f_out);
nombreArchivo :='caracter.txt';
dbms_output.put_line('Abrir el fichero '||nombrearchivo||' en modo escritura.');
f_out:=UTL_FILE.FOPEN('TEMPORAL',nombreArchivo,'w');
UTL_FILE.PUT(f_out,'a');
UTL_FILE.FCLOSE(f_out);
nombreArchivo :='vacio.txt';
dbms_output.put_line('Abrir el fichero '||nombrearchivo||' en modo escritura.');
f_out:=UTL_FILE.FOPEN('TEMPORAL',nombreArchivo,'w');
UTL_FILE.FCLOSE(f_out);
exception
when others then -- así me aseguro que cualquier flujo abierto será cerrado
dbms_output.put_line('Se ha producido un error: '||SQLERRM);
UTL_FILE.FCLOSE_ALL;
end;
/
the problem arises when I create another script to read the files without making use of the exception clause :
set serveroutput on
declare
nombreArchivo varchar2(30):='fich_fseek.txt';
--nombreArchivo varchar2(30):='caracter.txt';
--nombreArchivo varchar2(30):='vacio.txt';
f_out UTL_FILE.FILE_TYPE;
texto varchar2(100);
posición pls_integer := 0;
existe boolean;
tamaño_archivo number;
tamaño_bloque number;
begin
UTL_FILE.FGETATTR('TEMPORAL', nombreArchivo, existe, tamaño_archivo, tamaño_bloque);
if existe then
if tamaño_archivo > 0 then
dbms_output.put_line('Abrir el fichero '||nombrearchivo||' en modo lectura, que tiene un tamaño de '||tamaño_archivo||' bytes.');
f_out:=UTL_FILE.FOPEN('TEMPORAL',nombreArchivo,'r');
posición := UTL_FILE.FGETPOS(f_out);
while posición < tamaño_archivo loop
UTL_FILE.GET_LINE(f_out, texto);
dbms_output.put_line('pre Posición '||posición);
dbms_output.put_line(texto);
posición := UTL_FILE.FGETPOS(f_out);
dbms_output.put_line('post Posición '||posición);
end loop;
UTL_FILE.FCLOSE(f_out);
else
dbms_output.put_line('El fichero '||nombrearchivo||' está vacío (0 bytes).');
end if;
else
dbms_output.put_line('El archivo '||nombrearchivo||' no existe');
end if;
end;
/
Then an ORA-01403 "no data found" happens, but only with the 'fich_fseek.txt' file.

Thanks to Alex Poole for his comments. In effect, if in Windows is counting the new line characters in a wrong way, then instead of reading until readed_bytes is less than the file_size I will use a corrected_size: loop until readed_bytes is less than the corrected_size. And the correction is quite simple, at the starting point corrected_size equals file_size, but every time a new line is read the corrected_size will decrease in one unit (byte):
set serveroutput on
declare
nombreArchivo varchar2(30):='fich_fseek.txt';
--nombreArchivo varchar2(30):='caracter.txt';
--nombreArchivo varchar2(30):='vacio.txt';
f_out UTL_FILE.FILE_TYPE;
texto varchar2(100);
posición pls_integer := 0;
existe boolean;
tamaño_archivo number;
tamaño_bloque number;
tamaño_corregido number;
begin
UTL_FILE.FGETATTR('TEMPORAL', nombreArchivo, existe, tamaño_archivo, tamaño_bloque);
if existe then
if tamaño_archivo > 0 then
dbms_output.put_line('Abrir el fichero '||nombrearchivo||' en modo lectura, que tiene un tamaño de '||tamaño_archivo||' bytes.');
f_out:=UTL_FILE.FOPEN('TEMPORAL',nombreArchivo,'r');
posición := UTL_FILE.FGETPOS(f_out);
tamaño_corregido := tamaño_archivo;
while posición < tamaño_corregido loop -- hay que poner el -6 para evitar un error no_data_found
UTL_FILE.GET_LINE(f_out, texto);
--dbms_output.put_line('pre Posición '||posición);
dbms_output.put_line(texto);
posición := UTL_FILE.FGETPOS(f_out);
--dbms_output.put_line('post Posición '||posición);
tamaño_corregido := tamaño_corregido-1;
end loop;
UTL_FILE.FCLOSE(f_out);
else
dbms_output.put_line('El fichero '||nombrearchivo||' está vacío (0 bytes).');
end if;
else
dbms_output.put_line('El archivo '||nombrearchivo||' no existe');
end if;
end;
/
an alternative version using byte by byte reading:
set serveroutput on
declare
nombreArchivo varchar2(30):='fich_fseek.txt';
--nombreArchivo varchar2(30):='caracter.txt';
--nombreArchivo varchar2(30):='vacio.txt';
f_out UTL_FILE.FILE_TYPE;
texto varchar2(100) := '';
posición pls_integer := 0;
existe boolean;
tamaño_archivo number;
tamaño_bloque number;
flag_acento boolean := false;
tamaño_corregido number;
begin
UTL_FILE.FGETATTR('TEMPORAL', nombreArchivo, existe, tamaño_archivo, tamaño_bloque);
if existe then
if tamaño_archivo > 0 then
dbms_output.put_line('Abrir el fichero '||nombrearchivo||' en modo lectura, que tiene un tamaño de '||tamaño_archivo||' bytes.');
f_out:=UTL_FILE.FOPEN('TEMPORAL',nombreArchivo,'r');
posición := UTL_FILE.FGETPOS(f_out);
tamaño_corregido := tamaño_archivo;
while posición < tamaño_corregido loop
UTL_FILE.GET_RAW(f_out, texto, 1);
if texto = 'C3' then
--dbms_output.put_line('Encontrado');
flag_acento := true; --TODO
goto CONTINUE;
end if;
if flag_acento then
dbms_output.put_line('Posición '||rpad(posición,3)||' '||texto||': '||utl_raw.cast_to_varchar2('C3'||texto));
flag_acento := false;
else
dbms_output.put_line('Posición '||rpad(posición,3)||' '||texto||': '||CHR(TO_NUMBER(texto,'xx')));
end if;
if texto = '0A' then -- caracter de sálto de línea
--exit;
tamaño_corregido := tamaño_corregido-1;
end if;
<<CONTINUE>> posición := UTL_FILE.FGETPOS(f_out);
end loop;
--dbms_output.put_line('ASDF '||CHR(TO_NUMBER('C3','xx'))||CHR(TO_NUMBER('81','xx')));
/*unión := utl_raw.cast_to_varchar2('C381');
dbms_output.put_line('ASDF '||unión );*/
UTL_FILE.FCLOSE(f_out);
else
dbms_output.put_line('El fichero '||nombrearchivo||' está vacío (0 bytes).');
end if;
else
dbms_output.put_line('El archivo '||nombrearchivo||' no existe');
end if;
end;
/

Related

Is there any way to reduce Delphi code / somehow to put other object into variable? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have
var objeto:TDateEdit; ...
If I change as TDateEdit in the code:
if UpperCase(CAMPOSnoBANCO[ii]) = UpperCase((FORMULARIO.Components[i] as TDateEdit).name )
and use this:
if UpperCase(CAMPOSnoBANCO[ii]) = UpperCase((FORMULARIO.Components[i] as objeto).name)
The code works.... but I need a change
objeto := TDBEdit;
I need a way to change this variable type to reduce a code
I will use
If (FORMULARIO.Components[i] is TDateEdit) then objeto := TDateEdit
If (FORMULARIO.Components[i] is TDBLookupComboBox) then objeto := TDBLookupComboBox
But the variable is
var objeto: TDateEdit;
How can I do it without repeating the code for each object type?
Function ValidaCampoObrigatorio(): boolean;
var i,PrimeiroCampo,ii,indexOfItem:Integer;
var MSGaglutinada,TIPO:string;
var NOMEcampo : variant ;
var objeto:TDateEdit ;
var VALIDOU:boolean;
begin
CorERRO:=RGB(255,218,185);
CorCertO:= 12582911;//$FF000005;
Result := false;
MSGaglutinada:='';
PrimeiroCampo:=-1;
tipo:='';
NOMEcampo:='';
for i := 0 to FORMULARIO.ComponentCount -1 do
begin
if (FORMULARIO.Components[i] is TDateEdit) then
begin
indexOfItem := -1;
ii:=0;
for ii := Low(CAMPOSnoBANCO) to High(CAMPOSnoBANCO) do
//LOCALIZANDO DENTRO da matriz
if UpperCase(CAMPOSnoBANCO[ii]) = UpperCase((FORMULARIO.Components[i] as TDateEdit).name ) then
begin
BREAK;
end;
VALIDOU:=True;
if EhRequerido[ansiindexstr((FORMULARIO.Components[i] as TDateEdit).name , CAMPOSnoBANCO)]=true then
begin
if((FORMULARIO.Components[i] as TDateEdit).text = '')then
begin
if PrimeiroCampo<0 then begin PrimeiroCampo:=i;TIPO:='TDateEdit' end;
MSGaglutinada := UpperCase((FORMULARIO.Components[i] as TDateEdit).Name)+' não pode ser NULO'+ #13#10+Trim(MSGaglutinada) ;
(FORMULARIO.Components[i] as TDateEdit).Color:=corERRO; VALIDOU:=false ;
end;
end;
if EhEMAIL[ansiindexstr((FORMULARIO.Components[i] as TDateEdit).name , CAMPOSnoBANCO)]=true then
begin
if ValidEmail((FORMULARIO.Components[i] as TDateEdit).text) = False then
begin
if PrimeiroCampo<0 then begin PrimeiroCampo:=i;TIPO:='TDBEdit' end;
MSGaglutinada := UpperCase((FORMULARIO.Components[i] as TDateEdit).Name)+' DEVE ser válido'+ #13#10+Trim(MSGaglutinada) ;
(FORMULARIO.Components[i] as TDateEdit).Color:=corERRO; VALIDOU:=false ;
end;
end ;
if EhData[ansiindexstr((FORMULARIO.Components[i] as TDateEdit).name , CAMPOSnoBANCO)]=true then
begin
if DataValida((FORMULARIO.Components[i] as TDateEdit).text)=false then
begin
if PrimeiroCampo<0 then begin PrimeiroCampo:=i;TIPO:='TDateEdit' end;
MSGaglutinada := UpperCase((FORMULARIO.Components[i] as TDateEdit).Name)+' DEVE uma data Válida'+ #13#10+Trim(MSGaglutinada) ;
(FORMULARIO.Components[i] as TDateEdit).Color:=corERRO; VALIDOU:=false ;
end
else
begin
if (OperadorDatamenor[ansiindexstr((FORMULARIO.Components[i] as TDateEdit).name , CAMPOSnoBANCO)] <> '') then
begin
if StrToDate(OperadorDatamenor[ansiindexstr((FORMULARIO.Components[i] as TDateEdit).name , CAMPOSnoBANCO)])<=StrToDate((FORMULARIO.Components[i] as TDateEdit).text)then
begin
if PrimeiroCampo<0 then begin PrimeiroCampo:=i;TIPO:='TDateEdit' end;
MSGaglutinada := UpperCase((FORMULARIO.Components[i] as TDateEdit).Name)+' não pode maior ou igual à '+ (OperadorDatamenor[ansiindexstr((FORMULARIO.Components[i] as TDateEdit).name , CAMPOSnoBANCO)])+#13#10+Trim(MSGaglutinada) ;
(FORMULARIO.Components[i] as TDateEdit).Color:=corERRO; VALIDOU:=false ;
end;
end;
if (OperadorDataMaior[ansiindexstr((FORMULARIO.Components[i] as TDateEdit).name , CAMPOSnoBANCO)] <> '') then
begin
if StrToDate(OperadorDatamaior[ansiindexstr((FORMULARIO.Components[i] as TDateEdit).name , CAMPOSnoBANCO)])>=StrToDate((FORMULARIO.Components[i] as TDateEdit).text)then
begin
if PrimeiroCampo<0 then begin PrimeiroCampo:=i;TIPO:='TDateEdit' end;
MSGaglutinada := UpperCase((FORMULARIO.Components[i] as TDateEdit).Name)+' não pode menor ou igual à '+ (OperadorDatamenor[ansiindexstr((FORMULARIO.Components[i] as TDateEdit).name , CAMPOSnoBANCO)])+#13#10+Trim(MSGaglutinada) ;
(FORMULARIO.Components[i] as TDateEdit).Color:=corERRO; VALIDOU:=false ;
end;
end;
end;
end ;
if VALIDOU=true then
begin
(FORMULARIO.Components[i] as TDateEdit).Color:= CorCertO;
end;
end;
if (FORMULARIO.Components[i] is TDBEdit) then
begin
indexOfItem := -1;
ii:=0;
for ii := Low(CAMPOSnoBANCO) to High(CAMPOSnoBANCO) do
//LOCALIZANDO DENTRO da matriz
if UpperCase(CAMPOSnoBANCO[ii]) = UpperCase((FORMULARIO.Components[i] as TDBEdit).name ) then
begin
BREAK;
end;
VALIDOU:=True;
if EhRequerido[ansiindexstr((FORMULARIO.Components[i] as TDBEdit).name , CAMPOSnoBANCO)]=true then
begin
if((FORMULARIO.Components[i] as TDBEdit).field.AsString = '')then
begin
if PrimeiroCampo<0 then begin PrimeiroCampo:=i;TIPO:='TDBEdit' end;
MSGaglutinada := UpperCase((FORMULARIO.Components[i] as TDBEdit).Name)+' não pode ser NULO'+ #13#10+Trim(MSGaglutinada) ;
(FORMULARIO.Components[i] as TDBEdit).Color:=corERRO; VALIDOU:=false ;
end;
end;
if EhEMAIL[ansiindexstr((FORMULARIO.Components[i] as TDBEdit).name , CAMPOSnoBANCO)]=true then
begin
if ValidEmail((FORMULARIO.Components[i] as TDBEdit).text) = False then
begin
if PrimeiroCampo<0 then begin PrimeiroCampo:=i;TIPO:='TDBEdit' end;
MSGaglutinada := UpperCase((FORMULARIO.Components[i] as TDBEdit).Name)+' DEVE ser válido'+ #13#10+Trim(MSGaglutinada) ;
(FORMULARIO.Components[i] as TDBEdit).Color:=corERRO; VALIDOU:=false ;
end;
end ;
if EhData[ansiindexstr((FORMULARIO.Components[i] as TDBEdit).name , CAMPOSnoBANCO)]=true then
begin
if DataValida((FORMULARIO.Components[i] as TDBEdit).text)=false then
begin
if PrimeiroCampo<0 then begin PrimeiroCampo:=i;TIPO:='TDBEdit' end;
MSGaglutinada := UpperCase((FORMULARIO.Components[i] as TDBEdit).Name)+' DEVE uma data Válida'+ #13#10+Trim(MSGaglutinada) ;
(FORMULARIO.Components[i] as TDBEdit).Color:=corERRO; VALIDOU:=false ;
end
else
begin
if (OperadorDatamenor[ansiindexstr((FORMULARIO.Components[i] as TDBEdit).name , CAMPOSnoBANCO)] <> '') then
begin
if StrToDate(OperadorDatamenor[ansiindexstr((FORMULARIO.Components[i] as TDBEdit).name , CAMPOSnoBANCO)])<=StrToDate((FORMULARIO.Components[i] as TDBEdit).text)then
begin
if PrimeiroCampo<0 then begin PrimeiroCampo:=i;TIPO:='TDBEdit' end;
MSGaglutinada := UpperCase((FORMULARIO.Components[i] as TDBEdit).Name)+' não pode maior ou igual à '+ (OperadorDatamenor[ansiindexstr((FORMULARIO.Components[i] as TDBEdit).name , CAMPOSnoBANCO)])+#13#10+Trim(MSGaglutinada) ;
(FORMULARIO.Components[i] as TDBEdit).Color:=corERRO; VALIDOU:=false ;
end;
end;
if (OperadorDataMaior[ansiindexstr((FORMULARIO.Components[i] as TDBEdit).name , CAMPOSnoBANCO)] <> '') then
begin
if StrToDate(OperadorDatamaior[ansiindexstr((FORMULARIO.Components[i] as TDBEdit).name , CAMPOSnoBANCO)])>=StrToDate((FORMULARIO.Components[i] as TDBEdit).text)then
begin
if PrimeiroCampo<0 then begin PrimeiroCampo:=i;TIPO:='TDBEdit' end;
MSGaglutinada := UpperCase((FORMULARIO.Components[i] as TDBEdit).Name)+' não pode menor ou igual à '+ (OperadorDatamenor[ansiindexstr((FORMULARIO.Components[i] as TDBEdit).name , CAMPOSnoBANCO)])+#13#10+Trim(MSGaglutinada) ;
(FORMULARIO.Components[i] as TDBEdit).Color:=corERRO; VALIDOU:=false ;
end;
end;
end;
end ;
if VALIDOU=true then
begin
(FORMULARIO.Components[i] as TDBEdit).Color:= CorCertO;
end;
end;
if (FORMULARIO.Components[i] is TDBLookupComboBox) then
begin
indexOfItem := -1;
ii:=0;
for ii := Low(CAMPOSnoBANCO) to High(CAMPOSnoBANCO) do
//LOCALIZANDO DENTRO da matriz
if UpperCase(CAMPOSnoBANCO[ii]) = UpperCase((FORMULARIO.Components[i] as TDBLookupComboBox).name ) then
begin
BREAK;
end;
VALIDOU:=True;
if EhRequerido[ansiindexstr((FORMULARIO.Components[i] as TDBLookupComboBox).name , CAMPOSnoBANCO)]=true then
begin
if((FORMULARIO.Components[i] as TDBLookupComboBox).field.AsString = '')then
begin
if PrimeiroCampo<0 then begin PrimeiroCampo:=i;TIPO:='TDBLookupComboBox' end;
MSGaglutinada := UpperCase((FORMULARIO.Components[i] as TDBLookupComboBox).Name)+' não pode ser NULO'+ #13#10+Trim(MSGaglutinada) ;
(FORMULARIO.Components[i] as TDBLookupComboBox).Color:=corERRO; VALIDOU:=false ;
end;
end;
if EhEMAIL[ansiindexstr((FORMULARIO.Components[i] as TDBLookupComboBox).name , CAMPOSnoBANCO)]=true then
begin
if ValidEmail((FORMULARIO.Components[i] as TDBLookupComboBox).text) = False then
begin
if PrimeiroCampo<0 then begin PrimeiroCampo:=i;TIPO:='TDBLookupComboBox' end;
MSGaglutinada := UpperCase((FORMULARIO.Components[i] as TDBLookupComboBox).Name)+' DEVE ser válido'+ #13#10+Trim(MSGaglutinada) ;
(FORMULARIO.Components[i] as TDBLookupComboBox).Color:=corERRO; VALIDOU:=false ;
end;
end ;
if EhData[ansiindexstr((FORMULARIO.Components[i] as TDBLookupComboBox).name , CAMPOSnoBANCO)]=true then
begin
if DataValida((FORMULARIO.Components[i] as TDBLookupComboBox).text)=false then
begin
if PrimeiroCampo<0 then begin PrimeiroCampo:=i;TIPO:='TDBLookupComboBox' end;
MSGaglutinada := UpperCase((FORMULARIO.Components[i] as TDBLookupComboBox).Name)+' DEVE uma data Válida'+ #13#10+Trim(MSGaglutinada) ;
(FORMULARIO.Components[i] as TDBLookupComboBox).Color:=corERRO; VALIDOU:=false ;
end
else
begin
if (OperadorDatamenor[ansiindexstr((FORMULARIO.Components[i] as TDBLookupComboBox).name , CAMPOSnoBANCO)] <> '') then
begin
if StrToDate(OperadorDatamenor[ansiindexstr((FORMULARIO.Components[i] as TDBLookupComboBox).name , CAMPOSnoBANCO)])<=StrToDate((FORMULARIO.Components[i] as TDBLookupComboBox).text)then
begin
if PrimeiroCampo<0 then begin PrimeiroCampo:=i;TIPO:='TDBLookupComboBox' end;
MSGaglutinada := UpperCase((FORMULARIO.Components[i] as TDBLookupComboBox).Name)+' não pode maior ou igual à '+ (OperadorDatamenor[ansiindexstr((FORMULARIO.Components[i] as TDBLookupComboBox).name , CAMPOSnoBANCO)])+#13#10+Trim(MSGaglutinada) ;
(FORMULARIO.Components[i] as TDBLookupComboBox).Color:=corERRO; VALIDOU:=false ;
end;
end;
if (OperadorDataMaior[ansiindexstr((FORMULARIO.Components[i] as TDBLookupComboBox).name , CAMPOSnoBANCO)] <> '') then
begin
if StrToDate(OperadorDatamaior[ansiindexstr((FORMULARIO.Components[i] as TDBLookupComboBox).name , CAMPOSnoBANCO)])>=StrToDate((FORMULARIO.Components[i] as TDBLookupComboBox).text)then
begin
if PrimeiroCampo<0 then begin PrimeiroCampo:=i;TIPO:='TDBLookupComboBox' end;
MSGaglutinada := UpperCase((FORMULARIO.Components[i] as TDBLookupComboBox).Name)+' não pode menor ou igual à '+ (OperadorDatamenor[ansiindexstr((FORMULARIO.Components[i] as TDBLookupComboBox).name , CAMPOSnoBANCO)])+#13#10+Trim(MSGaglutinada) ;
(FORMULARIO.Components[i] as TDBLookupComboBox).Color:=corERRO; VALIDOU:=false ;
end;
end;
end;
end ;
if VALIDOU=true then
begin
(FORMULARIO.Components[i] as TDBLookupComboBox).Color:= CorCertO;
end;
end;
if (FORMULARIO.Components[i] is TDBDateEdit) then
begin
indexOfItem := -1;
ii:=0;
for ii := Low(CAMPOSnoBANCO) to High(CAMPOSnoBANCO) do
//LOCALIZANDO DENTRO da matriz
if UpperCase(CAMPOSnoBANCO[ii]) = UpperCase((FORMULARIO.Components[i] as TDBDateEdit).name ) then
begin
BREAK;
end;
VALIDOU:=True;
if EhRequerido[ansiindexstr((FORMULARIO.Components[i] as TDBDateEdit).name , CAMPOSnoBANCO)]=true then
begin
if((FORMULARIO.Components[i] as TDBDateEdit).text = '')then
begin
if PrimeiroCampo<0 then begin PrimeiroCampo:=i;TIPO:='TDBDateEdit' end;
MSGaglutinada := UpperCase((FORMULARIO.Components[i] as TDBDateEdit).Name)+' não pode ser NULO'+ #13#10+Trim(MSGaglutinada) ;
(FORMULARIO.Components[i] as TDBDateEdit).Color:=corERRO; VALIDOU:=false ;
end;
end;
if EhEMAIL[ansiindexstr((FORMULARIO.Components[i] as TDBDateEdit).name , CAMPOSnoBANCO)]=true then
begin
if ValidEmail((FORMULARIO.Components[i] as TDBDateEdit).text) = False then
begin
if PrimeiroCampo<0 then begin PrimeiroCampo:=i;TIPO:='TDBDateEdit' end;
MSGaglutinada := UpperCase((FORMULARIO.Components[i] as TDBDateEdit).Name)+' DEVE ser válido'+ #13#10+Trim(MSGaglutinada) ;
(FORMULARIO.Components[i] as TDBDateEdit).Color:=corERRO; VALIDOU:=false ;
end;
end ;
if EhData[ansiindexstr((FORMULARIO.Components[i] as TDBDateEdit).name , CAMPOSnoBANCO)]=true then
begin
if DataValida((FORMULARIO.Components[i] as TDBDateEdit).text)=false then
begin
if PrimeiroCampo<0 then begin PrimeiroCampo:=i;TIPO:='TDBDateEdit' end;
MSGaglutinada := UpperCase((FORMULARIO.Components[i] as TDBDateEdit).Name)+' DEVE uma data Válida'+ #13#10+Trim(MSGaglutinada) ;
(FORMULARIO.Components[i] as TDBDateEdit).Color:=corERRO; VALIDOU:=false ;
end
else
begin
if (OperadorDatamenor[ansiindexstr((FORMULARIO.Components[i] as TDBDateEdit).name , CAMPOSnoBANCO)] <> '') then
begin
if StrToDate(OperadorDatamenor[ansiindexstr((FORMULARIO.Components[i] as TDBDateEdit).name , CAMPOSnoBANCO)])<=StrToDate((FORMULARIO.Components[i] as TDBDateEdit).text)then
begin
if PrimeiroCampo<0 then begin PrimeiroCampo:=i;TIPO:='TDBDateEdit' end;
MSGaglutinada := UpperCase((FORMULARIO.Components[i] as TDBDateEdit).Name)+' não pode maior ou igual à '+ (OperadorDatamenor[ansiindexstr((FORMULARIO.Components[i] as TDBDateEdit).name , CAMPOSnoBANCO)])+#13#10+Trim(MSGaglutinada) ;
(FORMULARIO.Components[i] as TDBDateEdit).Color:=corERRO; VALIDOU:=false ;
end;
end;
if (OperadorDataMaior[ansiindexstr((FORMULARIO.Components[i] as TDBDateEdit).name , CAMPOSnoBANCO)] <> '') then
begin
if StrToDate(OperadorDatamaior[ansiindexstr((FORMULARIO.Components[i] as TDBDateEdit).name , CAMPOSnoBANCO)])>=StrToDate((FORMULARIO.Components[i] as TDBDateEdit).text)then
begin
if PrimeiroCampo<0 then begin PrimeiroCampo:=i;TIPO:='TDBDateEdit' end;
MSGaglutinada := UpperCase((FORMULARIO.Components[i] as TDBDateEdit).Name)+' não pode menor ou igual à '+ (OperadorDatamenor[ansiindexstr((FORMULARIO.Components[i] as TDBDateEdit).name , CAMPOSnoBANCO)])+#13#10+Trim(MSGaglutinada) ;
(FORMULARIO.Components[i] as TDBDateEdit).Color:=corERRO; VALIDOU:=false ;
end;
end;
end;
end ;
if VALIDOU=true then
begin
(FORMULARIO.Components[i] as TDBDateEdit).Color:= CorCertO;
end;
end;
//////////////////////////////////////////////////////////////
//TMaskEdit
if (FORMULARIO.Components[i] is TMaskEdit) then
begin
indexOfItem := -1;
ii:=0;
for ii := Low(CAMPOSnoBANCO) to High(CAMPOSnoBANCO) do
//LOCALIZANDO DENTRO da matriz
if UpperCase(CAMPOSnoBANCO[ii]) = UpperCase((FORMULARIO.Components[i] as TMaskEdit).name ) then
begin
BREAK;
end;
VALIDOU:=True;
if EhRequerido[ansiindexstr((FORMULARIO.Components[i] as TMaskEdit).name , CAMPOSnoBANCO)]=true then
begin
if((FORMULARIO.Components[i] as TMaskEdit).text = '')then
begin
if PrimeiroCampo<0 then begin PrimeiroCampo:=i;TIPO:='TDBDateEdit' end;
MSGaglutinada := UpperCase((FORMULARIO.Components[i] as TMaskEdit).Name)+' não pode ser NULO'+ #13#10+Trim(MSGaglutinada) ;
(FORMULARIO.Components[i] as TMaskEdit).Color:=corERRO; VALIDOU:=false ;
end;
end;
if EhEMAIL[ansiindexstr((FORMULARIO.Components[i] as TMaskEdit).name , CAMPOSnoBANCO)]=true then
begin
if ValidEmail((FORMULARIO.Components[i] as TMaskEdit).text) = False then
begin
if PrimeiroCampo<0 then begin PrimeiroCampo:=i;TIPO:='TMaskEdit' end;
MSGaglutinada := UpperCase((FORMULARIO.Components[i] as TMaskEdit).Name)+' DEVE ser válido'+ #13#10+Trim(MSGaglutinada) ;
(FORMULARIO.Components[i] as TMaskEdit).Color:=corERRO; VALIDOU:=false ;
end;
end ;
if EhData[ansiindexstr((FORMULARIO.Components[i] as TMaskEdit).name , CAMPOSnoBANCO)]=true then
begin
if DataValida((FORMULARIO.Components[i] as TMaskEdit).text)=false then
begin
if PrimeiroCampo<0 then begin PrimeiroCampo:=i;TIPO:='TMaskEdit' end;
MSGaglutinada := UpperCase((FORMULARIO.Components[i] as TMaskEdit).Name)+' DEVE uma data Válida'+ #13#10+Trim(MSGaglutinada) ;
(FORMULARIO.Components[i] as TMaskEdit).Color:=corERRO; VALIDOU:=false ;
end
else
begin
if (OperadorDatamenor[ansiindexstr((FORMULARIO.Components[i] as TMaskEdit).name , CAMPOSnoBANCO)] <> '') then
begin
if StrToDate(OperadorDatamenor[ansiindexstr((FORMULARIO.Components[i] as TMaskEdit).name , CAMPOSnoBANCO)])<=StrToDate((FORMULARIO.Components[i] as TMaskEdit).text)then
begin
if PrimeiroCampo<0 then begin PrimeiroCampo:=i;TIPO:='TMaskEdit' end;
MSGaglutinada := UpperCase((FORMULARIO.Components[i] as TMaskEdit).Name)+' não pode maior ou igual à '+ (OperadorDatamenor[ansiindexstr((FORMULARIO.Components[i] as TMaskEdit).name , CAMPOSnoBANCO)])+#13#10+Trim(MSGaglutinada) ;
(FORMULARIO.Components[i] as TMaskEdit).Color:=corERRO; VALIDOU:=false ;
end;
end;
if (OperadorDataMaior[ansiindexstr((FORMULARIO.Components[i] as TMaskEdit).name , CAMPOSnoBANCO)] <> '') then
begin
if StrToDate(OperadorDatamaior[ansiindexstr((FORMULARIO.Components[i] as TMaskEdit).name , CAMPOSnoBANCO)])>=StrToDate((FORMULARIO.Components[i] as TMaskEdit).text)then
begin
if PrimeiroCampo<0 then begin PrimeiroCampo:=i;TIPO:='TMaskEdit' end;
MSGaglutinada := UpperCase((FORMULARIO.Components[i] as TMaskEdit).Name)+' não pode menor ou igual à '+ (OperadorDatamenor[ansiindexstr((FORMULARIO.Components[i] as TMaskEdit).name , CAMPOSnoBANCO)])+#13#10+Trim(MSGaglutinada) ;
(FORMULARIO.Components[i] as TMaskEdit).Color:=corERRO; VALIDOU:=false ;
end;
end;
end;
end ;
if VALIDOU=true then
begin
(FORMULARIO.Components[i] as TMaskEdit).Color:= CorCertO;
end;
end;
end;
///////////////////////////////////////////////////////////
if MSGaglutinada <>'' then
begin
MSGaglutinada:=ReplaceAll(MSGaglutinada,CAMPOSnoBANCO,CAMPOSexibirCOMO,True) ;
MessageDlg('O(s) campo(s): '+#13#10+MSGaglutinada , mtWarning, [mbok],0 ) ;
if TIPO='TDBEdit' then
begin
(FORMULARIO.Components[PrimeiroCampo] as TDBEdit).SetFocus;
end
else if TIPO='TDBLookupComboBox' then
begin
(FORMULARIO.Components[PrimeiroCampo] as TDBLookupComboBox).SetFocus
end
else if TIPO='TMaskEdit' then begin
(FORMULARIO.Components[PrimeiroCampo] as TMaskEdit).SetFocus
end
else if TIPO='TDBDateEdit' then begin
(FORMULARIO.Components[PrimeiroCampo] as TDBDateEdit).SetFocus
end
else if TIPO='TDateEdit' then begin
(FORMULARIO.Components[PrimeiroCampo] as TDateEdit).SetFocus
end;
Abort;
end;
result := true;
end;
function ReplaceAll(const Subject: String;
const OldPatterns, NewPatterns: array of String;
IgnoreCase: Boolean): String;
var
ReplaceFlags: TReplaceFlags;
NewPattern: String;
I: Integer;
begin
ReplaceFlags := [rfReplaceAll];
if IgnoreCase then
Include(ReplaceFlags, rfIgnoreCase);
Result := Subject;
for I := Low(OldPatterns) to High(OldPatterns) do
begin
if I <= High(NewPatterns) then
NewPattern := NewPatterns[I]
else
NewPattern := '';
Result := StringReplace(Result, OldPatterns[I], NewPattern, ReplaceFlags);
end;
end;
function ValidEmail(email: string): boolean;
var
RegEx: TRegEx;
begin
RegEx := TRegex.Create('^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]*[a-zA-Z0-9]+$');
Result := RegEx.Match(email).Success;
end;
function DataValida(StrD: string): Boolean;
var
DataDigitadaNoEdit:TDateTime;
{Testa se uma data é valida}
begin
Result := true;
try
//ShowMessage((StrD));
if (StrD<>' / / ') and (StrD <> ' / / ') and (StrD <> null) and (StrD<>'')then
begin
TryStrToDate(StrD,DataDigitadaNoEdit) ;
end
else
Begin
Result:=False;
// Abort;
end;
except
on EConvertError do Result:=False;
end;
end;
function NumeroValido(StrD: string): Boolean;
{Testa se uma data é valida}
begin
Result := true;
try
StrToDate(StrD);
except
on EConvertError do Result:=False;
end;
end;
It is possible to store a class type in a variable at runtime. However, you can't perform type-casts using that variable. Casts are evaluated at compile-time and must use a concrete type to cast to.
Besides, you don't really need those kind of type-casts in this situation at all. For starters, most of your as casts are performing redundant type-checks that you already performed with is. But more importantly, Name is a public property of TComponent so you don't need a type-cast at all to access it, eg:
if SameText(CAMPOSnoBANCO[ii], FORMULARIO.Components[i].Name) then
For other properties that are not public/published but are protected in a base class, like Text and Color are, you can use an accessor class to reach them, or you can use RTTI instead.
The code shown is needlessly repetitive and verbose, there are a lot of things that can be simplified in it.
Try something more like this:
type
TControlAccess = class(TControl)
end;
function ValidaCampoObrigatorio(): Boolean;
var
i, ii: Integer;
MSGaglutinada: String;
VALIDOU: Boolean;
Comp: TComponent;
Ctrl, PrimeiroCampo: TWinControl;
function GetControlText(ACtrl: TControl): String;
begin
Result := TControlAccess(ACtrl).Text;
// alternatively:
// Result := TypInfo.GetStrProp(ACtrl, 'Text');
end;
procedure SetControlColor(ACtrl: TControl; AValue: TColor);
begin
TControlAccess(ACtrl).Color := AValue;
// alternatively:
// TypInfo.SetOrdProp(ACtrl, 'Color', AValue);
end;
begin
CorERRO := RGB(255, 218, 185);
CorCertO := 12582911;//$FF000005;
Result := False;
MSGaglutinada := '';
PrimeiroCampo := nil;
for i := 0 to FORMULARIO.ComponentCount - 1 do
begin
Comp := FORMULARIO.Components[i];
if not (Comp is TWinControl) then Continue;
Ctrl := TWinControl(Comp);
//LOCALIZANDO DENTRO da matriz
ii := AnsiIndexText(Ctrl.Name, CAMPOSnoBANCO);
VALIDOU := True;
if EhRequerido[ii] then
begin
if (GetControlText(Ctrl) = '') then
begin
MSGaglutinada := UpperCase(Ctrl.Name) + ' não pode ser NULO' + #13#10 + Trim(MSGaglutinada);
VALIDOU := False;
end;
end;
if EhEMAIL[ii] then
begin
if not ValidEmail(GetControlText(Ctrl)) then
begin
MSGaglutinada := UpperCase(Ctrl.Name) + ' DEVE ser válido' + #13#10 + Trim(MSGaglutinada);
VALIDOU := False;
end;
end;
if EhData[ii] then
begin
if not DataValida(GetControlText(Ctrl)) then
begin
MSGaglutinada := UpperCase(Ctrl.Name) + ' DEVE uma data Válida' + #13#10 + Trim(MSGaglutinada);
VALIDOU := False;
end
else
begin
if (OperadorDatamenor[ii] <> '') then
begin
if StrToDate(OperadorDatamenor[ii]) <= StrToDate(GetControlText(Ctrl)) then
begin
MSGaglutinada := UpperCase(Ctrl.Name) + ' não pode maior ou igual à ' + OperadorDatamenor[ii] + #13#10 + Trim(MSGaglutinada);
VALIDOU := False;
end;
end;
if (OperadorDataMaior[ii] <> '') then
begin
if StrToDate(OperadorDatamaior[ii]) >= StrToDate(GetControlText(Ctrl)) then
begin
MSGaglutinada := UpperCase(Ctrl.Name) + ' não pode menor ou igual à ' + OperadorDatamenor[ii] + #13#10 + Trim(MSGaglutinada);
VALIDOU := False;
end;
end;
end;
end;
if not VALIDOU then
begin
if PrimeiroCampo = nil then PrimeiroCampo := Ctrl;
SetControlColor(Ctrl, corERRO);
end
else
SetControlColor(Ctrl, CorCertO);
end;
///////////////////////////////////////////////////////////
if MSGaglutinada <> '' then
begin
MSGaglutinada := ReplaceAll(MSGaglutinada, CAMPOSnoBANCO, CAMPOSexibirCOMO, True);
MessageDlg('O(s) campo(s): ' + #13#10 + MSGaglutinada, mtWarning, [mbok], 0);
PrimeiroCampo.SetFocus;
Abort;
end;
Result := True;
end;

PL/pgSQL ERROR: too many parameters specified for RAISE

I'm trying to put more than 2 parameters into a raise notice but i can't ¿How can i do it?
CREATE OR REPLACE FUNCTION TABLA_MULT(numeric) RETURNS void AS '
DECLARE
texto1 TEXT := ''multiplicado por '';
texto2 TEXT := '' es igual a '';
BEGIN
RAISE NOTICE ''TABLA DE MULTIPLICAR DEL %'',$1;
RAISE NOTICE ''=========================='';
FOR i IN 1..10 LOOP
DECLARE result numeric := ($1*i);
BEGIN
RAISE NOTICE ''El número %'',i,texto1,$1,texto2,result;
END;
END LOOP;
END; ' LANGUAGE 'plpgsql';
As documented in the manual you need one % for each parameter that should be replaced:
The number of arguments must match the number of % placeholders in the format string, or an error is raised during the compilation of the function.
So you need:
RAISE NOTICE 'El número % % % % %',i,texto1,$1,texto2,result;
Not specifically related to your question but you may want to investigate Postgres Dollar-Quoted String Constants. This relieves you from having to double quote within the function body. Thus your function (as initially posted by you becomes):
CREATE OR REPLACE FUNCTION TABLA_MULT(numeric) RETURNS void AS $$
DECLARE
texto1 TEXT := 'multiplicado por ';
texto2 TEXT := ' es igual a ';
BEGIN
RAISE NOTICE 'TABLA DE MULTIPLICAR DEL %',$1;
RAISE NOTICE '==========================';
FOR i IN 1..10 LOOP
DECLARE result numeric := ($1*i);
BEGIN
RAISE NOTICE 'El número %',i,texto1,$1,texto2,result;
END;
END LOOP;
END; $$ LANGUAGE 'plpgsql';
It would also be self beneficial to systematically indent your code.

syntax error at or near "CURSOR"

i'm getting this error on my code and I have no idea what might be. I just got started with PL/pgSQL. Sorry if it is a stupid question.
ERROR: syntax error at or near "CURSOR"
LINE 9: CURSOR reg_notif IS SELECT * FROM sv_notificacao;
^
********** Error **********
My Code:
CREATE OR REPLACE FUNCTION checa_multa()
RETURNS INT AS
$$
DECLARE
CURSOR reg_notif IS SELECT * FROM sv_notificacao;
BEGIN
OPEN reg_notif;
LOOP
FETCH reg_notif INTO rn_linha
IF rn_linha.placa_veiculo IN (SELECT sv_veiculo.placa FROM sv_veiculo) --A placa informada na notificação deverá existir no cadastro de veículos;
AND rn_linha.nro_cnh IN (SELECT sv_condutor.nro_cnh FROM sv_condutor) --O número da CNH deverá ser existir no cadastro de condu
AND rn_linha.data_hora IS NOT NULL --A dtaa informada deve estar preenchida
AND rn_linha.data_hora <= CURRENT_DATE -- A nada informada não deverá ser futura
AND rn_linha.velocidade_inf> 0 --velocidade apurada superior a zero
AND rn_linha.velocidade_via > 0 --valocidade da via superior a zero
THEN
CREATE TABLE sv_infracao
(
cod_infracao SERIAL PRIMARY KEY,
cod_cpf BIGINT,
cnh_condutor VARCHAR(11),
placa_veiculo VARCHAR(7),
data_hora TIMESTAMP DEFAULT NULL,
velocidade_inf INT DEFAULT NULL,
velocidade_via INT DEFAULT NULL,
CONSTRAINT sv_infracao_sv_condutor FOREIGN KEY (cnh_condutor) REFERENCES sv_condutor (nro_cnh),
CONSTRAINT sv_infracao_sv_veiculo FOREIGN KEY (placa_veiculo) REFERENCES sv_veiculo (placa)
);
INSERT INTO sv_infracao (cod_cpf, cnh_condutor, placa_veiculo, data_hora, velocidade_inf, velocidade_via)
VALUES rn_linha.cod_cpf, rn_linha.cnh_condutor, rn_linha.placa_veiculo, rn_linha.data_hora, rn_linha.velocidade_inf, rn_linha.velocidade_via) ;
ELSE
CREATE TABLE sv_log_erro
(
cod_log SERIAL PRIMARY KEY,
notificacao INT,
descricao_problema TEXT,
CONSTRAINT sv_log_erro_sv_notificacao FOREIGN KEY (notificacao) REFERENCES sv_notificacao (cod_notif)
);
--Placa nao esta cadastrada no cadaastro de veiculos
IF placa NOT IN (SELECT sv_veiculo.placa FROM sv_veiculo) THEN
INSERT INTO sv_log_erro (notificacao, descricao_problema)
VALUES (rn_linha.cod_notif, 'A Placa: ' || rn_linha.placa_veiculo || ' não foi localizada');
END IF;
--Condutor não localizado
IF cnh NOT IN (SELECT sv_condutor.nro_cnh FROM sv_condutor) THEN
INSERT INTO sv_log_erro (notificacao, descricao_problema)
VALUES (rn_linha.cod_notif, 'A CNH: ' || rn_linha.nro_cnh || ' do Condutor informado não foi localizada');
END IF;
--Data não informada
IF data IS NULL THEN
INSERT INTO sv_log_erro (notificacao, descricao_problema)
VALUES (rn_linha.cod_notif, 'Data não preenchida');
END IF;
--Data do futuro
IF data > CURRENT_DATE THEN
INSERT INTO sv_log_erro (notificacao, descricao_problema)
VALUES (rn_linha.cod_notif, 'Data de notificação informada é do futuro '||data);
END IF;
--Velocidade nao informada
IF velocidadeInf <= 0 THEN
INSERT INTO sv_log_erro (notificacao, descricao_problema)
VALUES (rn_linha.cod_notif, 'Velocidade apurada do veiculo '|| rn_linha.placa_veiculo ||' não informada');
END IF;
--Velocidade nao informada
IF velocidadeVia <= 0 THEN
INSERT INTO sv_log_erro (notificacao, descricao_problema)
VALUES (rn_linha.cod_notif, 'Velocidade da via do veículo '|| placarn_linha.placa_veiculo ||' não informada');
END IF;
END IF;
END LOOP;
CLOSE reg_notif;
RETURN retorno;
END;
$$ LANGUAGE plpgsql;
SELECT checa_multa()
Try changing few things like:
DECLARE CURSOR reg_notif FOR SELECT Field1, Field2 FROM sv_notificacao;
Using FOR instead of IS
Don't use * in SELECT list because we are fetching CURSOR value in single field i.e. "rn_linha" in our case. As * can return more then 1 fields which do not match with FETCH values.
Let use now if issue persist after changes.

Unknown identifier and wpSelectDir

I have an error that's occuring during the compliation of my Inno Setup script.
Unknown identifier 'PathOfDir2'
I know I can set var PathOfDir2: String; but i don't know where and if it will receive the value from my wpSelectDir.
Dooes anyone know what's going wrong?
[code]
// Variables Globales
var
TimeZone: String;
type
SERVICE_STATUS = record
dwServiceType : cardinal;
dwCurrentState : cardinal;
dwControlsAccepted : cardinal;
dwWin32ExitCode : cardinal;
dwServiceSpecificExitCode : cardinal;
dwCheckPoint : cardinal;
dwWaitHint : cardinal;
end;
HANDLE = cardinal;
const
SERVICE_QUERY_CONFIG = $1;
SERVICE_CHANGE_CONFIG = $2;
SERVICE_QUERY_STATUS = $4;
SERVICE_START = $10;
SERVICE_STOP = $20;
SERVICE_ALL_ACCESS = $f01ff;
SC_MANAGER_ALL_ACCESS = $f003f;
SERVICE_WIN32_OWN_PROCESS = $10;
SERVICE_WIN32_SHARE_PROCESS = $20;
SERVICE_WIN32 = $30;
SERVICE_INTERACTIVE_PROCESS = $100;
SERVICE_BOOT_START = $0;
SERVICE_SYSTEM_START = $1;
SERVICE_AUTO_START = $2;
SERVICE_DEMAND_START = $3;
SERVICE_DISABLED = $4;
SERVICE_DELETE = $10000;
SERVICE_CONTROL_STOP = $1;
SERVICE_CONTROL_PAUSE = $2;
SERVICE_CONTROL_CONTINUE = $3;
SERVICE_CONTROL_INTERROGATE = $4;
SERVICE_STOPPED = $1;
SERVICE_START_PENDING = $2;
SERVICE_STOP_PENDING = $3;
SERVICE_RUNNING = $4;
SERVICE_CONTINUE_PENDING = $5;
SERVICE_PAUSE_PENDING = $6;
SERVICE_PAUSED = $7;
// #######################################################################################
// nt based service utilities
// #######################################################################################
function OpenSCManager(lpMachineName, lpDatabaseName: string; dwDesiredAccess :cardinal): HANDLE;
external 'OpenSCManagerA#advapi32.dll stdcall';
function OpenService(hSCManager :HANDLE;lpServiceName: string; dwDesiredAccess :cardinal): HANDLE;
external 'OpenServiceA#advapi32.dll stdcall';
function CloseServiceHandle(hSCObject :HANDLE): boolean;
external 'CloseServiceHandle#advapi32.dll stdcall';
function CreateService(hSCManager :HANDLE;lpServiceName, lpDisplayName: string;dwDesiredAccess,dwServiceType,dwStartType,dwErrorControl: cardinal;lpBinaryPathName,lpLoadOrderGroup: String; lpdwTagId : cardinal;lpDependencies,lpServiceStartName,lpPassword :string): cardinal;
external 'CreateServiceA#advapi32.dll stdcall';
function DeleteService(hService :HANDLE): boolean;
external 'DeleteService#advapi32.dll stdcall';
function StartNTService(hService :HANDLE;dwNumServiceArgs : cardinal;lpServiceArgVectors : cardinal) : boolean;
external 'StartServiceA#advapi32.dll stdcall';
function ControlService(hService :HANDLE; dwControl :cardinal;var ServiceStatus :SERVICE_STATUS) : boolean;
external 'ControlService#advapi32.dll stdcall';
function QueryServiceStatus(hService :HANDLE;var ServiceStatus :SERVICE_STATUS) : boolean;
external 'QueryServiceStatus#advapi32.dll stdcall';
function QueryServiceStatusEx(hService :HANDLE;ServiceStatus :SERVICE_STATUS) : boolean;
external 'QueryServiceStatus#advapi32.dll stdcall';
function OpenServiceManager() : HANDLE;
begin
if UsingWinNT() = true then
begin
Result := OpenSCManager('','ServicesActive',SC_MANAGER_ALL_ACCESS);
if Result = 0 then
MsgBox('the servicemanager is not available', mbError, MB_OK)
end
else
begin
MsgBox('only nt based systems support services', mbError, MB_OK)
Result := 0;
end
end;
function IsServiceInstalled(ServiceName: string) : boolean;
var
hSCM : HANDLE;
hService: HANDLE;
begin
hSCM := OpenServiceManager();
Result := false;
if hSCM <> 0 then begin
hService := OpenService(hSCM,ServiceName,SERVICE_QUERY_CONFIG);
if hService <> 0 then begin
Result := true;
CloseServiceHandle(hService)
end;
CloseServiceHandle(hSCM)
end
end;
function InstallService(FileName, ServiceName, DisplayName, Description : string;ServiceType,StartType :cardinal) : boolean;
var
hSCM : HANDLE;
hService: HANDLE;
begin
hSCM := OpenServiceManager();
Result := false;
if hSCM <> 0 then begin
hService := CreateService(hSCM,ServiceName,DisplayName,SERVICE_ALL_ACCESS,ServiceType,StartType,0,FileName,'',0,'','','');
if hService <> 0 then begin
Result := true;
// Win2K & WinXP supports aditional description text for services
if Description<> '' then
RegWriteStringValue(HKLM,'System\CurrentControlSet\Services' + ServiceName,'Description',Description);
CloseServiceHandle(hService)
end;
CloseServiceHandle(hSCM)
end
end;
function RemoveService(ServiceName: string) : boolean;
var
hSCM : HANDLE;
hService: HANDLE;
begin
hSCM := OpenServiceManager();
Result := false;
if hSCM <> 0 then begin
hService := OpenService(hSCM,ServiceName,SERVICE_DELETE);
if hService <> 0 then begin
Result := DeleteService(hService);
CloseServiceHandle(hService)
end;
CloseServiceHandle(hSCM)
end
end;
function StartService(ServiceName: string) : boolean;
var
hSCM : HANDLE;
hService: HANDLE;
begin
hSCM := OpenServiceManager();
Result := false;
if hSCM <> 0 then begin
hService := OpenService(hSCM,ServiceName,SERVICE_START);
if hService <> 0 then begin
Result := StartNTService(hService,0,0);
CloseServiceHandle(hService)
end;
CloseServiceHandle(hSCM)
end;
end;
function StopService(ServiceName: string) : boolean;
var
hSCM : HANDLE;
hService: HANDLE;
Status : SERVICE_STATUS;
begin
hSCM := OpenServiceManager();
Result := false;
if hSCM <> 0 then begin
hService := OpenService(hSCM,ServiceName,SERVICE_STOP);
if hService <> 0 then begin
Result := ControlService(hService,SERVICE_CONTROL_STOP,Status);
CloseServiceHandle(hService)
end;
CloseServiceHandle(hSCM)
end;
end;
function IsServiceRunning(ServiceName: string) : boolean;
var
hSCM : HANDLE;
hService: HANDLE;
Status : SERVICE_STATUS;
begin
hSCM := OpenServiceManager();
Result := false;
if hSCM <> 0 then begin
hService := OpenService(hSCM,ServiceName,SERVICE_QUERY_STATUS);
if hService <> 0 then begin
if QueryServiceStatus(hService,Status) then begin
Result :=(Status.dwCurrentState = SERVICE_RUNNING)
end;
CloseServiceHandle(hService)
end;
CloseServiceHandle(hSCM)
end
end;
// #######################################################################################
// create an entry in the services file
// #######################################################################################
function SetupService(service, port, comment: string) : boolean;
var
filename : string;
s : string;
lines : TArrayOfString;
n : longint;
i : longint;
errcode : integer;
servnamlen : integer;
error : boolean;
begin
if UsingWinNT() = true then
filename := ExpandConstant('{sys}\drivers\etc\services')
else
filename := ExpandConstant('{win}\services');
if LoadStringsFromFile(filename,lines) = true then begin
Result := true;
n := GetArrayLength(lines) - 1;
servnamlen := Length(service);
error := false;
for i:=0 to n do begin
if Copy(lines[i],1,1) <> '#' then begin
s := Copy(lines[i],1,servnamlen);
if CompareText(s,service) = 0 then
exit; // found service-entry
if Pos(port,lines[i]) > 0 then begin
error := true;
lines[i] := '#' + lines[i] + ' # disabled because collision with ' + service + ' service';
end;
end
else if CompareText(Copy(lines[i],2,servnamlen),service) = 0 then begin
// service-entry was disabled
Delete(lines[i],1,1);
Result := SaveStringsToFile(filename,lines,false);
exit;
end;
end;
if error = true then begin
// save disabled entries
if SaveStringsToFile(filename,lines,false) = false then begin
Result := false;
exit;
end;
end;
// create new service entry
s := service + ' ' + port + ' # ' + comment + #13#10;
if SaveStringToFile(filename,s,true) = false then begin
Result := false;
exit;
end;
if error = true then begin
MsgBox('the ' + service + ' port was already used. The old service is disabled now. You should check the services file manually now.',mbInformation,MB_OK);
//InstExec('notepad.exe',filename,GetCurrentDir(),true,false,SW_SHOWNORMAL,errcode);
end;
end
else
Result := false;
end;
// #######################################################################################
// version functions
// #######################################################################################
function CheckVersion(Filename : string;hh,hl,lh,ll : integer) : boolean;
var
VersionMS : cardinal;
VersionLS : cardinal;
CheckMS : cardinal;
CheckLS : cardinal;
begin
if GetVersionNumbers(Filename,VersionMS,VersionLS) = false then
Result := false
else begin
CheckMS := (hh shl $10) or hl;
CheckLS := (lh shl $10) or ll;
Result := (VersionMS > CheckMS) or ((VersionMS = CheckMS) and (VersionLS >= CheckLS));
end;
end;
// Some examples for version checking
function NeedShellFolderUpdate() : boolean;
begin
Result := CheckVersion('ShFolder.dll',5,50,4027,300) = false;
end;
function NeedVCRedistUpdate() : boolean;
begin
Result := (CheckVersion('mfc42.dll',6,0,8665,0) = false)
or (CheckVersion('msvcrt.dll',6,0,8797,0) = false)
or (CheckVersion('comctl32.dll',5,80,2614,3600) = false);
end;
function NeedHTMLHelpUpdate() : boolean;
begin
Result := CheckVersion('hh.exe',4,72,0,0) = false;
end;
function NeedWinsockUpdate() : boolean;
begin
Result := (UsingWinNT() = false) and (CheckVersion('mswsock.dll',4,10,0,1656) = false);
end;
function NeedDCOMUpdate() : boolean;
begin
Result := (UsingWinNT() = false) and (CheckVersion('oleaut32.dll',2,30,0,0) = false);
end;
// #######################################################################################
// Replace substring in a string functions
// #######################################################################################
procedure FileReplace(SrcFile, sFrom, sTo: String);
var
FileContent: String;
begin
//Load srcfile to a string
LoadStringFromFile(SrcFile, FileContent);
//Replace Fraomstring by toString in file string content
StringChange (sTo,'/', '\');
StringChange (FileContent, sFrom, sTo);
//Replace old content srcfile by the new content
DeleteFile(SrcFile);
SaveStringToFile(SrcFile,FileContent, True);
end;
// #######################################################################################
// Replace in file functions
// #######################################################################################
procedure FileWrite(SrcFile, sFrom, sTo: String);
var
FileContent: String;
begin
//Load srcfile to a string
LoadStringFromFile(SrcFile, FileContent);
//Replace Fraomstring by toString in file string content
//StringChange (sTo,'/', '\');
StringChange (FileContent, sFrom, sTo);
//Replace old content srcfile by the new content
DeleteFile(SrcFile);
SaveStringToFile(SrcFile,FileContent, True);
end;
// #######################################################################################
// Custumized page for apache config
// #######################################################################################
procedure CreateTheWizardPages;
// variables locales
var
Lbl: TLabel;
Page: TWizardPage;
Edit: TEdit;
PortNbr: String;
// boites
begin
Page := CreateCustomPage(wpSelectComponents, 'Apache configuration', 'Please enter your parameter for the apache server (Default is 80)');
Lbl := TLabel.Create(Page);
Lbl.Top := ScaleY(11);
Lbl.Caption := 'Apache server port :';
Lbl.AutoSize := True;
Lbl.Parent := Page.Surface;
Edit := TEdit.Create(Page);
Edit.Top := ScaleY(8);
Edit.Left := Lbl.Left + ScaleX(70);
Edit.Width := Page.SurfaceWidth div 2 - ScaleX(8);
Edit.Text := PortNbr;
Edit.Text := '80';
Edit.Parent := Page.Surface;
end;
// #######################################################################################
// Custumized page for Password enter
// #######################################################################################
procedure CreateTheWizardPagesPwd;
// variables locales
var
PasWd: TLabel;
PagePwd: TWizardPage;
EditPw: TEdit;
//MailHostName: String;
// boites
begin
PagePwd := CreateCustomPage(wpSelectComponents, 'Password for the data base user', 'Please enter the password for the data base');
PasWd := TLabel.Create(PagePwd);
PasWd.Top := ScaleY(11);
PasWd.Caption := 'PassWord : ';
PasWd.AutoSize := True;
PasWd.Parent := PagePwd.Surface;
EditPw := TEdit.Create(PagePwd);
EditPw.Top := ScaleY(8);
EditPw.Left := PasWd.Left + ScaleX(70);
EditPw.Width := PagePwd.SurfaceWidth div 2 - ScaleX(8);
EditPw.Parent := PagePwd.Surface;
end;
// #######################################################################################
// Custumized page for Enter the path of the backup file
// #######################################################################################
procedure CreateTheWizardPagesBkpDir;
var
PageBkpDir: TInputDirWizardPage;
// boites
begin
PageBkpDir := CreateInputDirPage(wpSelectDir,'Select Backup Data Directory','Where should Backup data files be installed?','Select the folder in which Setup should copy backup data files, then click Next.', False, '');
PageBkpDir.Add('');
PageBkpDir.Values[0] := ExpandConstant('{userdesktop}\dbBackup');
end;
// #######################################################################################
// Custumized page for Time zone enter
// #######################################################################################
procedure CreateTheWizardPagesTimeZone;
// variables locales
var
Panel: TPanel;
PageTimeZone: TWizardPage;
ListBTimeZone: TNewListBox;
// boites
begin
PageTimeZone := CreateCustomPage(wpWelcome, 'Time zone of your location', 'Please choose your time zone');
Panel := TPanel.Create(PageTimeZone);
Panel.Width := PageTimeZone.SurfaceWidth div 2 - ScaleX(8);
Panel.Left := PageTimeZone.SurfaceWidth - Panel.Width;
Panel.Caption := 'TPanel';
Panel.Color := clWindow;
Panel.ParentBackground := False;
Panel.Parent := PageTimeZone.Surface;
ListBTimeZone := TNewListBox.Create(PageTimeZone);
ListBTimeZone.Width := PageTimeZone.SurfaceWidth;
ListBTimeZone.Height := ScaleY(200);
ListBTimeZone.Parent := PageTimeZone.Surface;
ListBTimeZone.Items.Add('Etc/UTC');
ListBTimeZone.Items.Add('Europe/Paris');
ListBTimeZone.ItemIndex := 2;
end;
// Initialisation
procedure InitializeWizard();
begin
CreateTheWizardPages;
CreateTheWizardPagesTimeZone;
CreateTheWizardPagesPwd;
CreateTheWizardPagesBkpDir;
end;
// #######################################################################################
// Function to stop and delete de service by uninstallation procedur
// #######################################################################################
procedure CurUninstallStepChanged(CurStep: TUninstallStep);
var
ErrorCode: Integer;
begin
if CurStep = usUninstall then
begin
//Uninstall process
ShellExec('open','taskkill.exe','/f /im MyApplicationService.exe','',SW_HIDE,ewNoWait,ErrorCode);
ShellExec('open','taskkill.exe','/f /im httpd.exe','',SW_HIDE,ewNoWait,ErrorCode);
ShellExec('open','taskkill.exe','/f /im mysqld.exe','',SW_HIDE,ewNoWait,ErrorCode);
// stop all affected services
StopService('MyApplicationService');
StopService('MySqld');
StopService('Apache');
// remove all affected services
RemoveService('MyApplicationService');
RemoveService('MySqld');
RemoveService('Apache');
end;
end;
// #######################################################################################
// Function to check and replace the string in the file at the end of the installation
// #######################################################################################
procedure CurStepChanged(CurStep: TSetupStep);
var
ErrorCode: Integer;
WorkingDir: String;
PathOfDir: String;
begin
//juste aprés installation
if CurStep = ssPostInstall then
begin
PathOfDir := GetShortName(PathOfDir2);
FileReplace(ExpandConstant('{app}\create_db.sql'), '##Pwd##', EditPw.Text);
FileReplace(ExpandConstant('{app}\webserver\bin\apache\Apache2.2.22\conf\httpd.conf'), '##Port##', PortNbr);
FileReplace(ExpandConstant('{app}\webserver\bin\apache\Apache2.2.22\conf\httpd.conf'), '##Path##', PathOfDir+'\webserver');
FileReplace(ExpandConstant('{app}\webserver\bin\apache\Apache2.2.22\bin\php.ini'), '##Path##', PathOfDir+'\webserver');
FileWrite(ExpandConstant('{app}\webserver\bin\apache\Apache2.2.22\bin\php.ini'), '##TimeZone##', TimeZone);
FileReplace(ExpandConstant('{app}\webserver\bin\mysql\mysql5.5.24\my.ini'), '##Path##', PathOfDir+'\webserver');
FileReplace(ExpandConstant('{app}\webserver\bin\mysql\mysql5.5.24\bin\dbexport.bat'), '##Path##', PathOfBackupDir);
FileReplace(ExpandConstant('{app}\webserver\bin\mysql\mysql5.5.24\bin\create_db.bat'), '##Path##', PathOfDir + '\webserver\bin\mysql\mysql5.5.24');
FileReplace(ExpandConstant('{app}\webserver\bin\mysql\mysql5.5.24\bin\create_db.bat'), '##PathOfDir##', PathOfDir);
FileReplace(ExpandConstant('{app}\webserver\bin\php\php5.4.3\php.ini'), '##Path##', PathOfDir+'\webserver');
FileReplace(ExpandConstant('{app}\webserver\bin\php\php5.4.3\phpForApache.ini'), '##Path##', PathOfDir+'\webserver');
if InstallService(ExpandConstant('"{app}\webserver\bin\mysql\mysql5.5.24\bin\mysqld.exe" MySqld'),'MySqld','MySqld','The mysql service',SERVICE_WIN32_OWN_PROCESS,SERVICE_AUTO_START) = true then
begin
StartService('MySqld');
Sleep(8000);
end
else
MsgBox('MySqld service could not be installed',mbInformation, MB_OK);
if InstallService(ExpandConstant('"{app}\webserver\bin\apache\apache2.2.22\bin\httpd.exe" -k runservice'),'Apache','Apache','The apache service',SERVICE_WIN32_OWN_PROCESS,SERVICE_AUTO_START) = true then
begin
StartService('Apache');
Sleep(5000);
end
else
MsgBox('Apache service could not be installed',mbInformation, MB_OK);
if InstallService(ExpandConstant('"{app}\MyApplicationService.exe"'),'MyApplicationService','MyApplicationService','The server',SERVICE_WIN32_OWN_PROCESS,SERVICE_AUTO_START) = true then
begin
StartService('MyApplicationService');
Sleep(5000);
end
else
MsgBox('The MyApplicationService service could not be installed',mbInformation, MB_OK);
end;
if CurStep = ssInstall then
begin
//Uninstall process
ShellExec('open','taskkill.exe','/f /im MyApplicationService.exe','',SW_HIDE,ewNoWait,ErrorCode);
ShellExec('open','taskkill.exe','/f /im httpd.exe','',SW_HIDE,ewNoWait,ErrorCode);
ShellExec('open','taskkill.exe','/f /im mysqld.exe','',SW_HIDE,ewNoWait,ErrorCode);
// stop all affected services
StopService('MyApplicationService');
StopService('MySqld');
StopService('Apache');
// remove all affected services
RemoveService('MyApplicationService');
RemoveService('MySqld');
RemoveService('Apache');
end;
if CurStep = ssDone then
begin
Exec(ExpandConstant('{app}\webserver\bin\mysql\mysql5.5.24\bin\create_db.bat'),'','', SW_SHOW, ewWaitUntilTerminated, ErrorCode);
end;
end;
// #######################################################################################
// Function to check the values entered
// #######################################################################################
function NextButtonClick(CurPageID: Integer): Boolean;
var
ErrorCode: Integer;
begin
Result := True;
case CurPageID of
Page.ID:
begin
if (Edit.Text = '') then
begin
MsgBox('Port number check:'#13#13 'The port number is empty. The default port << 80 >> will be applied. Please click on the back button to change if needed ', mbError, MB_OK);
Edit.Text := '80';
end
else
begin
Result := True;
PortNbr := Edit.Text;
end
end;
//End page.id
PagesEmailSt.ID:
begin
if (EditPwd.Text = EditPwd2.Text) then
begin
MailHostName := EditMailHostName.Text;
MailUserName := EditUserName.Text;
MailPwd := EditPwd.Text;
MailFrom := EditFromMail.Text;
MailSmtpPort := EditSmtpPort.Text;
end
else
begin
MsgBox('Password check:'#13#13 'The password entered is not the same. Please click on back and check ', mbError, MB_OK);
Result := false;
end
end;
//End PagesEmailSt.id
//Time zone add beginn
PageTimeZone.ID:
begin
Result := false;
TimeZone := ListBTimeZone.Items.Strings[ListBTimeZone.ItemIndex];
end;
//End time zone add
//Beginn dir selector
PageBkpDir.ID:
begin
//PageBkpDir.Values[0] := ExpandConstant('{userdesktop}\dbBackup');
PathOfBackupDir := PageBkpDir.Values[0];
end;
wpSelectDir:
begin
PathOfDir2 := WizardDirValue;
//MsgBox('NextButtonClick:' #13#13 'You selected: ''' + PathOfDir + '''.', mbInformation, MB_OK);
end;
//End dir selector
end; //End case
Result := True;
end;
function GetDataDir(Param: String): String;
begin
//Return the selected DataDir
Result := PageBkpDir.Values[0];
end;
In this case, as it needs to be accessed from multiple functions, you need to make it a global variable by putting it in the top Var. You will also need to do the same with the page references/IDs.

PostgreSQL trigger syntax error

I wonder how to use trigger in PostgreSQL with RAISE SQLSTATE dynamic instruction?
IF i>0 THEN
RAISE SQLSTATE '23505' USING MESSAGE = 'la planète est déjà occupée (planet_non_free)=(%, %, %)', NEW.galaxie, NEW.systeme_solaire, NEW.position;
END IF;
It doesn't work.
I suggest to use:
IF i > 0 THEN
RAISE SQLSTATE '23505'
USING MESSAGE = format('la planète est déjà occupée (planet_non_free)=(%s, %s, %s)', NEW.galaxie, NEW.systeme_solaire, NEW.position);
END IF;
Then your error message reads:
la planète est déjà occupée (planet_non_free)=(<g>, <s>, <p>)
.. instead of:
("la planète est déjà occupée (planet_non_free)=(%, %, %)",<g>, <s>, <p>)
Ok, I've found the solution. I have only to surround MESSAGE value with parenthesis :
So :
IF i>0 THEN
RAISE SQLSTATE '23505' USING MESSAGE = 'la planète est déjà occupée (planet_non_free)=(%, %, %)', NEW.galaxie, NEW.systeme_solaire, NEW.position;
END IF;
becomes :
IF i>0 THEN
RAISE SQLSTATE '23505' USING MESSAGE = ('la planète est déjà occupée (planet_non_free)=(%, %, %)', NEW.galaxie, NEW.systeme_solaire, NEW.position);
END IF;
Simple but I did not saw explicit example with dynamic MESSAGE on the web.
Hope this helps
EDIT :
Ok sorry, the right syntax is this one :
IF i>0 THEN
RAISE SQLSTATE '23505' USING MESSAGE = 'la planète est déjà occupée (planet_non_free)=(' || NEW.galaxie || ',' || NEW.systeme_solaire || ',' || NEW.position || ')';
END IF;
It seems that we can not use % with USING MESSAGE statement.