segunda-feira, 20 de agosto de 2007

Rotinas em DELPHI para atualização de uma Tupla específica

Saudações Alunos e programadores,

abaixo segue um conjunto de rotinas utilizadas no processo de atualização de uma Tupla, escolhida pelo usuário, para ser atualizada por meio do comando em SQL denominado "UPDATE".

Uma série de verificações é realizada antes da atualização ser realizada com sucesso.
Observe com o seguinte espírito:
"... Você pode fazer diferente, Você pode fazer melhor ..."

Um grande abraço

Professor Alexandre Manoel


//==============================================================================
function Talx_frm_sgc_contas_bancarias.alx_boo_Conta_Bancaria_Alterada_Com_Sucesso(): Boolean;
var
alx_str_sql_text : TStrings;
alx_boo_apoio : Boolean;
alx_int_cb_id : Integer;
alx_str_cb_nome : String;
alx_str_cb_codigo : String;
alx_int_cb_ab_id : Integer;
alx_int_cb_un_id : Integer;
begin
try
alx_int_cb_id := strtoint(self.Edit2.Text);
alx_str_cb_nome := self.Edit3.Text;
alx_str_cb_codigo := self.Edit4.Text;
alx_int_cb_ab_id := strtoint(self.edit5.Text);
//--------------
alx_str_sql_text := TStringList.Create();
alx_str_sql_text.Add('UPDATE CONTAS_BANCARIAS SET CB_NOME = : , CB_CODIGO = : , CB_AB_ID = : , CB_UN_ID = 1 , CB_ATIVO = TRUE ');
alx_str_sql_text.Add('WHERE CB_ID = : ; ') ;
self.ADOQuery_Apoio.Active:= False;
self.ADOQuery_Apoio.SQL.Clear();
self.ADOQuery_Apoio.SQL:= alx_str_sql_text;
self.ADOQuery_Apoio.Parameters[0].Value:= alx_str_cb_nome;
self.ADOQuery_Apoio.Parameters[1].Value:= alx_str_cb_codigo;
self.ADOQuery_Apoio.Parameters[2].Value:= alx_int_cb_ab_id;
self.ADOQuery_Apoio.Parameters[3].Value:= alx_int_cb_id;
//--------------
self.ADOQuery_Apoio.ExecSQL();
alx_boo_apoio:= True;
self.alx_int_conta_bancaria_id_em_foco:= alx_int_cb_id; //... informa o id do usuário que foi inserido ...
//--------------
except
on E: Exception do begin
alx_boo_apoio := False;
self.alx_int_conta_bancaria_id_em_foco:= 0;
ShowMessage('Ôpa, ocorreu um erro ao realizar a transação que altera uma conta bancária escolhida no sistema! Veja: ' + E.Message);
end;
end;
result:= alx_boo_apoio;
end;
//==============================================================================
procedure Talx_frm_sgc_contas_bancarias.alx_voi_Colocar_Cursor_Sobre_Conta_Bancaria_Inserida_Ou_Alterada();
var
alx_int_apoio: Integer;
begin
try
self.ADOQuery_Contas_Bancarias.First();
while not(self.ADOQuery_Contas_Bancarias.Eof) do begin
alx_int_apoio:= self.ADOQuery_Contas_Bancarias.Fields[0].AsInteger;
if (alx_int_apoio = self.alx_int_conta_bancaria_id_em_foco) then begin
break;
end
else begin
self.ADOQuery_Contas_Bancarias.Next();
end;
end;
except
on e:Exception do begin
showmessage('Ôpa, ocorreu um erro ao colocar o cursor sobre a Conta Bancária recém inserida ou alterada! Veja: ' + E.Message);
end;
end;
end;
//==============================================================================
function Talx_frm_sgc_contas_bancarias.alx_int_Pegar_Agencia_Bancaria_Id(alx_str_agencia_bancaria_nome: String): Integer;
var
alx_str_sql_text: TStrings;
alx_int_apoio : Integer;
begin
try
alx_str_sql_text:= TStringList.Create();
alx_str_sql_text.Add('SELECT AB_ID FROM AGENCIAS_BANCARIAS WHERE AB_NOME = : ');
self.ADOQuery_Apoio.Active:= False;
self.ADOQuery_Apoio.SQL.Clear();
self.ADOQuery_Apoio.SQL:= alx_str_sql_text;
self.ADOQuery_Apoio.Parameters[0].Value:= alx_str_agencia_bancaria_nome;
self.ADOQuery_Apoio.Active:= True;
//-----------------
alx_int_apoio:= self.ADOQuery_Apoio.Fields[0].AsInteger;
self.ADOQuery_Apoio.Active:= False;
//-----------------
except
on E: Exception do begin
alx_int_apoio:= 0;
showmessage('Ôpa, ocorreu um erro ao buscar o código de identificação de uma Agência Bancária escolhida! Veja: ' + E.Message);
end;
end;
result:= alx_int_apoio;
end;
//==============================================================================
function Talx_frm_sgc_contas_bancarias.alx_int_Pegar_Banco_Sigla(alx_str_agencia_bancaria_nome: String): String;
var
alx_str_sql_text: TStrings;
alx_str_apoio : String;
begin
try
alx_str_sql_text:= TStringList.Create();
alx_str_sql_text.Add('SELECT BAN_SIGLA FROM AGENCIAS_BANCARIAS, BANCOS WHERE AB_BAN_ID = BAN_ID AND AB_NOME = : ');
self.ADOQuery_Apoio.Active:= False;
self.ADOQuery_Apoio.SQL.Clear();
self.ADOQuery_Apoio.SQL:= alx_str_sql_text;
self.ADOQuery_Apoio.Parameters[0].Value:= alx_str_agencia_bancaria_nome;
self.ADOQuery_Apoio.Active:= True;
//-----------------
alx_str_apoio:= self.ADOQuery_Apoio.Fields[0].AsString;
self.ADOQuery_Apoio.Active:= False;
//-----------------
except
on E: Exception do begin
alx_str_apoio:= 'erro!';
showmessage('Ôpa, ocorreu um erro ao buscar a sigla do Banco associado à Agência Bancária escolhida! Veja: ' + E.Message);
end;
end;
result:= alx_str_apoio;
end;
//==============================================================================
procedure Talx_frm_sgc_contas_bancarias.alx_voi_Especificar_Cidade_E_UF_Da_Conta_Escolhida(alx_str_agencia_bancaria_nome: String);
var
alx_str_sql_text: TStrings;
begin
try
alx_str_sql_text:= TStringList.Create();
alx_str_sql_text.Add('SELECT CITY_NOME , UF_SIGLA FROM AGENCIAS_BANCARIAS, CIDADES, UNIDADES_FEDERACAO ');
alx_str_sql_text.Add('WHERE AB_CITY_ID = CITY_ID AND CITY_UF_ID = UF_ID AND AB_NOME = : ');
self.ADOQuery_Apoio.Active:= False;
self.ADOQuery_Apoio.SQL.Clear();
self.ADOQuery_Apoio.SQL:= alx_str_sql_text;
self.ADOQuery_Apoio.Parameters[0].Value:= alx_str_agencia_bancaria_nome;
self.ADOQuery_Apoio.Active:= True;
//-----------------
self.Edit6.Text:= self.ADOQuery_Apoio.Fields[0].AsString;
self.Edit7.Text:= self.ADOQuery_Apoio.Fields[1].AsString;
self.ADOQuery_Apoio.Active:= False;
//-----------------
except
on E: Exception do begin
self.Edit6.Text:= 'erro!';
self.Edit7.Text:= 'erro!';
showmessage('Ôpa, ocorreu um erro ao especificar o nome da cidade e a sigla do estado associados à Agência Bancária escolhida! Veja: ' + E.Message);
end;
end;
end;
//==============================================================================
procedure Talx_frm_sgc_contas_bancarias.alx_voi_Atualizar_Campos_Ao_Selecionar_Conta_Bancaria();
var
alx_str_apoio: String;
begin
alx_str_apoio:= self.ComboBox1.Text;
self.Edit5.Text:= inttostr(self.alx_int_Pegar_Agencia_Bancaria_Id(alx_str_apoio));
self.Edit8.Text:= self.alx_int_Pegar_Banco_Sigla(alx_str_apoio);
self.alx_voi_Especificar_Cidade_E_UF_Da_Conta_Escolhida(alx_str_apoio);
end;
//==============================================================================
procedure Talx_frm_sgc_contas_bancarias.alx_voi_Controlar_Processo_Alteracao_Conta_Bancaria();
begin
if((self.BitBtn12.Caption = 'alterar') and (self.alx_boo_Usuario_Tem_Permissao_Para_Alteracao_Conta_Bancaria()) ) then begin
self.alx_voi_Liberar_Edits_Para_Edicao(True); //... liberar edits para edição ...
self.alx_voi_Bloquear_Botoes_Para_Alteracao(True); //... bloquear botões ...
self.alx_voi_Popular_Combobox_Agencias_Bancarias(); //... popular o combobox de agências bancárias ...
self.BitBtn12.Caption:= 'salvar';
end
else if ((self.BitBtn12.Caption = 'salvar') and (self.alx_boo_Verificacao_Ok()) ) then begin //...testar antes os campos...
if(self.alx_boo_Conta_Bancaria_Alterada_Com_Sucesso()) then begin //... somente se a inserção foi um sucesso ...
self.alx_voi_Popular_Grid_Contas_Bancarias(); //... realiza um refresh no grid ...
self.alx_voi_Colocar_Cursor_Sobre_Conta_Bancaria_Inserida_Ou_Alterada(); //... coloca o cursor sobre o usuário recém inserido
self.alx_voi_Atualizar_Cartao_Conta_Bancaria(); //... atualiza o cartão d usuário ...
self.alx_voi_Liberar_Edits_Para_Edicao(False); //... não-liberar edits para edição ...
self.alx_voi_Bloquear_Botoes_Para_Alteracao(False); //... desbloquear botões ...
self.BitBtn12.Caption:= 'alterar';
end;
end;
end;
//==============================================================================

sexta-feira, 13 de julho de 2007

Rotinas em DELPHI para uma inserção completa de tuplas: Caso de Usuários de um Sistema


As seguintes rotinas computacionais destinam-se à realização de um processo completo de inserção de tuplas em uma dada tabela de um banco de dados.



A interface que controla a coleção de usuários do sistema é apresentada na figura. Vários controles de verificação são realizados antes da inserção de uma tupla no banco de dados. Observe com atenção. Você pode fazer diferente, você pode fazer melhor... Temos aqui uma "dica" para ser usada como ponto de partida.

Lá vai...

private
{ Private declarations }
//-------
alx_int_user_id : Integer;
alx_str_user_nome : String;
alx_int_user_na_id : Integer;
alx_int_usuario_id_em_foco: Integer; //... descrição do usuário que receberá o foco logo após ser inserido ou alterado, ou ainda, excluído ...
//-------
function alx_boo_Usuario_Inserido_Com_Sucesso(): Boolean;
function alx_boo_Usuario_Tem_Permissao_Para_Insercao_Novo_Usuario(): Boolean;
function alx_boo_Verificacao_Ok(): Boolean;
function alx_int_Pegar_Nivel_Acesso_Id(alx_str_nivel_acesso_nome: String): Integer;
function alx_int_Pegar_Usuarios_Novo_Id(): Integer;
//-------
procedure alx_voi_Atualizar_Cartao_Usuario();
procedure alx_voi_Colocar_Cursor_Sobre_Usuario_Inserido_Ou_Alterado();
procedure alx_voi_Bloquear_Botoes_Para_Insercao(alx_boo_bloquear: Boolean);
procedure alx_voi_Controlar_Processo_Insercao_Usuario();
procedure alx_voi_Liberar_Edits_Para_Edicao(alx_boo_liberar: Boolean);
procedure alx_voi_Limpar_Campos_Cartao_Usuario();
procedure alx_voi_Popular_Combobox_Nivel_Acesso();
procedure alx_voi_Popular_Grid_Usuarios();
procedure alx_voi_Registrar_Entrada_Usuario(alx_int_usuario_id: Integer ; alx_str_nome: String ; alx_int_na_id: Integer);
procedure alx_voi_Registrar_Status_Bar_Usuario();
public
{ Public declarations }
constructor alx_voi_Create(alx_obj_owner: TComponent ; alx_int_usuario_id: Integer ; alx_str_user_name: String ; alx_int_nivel_acesso_id: Integer);
end;



implementation

{$R *.dfm}
//==============================================================================
constructor Talx_frm_sgc_users.alx_voi_Create(alx_obj_owner: TComponent ; alx_int_usuario_id: Integer ; alx_str_user_name: String ; alx_int_nivel_acesso_id: Integer);
begin
inherited Create(alx_obj_owner);
self.alx_voi_Registrar_Entrada_Usuario(alx_int_usuario_id , alx_str_user_name , alx_int_nivel_acesso_id);
self.alx_voi_Popular_Grid_Usuarios(); //... popular grid usuarios...
self.alx_voi_Atualizar_Cartao_Usuario(); //... atualizar cartão de usuários ...
self.alx_voi_Registrar_Status_Bar_Usuario();
self.Show();
end;
//==============================================================================
procedure Talx_frm_sgc_users.alx_voi_Popular_Grid_Usuarios();
var
alx_str_sql_text: TStrings;
begin
try
alx_str_sql_text:= TStringList.Create();
alx_str_sql_text.Add('SELECT USER_ID , USER_NOME, USER_APELIDO, USER_NA_ID, NA_APELIDO, USER_ATIVO ');
alx_str_sql_text.Add('FROM USERS , NIVEIS_ACESSO ' );
alx_str_sql_text.Add('WHERE USER_NA_ID = NA_ID ' );
alx_str_sql_text.Add('ORDER BY USER_NOME ;');
self.ADOQuery_Usuarios.Active:= False;
self.ADOQuery_Usuarios.SQL.Clear();
self.ADOQuery_Usuarios.SQL:= alx_str_sql_text;
self.ADOQuery_Usuarios.Active:= True;
except
on E: Exception do begin
showmessage('Ôpa, ocorreu um erro ao popular o combo de Contas Bancárias! Veja: ' + E.Message);
end;
end;
end;
//==============================================================================
procedure Talx_frm_sgc_users.alx_voi_Atualizar_Cartao_Usuario();
begin
try
self.Edit2.Text := self.ADOQuery_Usuarios.Fields[0].AsString;
self.Edit3.Text := self.ADOQuery_Usuarios.Fields[1].AsString;
self.Edit4.Text := self.ADOQuery_Usuarios.Fields[2].AsString;
self.Edit5.Text := self.ADOQuery_Usuarios.Fields[3].AsString;
self.ComboBox1.Text := self.ADOQuery_Usuarios.Fields[4].AsString;
self.Edit6.Text := 'senha_1';
self.Edit7.Text := 'senha_2';
self.CheckBox1.Checked:= self.ADOQuery_Usuarios.Fields[5].AsBoolean;
self.ComboBox1.Items.Clear();
self.ComboBox1.Enabled:= False;
except
on E:Exception do begin
self.Edit2.Text := 'erro'; self.Edit3.Text:= 'erro'; self.Edit4.Text:= 'erro' ; self.Edit5.Text:= 'erro';
self.ComboBox1.Text := 'erro'; self.Edit6.Text:= 'erro_1'; self.Edit7.Text:= 'erro_2'; self.CheckBox1.Checked:= False;
showmessage('Ôpa, ocorreu um erro ao atualizar o cartão de Usuários! Veja: ' + E.Message);
end;
end;
end;
//==============================================================================
procedure Talx_frm_sgc_users.alx_voi_Registrar_Entrada_Usuario(alx_int_usuario_id: Integer ; alx_str_nome: String ; alx_int_na_id: Integer);
begin
self.alx_int_user_id := alx_int_usuario_id;
self.alx_str_user_nome := alx_str_nome;
self.alx_int_user_na_id := alx_int_na_id;
self.alx_int_usuario_id_em_foco:= 0; //... código de um usuário recém inserido, ou alterado, para amnter o foco logo após a inserção ou alteração ...
end;
//==============================================================================
procedure Talx_frm_sgc_users.alx_voi_Registrar_Status_Bar_Usuario();
begin
self.StatusBar1.Panels[0].Text:= ' Usuário: ' + self.alx_str_user_nome;
self.StatusBar1.Panels[1].Text:= ' Nível de Acesso: ' + inttostr(self.alx_int_user_na_id);
self.StatusBar1.Panels[2].Text:= ' ';
self.StatusBar1.Panels[3].Text:= ' ';
self.StatusBar1.Panels[4].Text:= ' Sistema Saturno';
self.StatusBar1.Panels[5].Text:= ' AlexS - Software para Engenharia';
end;
//==============================================================================
procedure Talx_frm_sgc_users.alx_voi_Controlar_Processo_Insercao_Usuario();
begin
if((self.BitBtn11.Caption = 'inserir') and (self.alx_boo_Usuario_Tem_Permissao_Para_Insercao_Novo_Usuario()) ) then begin
self.alx_voi_Limpar_Campos_Cartao_Usuario(); //... limpar campos ...
self.alx_voi_Liberar_Edits_Para_Edicao(True); //... liberar edits para edição ...
self.alx_voi_Bloquear_Botoes_Para_Insercao(True); //... bloquear botões ...
self.Edit2.Text:= inttostr(self.alx_int_Pegar_Usuarios_Novo_Id()); //... anuncia um provável código novo para a futura inserção ...
self.alx_voi_Popular_Combobox_Nivel_Acesso(); //... popular o combobox do nivel de acesso ...
self.BitBtn11.Caption:= 'salvar';
end
else if ((self.BitBtn11.Caption = 'salvar') and (self.alx_boo_Verificacao_Ok()) ) then begin //...testar antes os campos...
if(self.alx_boo_Usuario_Inserido_Com_Sucesso()) then begin //... somente se a inserção foi um sucesso ...
self.alx_voi_Popular_Grid_Usuarios(); //... realiza um refresh no grid ...
self.alx_voi_Colocar_Cursor_Sobre_Usuario_Inserido_Ou_Alterado(); //... coloca o cursor sobre o usuário recém inserido
self.alx_voi_Atualizar_Cartao_Usuario(); //... atualiza o cartão d usuário ...
self.alx_voi_Liberar_Edits_Para_Edicao(False); //... não-liberar edits para edição ...
self.alx_voi_Bloquear_Botoes_Para_Insercao(False); //... desbloquear botões ...
self.BitBtn11.Caption:= 'inserir';
end;
end;
end;
//==============================================================================
procedure Talx_frm_sgc_users.alx_voi_Limpar_Campos_Cartao_Usuario();
begin
self.Edit2.Text := '';
self.Edit3.Text := '';
self.Edit4.Text := '';
self.Edit5.Text := '';
self.ComboBox1.Text := '';
self.Edit6.Text := '';
self.Edit7.Text := '';
self.ComboBox1.Text := 'escolha um nível de acesso';
self.CheckBox1.Checked:= True;
end;
//==============================================================================
procedure Talx_frm_sgc_users.alx_voi_Liberar_Edits_Para_Edicao(alx_boo_liberar: Boolean);
begin
self.Edit1.ReadOnly := alx_boo_liberar;
self.Edit2.ReadOnly := True;
self.Edit3.ReadOnly := not(alx_boo_liberar);
self.Edit4.ReadOnly := not(alx_boo_liberar);
self.Edit5.ReadOnly := True;
self.Edit6.ReadOnly := not(alx_boo_liberar);
self.Edit7.ReadOnly := not(alx_boo_liberar);
self.CheckBox1.Enabled:= alx_boo_liberar;
self.ComboBox1.Enabled:= alx_boo_liberar;
end;
//==============================================================================
procedure Talx_frm_sgc_users.alx_voi_Bloquear_Botoes_Para_Insercao(alx_boo_bloquear: Boolean);
begin
self.BitBtn1.Enabled := not(alx_boo_bloquear);
self.BitBtn2.Enabled := not(alx_boo_bloquear);
self.BitBtn3.Enabled := not(alx_boo_bloquear);
self.BitBtn4.Enabled := not(alx_boo_bloquear);
self.BitBtn5.Enabled := not(alx_boo_bloquear);
self.BitBtn6.Enabled := not(alx_boo_bloquear);
self.BitBtn7.Enabled := not(alx_boo_bloquear);
self.BitBtn8.Enabled := not(alx_boo_bloquear);
self.BitBtn9.Enabled := not(alx_boo_bloquear);
self.BitBtn10.Enabled:= not(alx_boo_bloquear);
self.BitBtn11.Enabled:= True;
self.BitBtn12.Enabled:= not(alx_boo_bloquear);
self.BitBtn13.Enabled:= not(alx_boo_bloquear);
self.BitBtn14.Enabled:= True;
self.CheckBox1.Enabled:= False;
end;
//==============================================================================
function Talx_frm_sgc_users.alx_int_Pegar_Usuarios_Novo_Id(): Integer;
var
alx_str_sql_text: TStrings;
alx_int_apoio : Integer;
begin
try
alx_str_sql_text:= TStringList.Create();
alx_str_sql_text.Add('SELECT MAX(USER_ID) FROM USERS ');
self.ADOQuery_Apoio.Active:= False;
self.ADOQuery_Apoio.SQL.Clear();
self.ADOQuery_Apoio.SQL:= alx_str_sql_text;
self.ADOQuery_Apoio.Active:= True;
//-----------------
alx_int_apoio:= self.ADOQuery_Apoio.Fields[0].AsInteger + 1;
self.ADOQuery_Apoio.Active:= False;
//-----------------
except
on E: Exception do begin
alx_int_apoio:= 0;
showmessage('Ôpa, ocorreu um erro ao buscar o novo código para um USUÁRIO! Veja: ' + E.Message);
end;
end;
result:= alx_int_apoio;
end;
//==============================================================================
procedure Talx_frm_sgc_users.alx_voi_Popular_Combobox_Nivel_Acesso();
var
alx_str_sql_text: TStrings;
begin
try
alx_str_sql_text:= TStringList.Create();
alx_str_sql_text.Add('SELECT NA_APELIDO ');
alx_str_sql_text.Add('FROM NIVEIS_ACESSO ');
alx_str_sql_text.Add('WHERE NA_ATIVO = TRUE ');
alx_str_sql_text.Add('ORDER BY NA_APELIDO ; ');
self.ADOQuery_Apoio.Active:= False;
self.ADOQuery_Apoio.SQL.Clear();
self.ADOQuery_Apoio.SQL:= alx_str_sql_text;
self.ADOQuery_Apoio.Active:= True;
//-----------------
self.ComboBox1.Items.Clear();
while not(self.ADOQuery_Apoio.Eof) do begin
self.ComboBox1.Items.Add(self.ADOQuery_Apoio.Fields[0].AsString);
self.ADOQuery_Apoio.Next();
end;
self.ComboBox1.Text:= 'escolha um nível de acesso';
self.Edit5.Text:= '';
//-----------------
self.ADOQuery_Apoio.Active:= False;
//-----------------
except
on E: Exception do begin
showmessage('Ôpa, ocorreu um erro ao popular o combo de Níveis de Acesso! Veja: ' + E.Message);
end;
end;
end;
//==============================================================================
function Talx_frm_sgc_users.alx_int_Pegar_Nivel_Acesso_Id(alx_str_nivel_acesso_nome: String): Integer;
var
alx_str_sql_text: TStrings;
alx_int_apoio : Integer;
begin
try
alx_str_sql_text:= TStringList.Create();
alx_str_sql_text.Add('SELECT NA_ID FROM NIVEIS_ACESSO WHERE NA_APELIDO = : ');
self.ADOQuery_Apoio.Active:= False;
self.ADOQuery_Apoio.SQL.Clear();
self.ADOQuery_Apoio.SQL:= alx_str_sql_text;
self.ADOQuery_Apoio.Parameters[0].Value:= alx_str_nivel_acesso_nome;
self.ADOQuery_Apoio.Active:= True;
//-----------------
alx_int_apoio:= self.ADOQuery_Apoio.Fields[0].AsInteger;
self.ADOQuery_Apoio.Active:= False;
//-----------------
except
on E: Exception do begin
alx_int_apoio:= 0;
showmessage('Ôpa, ocorreu um erro ao buscar o código para um apelido de Nível de Acesso escolhido! Veja: ' + E.Message);
end;
end;
result:= alx_int_apoio;
end;
//==============================================================================
function Talx_frm_sgc_users.alx_boo_Usuario_Inserido_Com_Sucesso(): Boolean;
var
alx_str_sql_text : TStrings;
alx_boo_apoio : Boolean;
alx_int_user_id : Integer;
alx_str_user_nome : String;
alx_str_user_apelido: String;
alx_str_senha : String;
alx_int_user_na_id : Integer;
begin
try
alx_int_user_id := self.alx_int_Pegar_Usuarios_Novo_Id();
alx_str_user_nome := self.Edit3.Text;
alx_str_user_apelido:= self.Edit4.Text;
alx_str_senha := self.edit6.Text;
alx_int_user_na_id := strtoint(self.Edit5.Text);
//--------------
alx_str_sql_text := TStringList.Create();
alx_str_sql_text.Add('INSERT INTO USERS VALUES (:, :, :, :, :, True) ; ');
self.ADOQuery_Apoio.Active:= False;
self.ADOQuery_Apoio.SQL.Clear();
self.ADOQuery_Apoio.SQL:= alx_str_sql_text;
self.ADOQuery_Apoio.Parameters[0].Value := alx_int_user_id;
self.ADOQuery_Apoio.Parameters[1].Value := alx_str_user_nome;
self.ADOQuery_Apoio.Parameters[2].Value := alx_str_user_apelido;
self.ADOQuery_Apoio.Parameters[3].Value := alx_str_senha;
self.ADOQuery_Apoio.Parameters[4].Value := alx_int_user_na_id;
//--------------
self.ADOQuery_Apoio.ExecSQL();
alx_boo_apoio:= True;
self.alx_int_usuario_id_em_foco:= alx_int_user_id; //... informa o id do usuário que foi inserido ...
//--------------
except
on E: Exception do begin
alx_boo_apoio := False;
self.alx_int_usuario_id_em_foco:= 0;
ShowMessage('Ôpa, ocorreu um erro ao realizar a transação que insere um novo usuário no sistema! Veja: ' + E.Message);
end;
end;
result:= alx_boo_apoio;
end;
//==============================================================================
procedure Talx_frm_sgc_users.alx_voi_Colocar_Cursor_Sobre_Usuario_Inserido_Ou_Alterado();
var
alx_int_apoio: Integer;
begin
try
self.ADOQuery_Usuarios.First();
while not(self.ADOQuery_Usuarios.Eof) do begin
alx_int_apoio:= self.ADOQuery_Usuarios.Fields[0].AsInteger;
if (alx_int_apoio = self.alx_int_usuario_id_em_foco) then begin
break;
end
else begin
self.ADOQuery_Usuarios.Next();
end;
end;
except
on e:Exception do begin
showmessage('Ôpa, ocorreu um erro ao colocar o cursor sobre o usuário recém inserido ou alterado! Veja: ' + E.Message);
end;
end;
end;
//==============================================================================
function Talx_frm_sgc_users.alx_boo_Verificacao_Ok(): Boolean;
var
alx_boo_apoio: Boolean;
begin
try
alx_boo_apoio:= True;
if not(self.Edit3.Text <> '') then begin
alx_boo_apoio:= False;
showmessage('Você deve digitar um nome para o usuário!');
self.Edit3.SetFocus();
end
else if not(self.Edit4.Text <> '') then begin
alx_boo_apoio:= False;
showmessage('Você deve digitar um apelido para o usuário!');
self.Edit4.SetFocus();
end
else if not(self.Edit5.Text <> '') then begin
alx_boo_apoio:= False;
showmessage('Você deve escolher um nível de acesso para esse usuário!');
self.ComboBox1.SetFocus();
end
else if not(self.Edit6.Text <> '') then begin
alx_boo_apoio:= False;
showmessage('A primeira senha não pode ser vazia!');
self.Edit6.SetFocus();
end
else if not(self.Edit7.Text <> '') then begin
alx_boo_apoio:= False;
showmessage('A segunda senha não pode ser vazia!');
self.Edit7.SetFocus();
end
else if not(self.Edit6.Text = self.Edit7.Text) then begin
alx_boo_apoio:= False;
showmessage('As senhas devem possuir mesmo valor (devem ser iguais). Digite-as novamente!');
self.Edit7.Text:= '';
self.Edit6.SetFocus();
end;
except
on E: Exception do begin
alx_boo_apoio:= False;
showmessage('Ôpa, ocorreu um erro ao verificar a possibilidade de inserir ou alterar dados de um usuário! Veja: ' + E.Message);
end;
end;
result:= alx_boo_apoio;
end;
//==============================================================================
function Talx_frm_sgc_users.alx_boo_Usuario_Tem_Permissao_Para_Insercao_Novo_Usuario(): Boolean;
var
alx_boo_apoio: Boolean;
begin
if ((self.alx_int_user_na_id = 1) or (self.alx_int_user_na_id = 2) or (self.alx_int_user_na_id = 6)) then begin
alx_boo_apoio:= True;
end
else begin
alx_boo_apoio:= False;
showmessage('você não tem permissão para inserir usuários. Procure o admiistrador do sistema para essa operação!');
end;
result:= alx_boo_apoio;
end;
//==============================================================================
procedure Talx_frm_sgc_users.BitBtn1Click(Sender: TObject);
begin
self.Close();
end;

procedure Talx_frm_sgc_users.FormClose(Sender: TObject; var Action: TCloseAction);
begin
self.Destroy;
end;

procedure Talx_frm_sgc_users.Fechar1Click(Sender: TObject);
begin
self.Close();
end;

procedure Talx_frm_sgc_users.DBGrid1CellClick(Column: TColumn);
begin
self.alx_voi_Atualizar_Cartao_Usuario();
end;

procedure Talx_frm_sgc_users.DBGrid1KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
self.alx_voi_Atualizar_Cartao_Usuario();
end;

procedure Talx_frm_sgc_users.BitBtn2Click(Sender: TObject);
begin
self.ADOQuery_Usuarios.First();
self.alx_voi_Atualizar_Cartao_Usuario();
end;

procedure Talx_frm_sgc_users.BitBtn3Click(Sender: TObject);
begin
self.ADOQuery_Usuarios.Prior();
self.alx_voi_Atualizar_Cartao_Usuario();
end;

procedure Talx_frm_sgc_users.BitBtn4Click(Sender: TObject);
begin
self.ADOQuery_Usuarios.Next();
self.alx_voi_Atualizar_Cartao_Usuario();
end;

procedure Talx_frm_sgc_users.BitBtn5Click(Sender: TObject);
begin
self.ADOQuery_Usuarios.Last();
self.alx_voi_Atualizar_Cartao_Usuario();
end;

procedure Talx_frm_sgc_users.BitBtn11Click(Sender: TObject);
begin
self.alx_voi_Controlar_Processo_Insercao_Usuario();
//... transferir o controle para uma procedure de alteração ...
end;

procedure Talx_frm_sgc_users.ComboBox1Select(Sender: TObject);
begin
self.Edit5.Text:= inttostr(self.alx_int_Pegar_Nivel_Acesso_Id(self.ComboBox1.Text));
end;

end.

quarta-feira, 4 de julho de 2007

Rotinas em DELPHI para operacionalização de uma Transação com ADO

Saudações alunos e interessados,

abaixo segue um conjunto de rotinas computacionais cujo principal objetivo é realizar duas tarefas específicas que fazem parte de uma certa transação sobre um banco de dados, por meio dos componentes "ADOConnection" e "ADOQuery".

Basicamente, esta TRANSAÇÃO controla as seguintes atualizações no banco de dados:
Tarefa_1: responsável pela inserção de um novo lançamento contábil de uma receita, cuja conta bancária e conta de nível_4 precisa ser especificada, juntamente com o valor do lançamento, em uma tabela denominada "Lançamentos";
Tarefa_2: responsável pela inserção dos elementos, presentes em uma lista, que representam as atividades que irão participar de um "rateio" e que estão associados ao lançamento inserido na tarefa anterior. Cada rateio mapeia um código exclusivo, uma atividade específica e um valor parcial, na tabela denominada "Rateios".
Então, a transação somente se completará se as duas tarefas forem realizadas com sucesso. Se não, um RollBack_trans é solicitado.

Seguem os artefatos de software:

//==============================================================================
procedure Talx_frm_sgc_lancamentos_receitas.alx_voi_Operar_Transacao_Insercao();
begin
try
alx_frm_data_module.ADOConnection_SGC.BeginTrans();
//----------------
if( self.alx_boo_Tarefa_1_Transacao_Realizada_Com_Sucesso() ) then begin //... insere o novo lançamento ...
if( self.alx_boo_Tarefa_2_Transacao_Realizada_Com_Sucesso() ) then begin //... insere as atividades associadas ...
alx_frm_data_module.ADOConnection_SGC.CommitTrans();
showmessage('O lançamento foi inserido no banco de dados com sucesso!');
end
else begin
alx_frm_data_module.ADOConnection_SGC.RollbackTrans();
showmessage('a transação NÃO completou-se: O lançamento NÃO foi inserido no banco de dados! você deve reespecificá-lo novamente.');
end;
end;
//----------------
//... preparar mensagens e botões adequados à pos-transação (sucesso ou não...)
//----------------
except
on E:Exception do begin
showmessage('Ôpa, ocorreu um erro ao realizar a transação de inserção de nova receita com contas para rateio! Veja: ' + E.Message);
end;
end;
end;
//==============================================================================
function Talx_frm_sgc_lancamentos_receitas.alx_boo_Tarefa_1_Transacao_Realizada_Com_Sucesso(): Boolean;
var
alx_str_sql_text : TStrings;
alx_boo_apoio : Boolean;
alx_int_lan_id : Integer;
alx_dat_lan_data : TDate;
alx_int_lan_cn4_id : Integer;
alx_int_lan_cb_id : Integer;
alx_flo_lan_valor : Real;
alx_str_lan_doc : String;
alx_str_lan_obs : String;
alx_int_lan_user_id: Integer;
begin
try
alx_int_lan_id := self.alx_int_Pegar_Lancamentos_Novo_Id();
alx_dat_lan_data := strtodate(self.Edit3.Text);
alx_int_lan_cn4_id := strtoint(self.Edit1.Text);
alx_int_lan_cb_id := strtoint(self.Edit2.Text);
alx_flo_lan_valor := strtofloat(self.Edit6.Text);
alx_str_lan_doc := self.Edit4.Text;
alx_str_lan_obs := self.Edit5.Text;
alx_int_lan_user_id:= self.alx_int_user_id;
//--------------
alx_str_sql_text := TStringList.Create();
alx_str_sql_text.Add('INSERT INTO LANCAMENTOS VALUES (:, :, :, :, :, :, :, :, True) ; ');
self.ADOQuery_Apoio.Active:= False;
self.ADOQuery_Apoio.SQL.Clear();
self.ADOQuery_Apoio.SQL:= alx_str_sql_text;
self.ADOQuery_Apoio.Parameters[0].Value := alx_int_lan_id;
self.ADOQuery_Apoio.Parameters[1].DataType:= FTDate;
self.ADOQuery_Apoio.Parameters[1].Value := alx_dat_lan_data;
self.ADOQuery_Apoio.Parameters[2].Value := alx_int_lan_cn4_id;
self.ADOQuery_Apoio.Parameters[3].Value := alx_int_lan_cb_id;
self.ADOQuery_Apoio.Parameters[4].DataType:= FTFloat;
self.ADOQuery_Apoio.Parameters[4].Value := alx_flo_lan_valor;
self.ADOQuery_Apoio.Parameters[5].Value := alx_str_lan_doc;
self.ADOQuery_Apoio.Parameters[6].Value := alx_str_lan_obs;
self.ADOQuery_Apoio.Parameters[7].Value := alx_int_user_id;
//--------------
self.ADOQuery_Apoio.ExecSQL();
alx_boo_apoio:= True;
self.Edit10.Text:= inttostr(alx_int_lan_id); //... fornece o verdadeiro id do lançamento que foi inserido ...
//--------------
except
on E: Exception do begin
alx_boo_apoio:= False;
ShowMessage('Ôpa, ocorreu um erro ao realizar a Tarefa_1 da transação que insere um lançamento de receita! Veja: ' + E.Message);
end;
end;
result:= alx_boo_apoio;
end;
//==============================================================================
function Talx_frm_sgc_lancamentos_receitas.alx_boo_Tarefa_2_Transacao_Realizada_Com_Sucesso(): Boolean;
var
alx_int_i : Integer;
alx_int_rateio_lan_id : Integer;
alx_int_rateio_ae_id : Integer;
alx_flo_rateio_parcial: Real;
alx_boo_apoio : Boolean;
begin
try
alx_int_rateio_lan_id := strtoint(self.Edit10.Text);
for alx_int_i:= 0 to (self.alx_lst_lista_atividades.Count - 1) do begin
alx_int_rateio_ae_id := strtoint( (TObject(self.alx_lst_lista_atividades.Items[alx_int_i]) as TStrings).Strings[0] );
alx_flo_rateio_parcial:= strtofloat( (TObject(self.alx_lst_lista_atividades.Items[alx_int_i]) as TStrings).Strings[2] );
if (self.alx_boo_Tarefa_2_Transacao_Rateio_Inserido_Com_Sucesso(alx_int_rateio_lan_id, alx_int_rateio_ae_id, alx_flo_rateio_parcial)) then begin
alx_boo_apoio:= True;
end
else begin
alx_boo_apoio:= False;
break;
end;
end;
except
on E:Exception do begin
alx_boo_apoio:= False;
showmessage('Ôpa, ocorreu um erro ao preparar a Tarefa_2 da transação de lançamento de nova receita! Veja: ' + E.Message);
end;
end;
result:= alx_boo_apoio;
end;
//==============================================================================
function Talx_frm_sgc_lancamentos_receitas.alx_boo_Tarefa_2_Transacao_Rateio_Inserido_Com_Sucesso(alx_int_lan_id: Integer ; alx_int_atividade_id: Integer ; alx_flo_valor: Real ): Boolean;
var
alx_str_sql_text : TStrings;
alx_int_rateio_id: Integer;
alx_boo_apoio : Boolean;
begin
try
alx_int_rateio_id:= self.alx_int_Pegar_Rateios_Novo_Id();
alx_str_sql_text := TStringList.Create();
alx_str_sql_text.Add('INSERT INTO RATEIOS VALUES (:, :, :, :, True); ');
self.ADOQuery_Apoio.Active:= False;
self.ADOQuery_Apoio.SQL.Clear();
self.ADOQuery_Apoio.SQL:= alx_str_sql_text;
self.ADOQuery_Apoio.Parameters[0].Value := alx_int_rateio_id;
self.ADOQuery_Apoio.Parameters[1].Value := alx_int_lan_id;
self.ADOQuery_Apoio.Parameters[2].Value := alx_int_atividade_id;
self.ADOQuery_Apoio.Parameters[3].DataType:= FTFloat;
self.ADOQuery_Apoio.Parameters[3].Value := alx_flo_valor;
//--------------
self.ADOQuery_Apoio.ExecSQL();
alx_boo_apoio:= True;
//--------------
except
on E:Exception do begin
alx_boo_apoio:= False;
showmessage('Ôpa, ocorreu um erro ao inserir um registro em Rateios! Veja: ' + E.Message);
end;
end;
result:= alx_boo_apoio;
end;
//==============================================================================
function Talx_frm_sgc_lancamentos_receitas.alx_int_Pegar_Rateios_Novo_Id(): Integer;
var
alx_str_sql_text: TStrings;
alx_int_apoio : Integer;
begin
try
alx_str_sql_text:= TStringList.Create();
alx_str_sql_text.Add('SELECT MAX(RATEIO_ID) FROM RATEIOS ');
self.ADOQuery_Apoio.Active:= False;
self.ADOQuery_Apoio.SQL.Clear();
self.ADOQuery_Apoio.SQL:= alx_str_sql_text;
self.ADOQuery_Apoio.Active:= True;
//-----------------
alx_int_apoio:= self.ADOQuery_Apoio.Fields[0].AsInteger + 1;
self.ADOQuery_Apoio.Active:= False;
//-----------------
except
on E: Exception do begin
alx_int_apoio:= 0;
showmessage('Ôpa, ocorreu um erro ao buscar o novo código para um Rateio! Veja: ' + E.Message);
end;
end;
result:= alx_int_apoio;
end;
//==============================================================================

sexta-feira, 29 de junho de 2007

Rotina em DELPHI para inserção de Tuplas


O artefato de software abaixo descreve uma rotina de inserção de uma nova Turma na tabela de Turmas. Quando o usuário escolhe inserir uma nova Turma por meio de um botão adequado, a inserção de fato somente é confirmada se o sistema retorna um Boolean "Verdadeiro" para a operacção denominada "Tuma inserida com sucesso". Caso contrário, trata-se a exceção e mantém-se a interface para as devidos ajustes. Veja abaixo:

//------------------------------------------------------------------------------
function TF_Turmas.Alx_Turma_Inserido_Com_Sucesso(): Boolean;
var
alx_str_sql_texto : TStrings;
alx_boo_apoio : Boolean;
alx_int_turma_id : Integer;
alx_str_turma_apelido : String;
alx_str_turma_nome : String;
begin
alx_str_sql_texto:= TStringList.Create();
try
alx_int_turma_id := self.Alx_Get_Turma_Id();
alx_str_turma_apelido:= self.Edit2.Text;
alx_str_turma_nome := self.Edit3.Text;
//-----------------------------------------------
alx_str_sql_texto.Add('INSERT INTO TURMAS VALUES ( :, :, : ) ');
F_Data_Module.ADOQuery_Cadastro_Turmas.Active:= False;
F_Data_Module.ADOQuery_Cadastro_Turmas.SQL:= alx_str_sql_texto;
F_Data_Module.ADOQuery_Cadastro_Turmas.Parameters[0].Value:= alx_int_turma_id;
F_Data_Module.ADOQuery_Cadastro_Turmas.Parameters[1].Value:= alx_str_turma_apelido;
F_Data_Module.ADOQuery_Cadastro_Turmas.Parameters[2].Value:= alx_str_turma_nome;
F_Data_Module.ADOQuery_Cadastro_Turmas.ExecSQL;
//------------------------------------------------
alx_str_sql_texto.Clear();
alx_str_sql_texto.Add('SELECT * FROM TURMAS ORDER BY TURMA_NOME ');
F_Data_Module.ADOQuery_Cadastro_Turmas.SQL:= alx_str_sql_texto;
F_Data_Module.ADOQuery_Cadastro_Turmas.Active:= True;
//------------------------------------------------
self.Alx_Turma_Set_Focus(alx_int_turma_id);
self.Alx_Atualizar_Turma();
alx_boo_apoio:= True;
except
on E: Exception do
begin
alx_str_sql_texto.Clear();
alx_str_sql_texto.Add('SELECT * FROM TURMAS ORDER BY TURMA_NOME ');
F_Data_Module.ADOQuery_Cadastro_Turmas.SQL:= alx_str_sql_texto;
F_Data_Module.ADOQuery_Cadastro_Turmas.Active:= True;
self.Alx_Atualizar_Turma();
showmessage('Ôpa, ocorreu um erro ao INSERIR um novo Turma! Veja: ' + E.Message);
alx_boo_apoio:= False;
end;
end;
result:= alx_boo_apoio;
end;
//---------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------
procedure TF_Turmas.Alx_Preparar_Para_Inserir();
begin
if(self.BitBtn1.Caption = 'inserir') then
begin
self.Alx_Limpar_Caixas_Texto_Turma(); //...limpar as caixas de texto
self.Alx_Liberar_Componentes_Para_Insercao(True); //...libera o groupbox das caixas de texto
self.BitBtn1.Caption:= 'salvar';
end
else if( (self.BitBtn1.Caption = 'salvar') and (self.Alx_Turma_Inserido_Com_Sucesso()) ) then
begin
self.Alx_Liberar_Componentes_Para_Insercao(False);
self.BitBtn1.Caption:= 'inserir';
end;
end;
//------------------------------------------------------------------------------

A interface se Turmas é apresentada abaixo:

segunda-feira, 25 de junho de 2007

Rotina em DELPHI para Top 10 entre datas escolhidas do Sistema de Video Locadora

A rotina abaixo descreve os 10 clientes que realizaram as maiores quantidades de empréstimos, entre duas datas, no sistema de Video Locadora. Lembre-se que essa quantidade é diferente do maior número de DVD´s locados (empréstimos podem ter um ou vários DVD´s locados).
//===================================================================================
procedure TForm_consultas_top_10.Button1Click(Sender: TObject);
var
alx_str_sql_texto1: TStrings;
alx_dat_data_1 : Tdate;
alx_dat_data_2 : TDate;
begin
try
alx_dat_data_1:= strtodate(self.Edit2.Text);
alx_dat_data_2:= strtodate(self.Edit3.Text);
alx_str_sql_texto1:= TStringList.Create();
alx_str_sql_texto1.Add('SELECT TOP 10 Cli_Id, Cli_Nome, Count(EE_EMP_ID) ');
alx_str_sql_texto1.Add('FROM clientes, emprestimos, emprest_x_exemp ');
alx_str_sql_texto1.Add('WHERE Cli_id = Emp_Cli_Id_Titular And Emp_id = EE_EMP_ID and Emp_Data between : And : ');
alx_str_sql_texto1.Add('GROUP BY Cli_Id, Cli_Nome ');
alx_str_sql_texto1.Add('ORDER BY Count(EE_EMP_ID) DESC , CLI_NOME ; ');
self.ADOQuery1.Active:= False;
self.ADOQuery1.SQL.Clear();
self.ADOQuery1.SQL:= alx_str_sql_texto1;
self.ADOQuery1.Parameters[0].DataType:= FTDate;
self.ADOQuery1.Parameters[0].Value:= alx_dat_data_1;
self.ADOQuery1.Parameters[1].DataType:= FTDate;
self.ADOQuery1.Parameters[1].Value:= alx_dat_data_2;
self.ADOQuery1.Active:= True;
except
on E: Exception do begin
showmessage('Ôpa, ocorreu um erro ao Pesquisar o conjunto Top Ten! Veja: ' + E.Message );
end;
end;
end;
//===================================================================================

sexta-feira, 15 de junho de 2007

Rotina em DELPHI para localizar nomes de Clientes em um dado DBGrid

A procedure abaixo deve ser solicitada no evento "OnKeyUp" do Edit utilizado para fazer a pesquisa de localização. Então, cada vez que um usuário digita uma tecla e solta-a, é disparado o evento que chama a procedure
"alx_voi_Localizar_Clientes()". O grid associado ao componente "ADOQuery_Clientes"
é preenchido com os clientes que satisfazem o critério de pesquisa e localização.
É isso, simples e eficiente...:)

//===========================================================================
procedure Tfrm_clientes.alx_voi_Localizar_Clientes();
var
alx_str_sql_texto: TStrings;
alx_str_prefixo : String;
begin
try
alx_str_prefixo:= self.Edit1.Text + '%'; //... utilizando o curinga "%" como sufixo de pesquisa ...
alx_str_sql_texto:= TStringList.Create();
alx_str_sql_texto.Add('SELECT CLI_ID , CLI_NOME , CLI_CPF , CLI_FONE , CLI_ENDERECO , CLI_CITY_ID , ');
alx_str_sql_texto.Add(' CITY_NOME , UF_SIGLA , CLI_NIVER , CLI_FUNC_ID , FUNC_APELIDO ');
alx_str_sql_texto.Add('FROM CLIENTES , CIDADES , UNIDADES_FEDERACAO , FUNCIONARIOS ');
alx_str_sql_texto.Add('WHERE CLI_CITY_ID = CITY_ID AND CITY_UF_ID = UF_ID AND CLI_FUNC_ID = FUNC_ID ');
alx_str_sql_texto.Add(' AND CLI_NOME LIKE : ');
alx_str_sql_texto.Add('ORDER BY CLI_NOME ; ');
self.ADOQuery_Clientes.Active:= False;
self.ADOQuery_Clientes.SQL.Clear();
self.ADOQuery_Clientes.SQL:= alx_str_sql_texto;
self.ADOQuery_Clientes.Parameters[0].Value:= sl_str_prefixo;
self.ADOQuery_Clientes.Active:= True;
except
on E: Exception do begin
showmessage('Ôpa, ocorreu um erro ao Pesquisar o conjunto de CLIENTES! Veja: ' + E.Message );
end;
end;
end;
//==============================================================================
//==============================================================================

domingo, 10 de junho de 2007

Rotinas em DELPHI para Popular um ComboBox


Esta postagem tem duplo objetivo:
(i) Mostar como se pode popular um combobox com valores buscados de um banco de dados;
(ii)Mostar como se pode buscar um código "id" em um banco de dados a partir de um nome selecionado previamente em um componente "ComboBox".

Os componentes "TEdit´s" que receberão os "Id´s" e os componentes "TComboBox´s" estão descritos na figura abaixo.



São apresentados métodos específicos para buscar um código "Id" de uma dada conta escolhida pelo usuário ao selecionar um item de um combobox básico.

Primeiro evento: O usuário seleciona um item de um combobox;
Segundo evento : Ao selecionar uma conta, coloca-se o valor do "Id" em um edit específico Para tanto, acessa-se o banco de dados e busca-se o "id" pelo nome selecionado.


Veja o corpo das functions abaixo na seção "implementation":
function alx_int_Pegar_Conta_Bancaria_Id(alx_str_conta_bancaria_nome: String): Integer;
function alx_int_Pegar_Conta_Nivel_4_Id(alx_str_conta_nivel_4_nome: String): Integer;


unit Unit_SGC_Lancamentos_Receitas;

interface

uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, ComCtrls, Grids, DBGrids, DB, ADODB, Unit_SGC_Data_Module;

type
Talx_frm_sgc_lancamentos_receitas = class(TForm)

StatusBar1: TStatusBar; Panel1: TPanel; BitBtn1: TBitBtn; GroupBox1: TGroupBox; ComboBox1: TComboBox; Edit1: TEdit; Label1: TLabel; ComboBox2: TComboBox; Label2: TLabel; Edit2: TEdit; Edit3: TEdit; Label3: TLabel; Edit4: TEdit; Label4: TLabel; Edit5: TEdit; Label5: TLabel; Edit6: TEdit; Label6: TLabel; Panel3: TPanel; DBGrid1: TDBGrid; GroupBox2: TGroupBox; Edit7: TEdit; BitBtn2: TBitBtn; BitBtn3: TBitBtn; RadioGroup1: TRadioGroup; RadioButton1: TRadioButton; RadioButton2: TRadioButton; Edit8: TEdit; ADOQuery_Rateios: TADOQuery; DataSource_Rateios: TDataSource; ADOQuery_Atividades_Extensao: TADOQuery; DataSource_Atividades_Extensao: TDataSource; ADOQuery_Apoio: TADOQuery; GroupBox3: TGroupBox; DBGrid_Atividades_Extensao: TDBGrid; Edit9: TEdit; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure RadioButton2Click(Sender: TObject); procedure RadioButton1Click(Sender: TObject); procedure BitBtn1Click(Sender: TObject); procedure BitBtn3Click(Sender: TObject); procedure DBGrid_Atividades_ExtensaoCellClick(Column: TColumn); procedure DBGrid_Atividades_ExtensaoKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);

procedure ComboBox1Select(Sender: TObject);
procedure ComboBox2Select(Sender: TObject);

private
{ Private declarations }
alx_str_user_nome : String;
alx_int_user_na_id: Integer;
//-------
function alx_int_Pegar_Conta_Bancaria_Id(alx_str_conta_bancaria_nome: String): Integer;
function alx_int_Pegar_Conta_Nivel_4_Id(alx_str_conta_nivel_4_nome: String): Integer;
//-------
procedure alx_voi_Atualizar_Cartao_Atividades_Extensao();
procedure alx_voi_Definir_Data_Lancamento_Receita();
procedure alx_voi_Popular_Contas_Bancarias_ComboBox();
procedure alx_voi_Popular_Contas_Nivel_4_ComboBox();
procedure alx_voi_Popular_Grid_Atividades_Extensao();
procedure alx_voi_Rateio_Preparar_Para_Digitar_Valor();
procedure alx_voi_Rateio_Preparar_Para_Calcular_Automaticamente();
procedure alx_voi_Registrar_Entrada_Usuario(alx_str_nome: String ; alx_int_na_id: Integer);
procedure alx_voi_Registrar_Status_Bar_Usuario();

public
{ Public declarations }
constructor alx_voi_Create(alx_obj_owner: TComponent ; alx_str_user_name: String ; alx_int_nivel_acesso_id: Integer);
destructor alx_voi_Destroy();
end;

implementation

{$R *.dfm}

//==============================================================================
function Talx_frm_sgc_lancamentos_receitas.alx_int_Pegar_Conta_Bancaria_Id(alx_str_conta_bancaria_nome: String): Integer;
var
alx_str_sql_text: TStrings; alx_int_apoio : Integer;
begin
try
alx_str_sql_text:= TStringList.Create();
alx_str_sql_text.Add('SELECT CB_ID FROM CONTAS_BANCARIAS WHERE CB_NOME = : ');
self.ADOQuery_Apoio.Active:= False;
self.ADOQuery_Apoio.SQL.Clear();
self.ADOQuery_Apoio.SQL:= alx_str_sql_text;
self.ADOQuery_Apoio.Parameters[0].Value:= alx_str_conta_bancaria_nome;
self.ADOQuery_Apoio.Active:= True;
//-----------------
alx_int_apoio:= self.ADOQuery_Apoio.Fields[0].AsInteger;
self.ADOQuery_Apoio.Active:= False;
//-----------------
except
on E: Exception do begin
alx_int_apoio:= 0;
showmessage('Ôpa, ocorreu um erro ao buscar o código para uma Contas de Nível 4 de nome conhecido! Veja: ' + E.Message);
end;
end;
result:= alx_int_apoio;
end;
//==============================================================================
function Talx_frm_sgc_lancamentos_receitas.alx_int_Pegar_Conta_Nivel_4_Id(alx_str_conta_nivel_4_nome: String): Integer;
var
alx_str_sql_text: TStrings; alx_int_apoio : Integer;
begin
try
alx_str_sql_text:= TStringList.Create();
alx_str_sql_text.Add('SELECT CN4_ID FROM CONTAS_NIVEL_4 WHERE CN4_NOME = : ');
self.ADOQuery_Apoio.Active:= False;
self.ADOQuery_Apoio.SQL.Clear();
self.ADOQuery_Apoio.SQL:= alx_str_sql_text;
self.ADOQuery_Apoio.Parameters[0].Value:= alx_str_conta_nivel_4_nome;
self.ADOQuery_Apoio.Active:= True;
//-----------------
alx_int_apoio:= self.ADOQuery_Apoio.Fields[0].AsInteger;
self.ADOQuery_Apoio.Active:= False;
//-----------------
except
on E: Exception do begin
alx_int_apoio:= 0;
showmessage('Ôpa, ocorreu um erro ao buscar o código para uma Contas de Nível 4 de nome conhecido! Veja: ' + E.Message);
end;
end;
result:= alx_int_apoio;
end;
//==============================================================================
procedure Talx_frm_sgc_lancamentos_receitas.ComboBox1Select( Sender: TObject);
begin
self.Edit1.Text:= inttostr(self.alx_int_Pegar_Conta_Bancaria_Id(self.ComboBox1.Text));
end;
//==============================================================================
procedure Talx_frm_sgc_lancamentos_receitas.ComboBox2Select(Sender: TObject);
begin
self.Edit2.Text:= inttostr(self.alx_int_Pegar_Conta_Nivel_4_Id(self.ComboBox2.Text));
end;
//==============================================================================
procedure Talx_frm_sgc_lancamentos_receitas.alx_voi_Popular_Contas_Bancarias_ComboBox();
var
alx_str_sql_text: TStrings;
begin
try
alx_str_sql_text:= TStringList.Create();
alx_str_sql_text.Add('SELECT CB_NOME FROM CONTAS_BANCARIAS WHERE CB_ATIVO = TRUE ORDER BY CB_NOME ;');
self.ADOQuery_Apoio.Active:= False;
self.ADOQuery_Apoio.SQL.Clear();
self.ADOQuery_Apoio.SQL:= alx_str_sql_text;
self.ADOQuery_Apoio.Active:= True;
//-----------------
self.ComboBox1.Items.Clear();
while not(self.ADOQuery_Apoio.Eof) do begin
self.ComboBox1.Items.Add(self.ADOQuery_Apoio.Fields[0].AsString);
self.ADOQuery_Apoio.Next();
end;
self.ComboBox1.Text:= 'escolha uma conta bancária';
self.Edit1.Text:= '';
//-----------------
self.ADOQuery_Apoio.Active:= False;
//-----------------
except
on E: Exception do begin
showmessage('Ôpa, ocorreu um erro ao popular o combo de Contas Bancárias! Veja: ' + E.Message);
end;
end;
end;
//==============================================================================
procedure Talx_frm_sgc_lancamentos_receitas.alx_voi_Popular_Contas_Nivel_4_ComboBox();
var
alx_str_sql_text: TStrings;
begin
try
alx_str_sql_text:= TStringList.Create();
alx_str_sql_text.Add('SELECT CN4_NOME '); alx_str_sql_text.Add('FROM CONTAS_NIVEL_4 , CONTAS_NIVEL_3 , CONTAS_NIVEL_2 , CONTAS_NIVEL_1 ');
alx_str_sql_text.Add('WHERE CN4_CN3_ID = CN3_ID AND CN3_CN2_ID = CN2_ID AND ');
alx_str_sql_text.Add(' CN2_CN1_ID = CN1_ID AND CN1_ID = 4 AND CN4_ATIVO = TRUE ');
alx_str_sql_text.Add('ORDER BY CN4_NOME ; ');
self.ADOQuery_Apoio.Active:= False;
self.ADOQuery_Apoio.SQL.Clear();
self.ADOQuery_Apoio.SQL:= alx_str_sql_text;
self.ADOQuery_Apoio.Active:= True;
//-----------------
self.ComboBox2.Items.Clear();
while not(self.ADOQuery_Apoio.Eof) do begin
self.ComboBox2.Items.Add(self.ADOQuery_Apoio.Fields[0].AsString);
self.ADOQuery_Apoio.Next();
end;
self.ComboBox2.Text:= 'escolha uma conta de nível 4 para o lançamento';
self.Edit2.Text:= '';
//-----------------
self.ADOQuery_Apoio.Active:= False;
//-----------------
except
on E: Exception do begin
showmessage('Ôpa, ocorreu um erro ao popular o combo de Contas de Nível 4! Veja: ' + E.Message);
end;
end;
end;
//==============================================================================
end.

quinta-feira, 7 de junho de 2007

Rotinas em DELPHI para um Painel Central Completo


A Unit "Unit_SGC_Painel_Central" controla a interface descrita na figura abaixo.


Como características principais tem-se:

Entrada Lógica no sistema;

Saída Lógica do sistema;

Ao saír, todos os formulários que estão criados serão automáticamente destruídos, para que um novo usuário possa logar-se e fazer uso do sistema conforme o seu perfil (dado pelo nível de acesso);

Uma série de controle são efetuados no processo de entrada e de saída lógica do sistema;
A seguir é apresentada a referida Unit.

unit Unit_SGC_Painel_Central;
interface

uses

Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, Menus, ComCtrls, jpeg, DB, ADODB, Unit_SGC_Data_Module;

type

Talx_frm_painel_central = class(TForm)

StatusBar1: TStatusBar; MainMenu1: TMainMenu; Saturno1: TMenuItem; Sair1: TMenuItem; Login1: TMenuItem; Configuraes1: TMenuItem; BancodeDados1: TMenuItem; Usurios1: TMenuItem; Sobre1: TMenuItem; AlexS1: TMenuItem; Relatrios1: TMenuItem; Panel1: TPanel; GroupBox1: TGroupBox; Panel2: TPanel; BitBtn1: TBitBtn; BitBtn2: TBitBtn; BitBtn3: TBitBtn; BitBtn4: TBitBtn; BitBtn5: TBitBtn; BitBtn6: TBitBtn; BitBtn7: TBitBtn; BitBtn8: TBitBtn; BitBtn9: TBitBtn; BitBtn10: TBitBtn; BitBtn11: TBitBtn; BitBtn12: TBitBtn; BitBtn13: TBitBtn; BitBtn14: TBitBtn; Panel3: TPanel; GroupBox2: TGroupBox; Edit1: TEdit; Edit2: TEdit; BitBtn15: TBitBtn; Label1: TLabel; Label2: TLabel; ADOQuery_SGC_Login: TADOQuery; Usurios2: TMenuItem; FilosofiadaAlexS1: TMenuItem; Manuteno1: TMenuItem; Image2: TImage;

procedure BitBtn1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);

procedure Sair1Click(Sender: TObject);
procedure BitBtn15Click(Sender: TObject);
procedure BitBtn2Click(Sender: TObject);
procedure BitBtn11Click(Sender: TObject);

procedure BitBtn6Click(Sender: TObject);

private
{ Private declarations }
//----------------
alx_str_user_nome : String;
alx_int_user_na_id : Integer;
alx_int_componentes_iniciais: Integer;
//----------------
function alx_boo_Usuario_Existe(alx_str_user_apelido_digitado: String): Boolean;
function alx_boo_Senha_Ok(alx_str_user_apelido_digitado: String ;
alx_str_senha_digitada: String): Boolean;
//----------------
procedure alx_voi_Habilitar_Botoes(alx_boo_liberar: Boolean);
procedure alx_voi_Habilitar_Menus(alx_boo_liberar: Boolean);
procedure alx_voi_Preparar_Form_Caso_Entrada_Logica();
procedure alx_voi_Preparar_Form_Caso_Saida_Logica();
procedure alx_voi_Preparar_Form_Caso_Usuario_E_Senha_Ok();
procedure alx_voi_Preparar_Form_Caso_Usuario_Ok_Senha_Errada();
procedure alx_voi_Preparar_Form_Caso_Usuario_Nao_Existe();
procedure alx_voi_Registrar_Entrada_Usuario(alx_str_nome: String ; alx_int_na_id: Integer);
procedure alx_voi_Registrar_Status_Bar_Usuario();
procedure alx_voi_Destruir_Todos_Os_Forms_Criados();
//----------------
public
{ Public declarations }
end;

var
alx_frm_painel_central: Talx_frm_painel_central;

implementation

uses Unit_SGC_Lancamentos_Receitas;

{$R *.dfm}

//============================================================================== procedure Talx_frm_painel_central.alx_voi_Destruir_Todos_Os_Forms_Criados();
begin
while (Application.ComponentCount > self.alx_int_componentes_iniciais) do begin
Application.Components[Application.ComponentCount - 1].Destroy;
end;
end;
//============================================================================== procedure Talx_frm_painel_central.alx_voi_Registrar_Entrada_Usuario(alx_str_nome: String ; alx_int_na_id: Integer);
begin
self.alx_str_user_nome := alx_str_nome;
self.alx_int_user_na_id:= alx_int_na_id;
end;
//============================================================================== procedure Talx_frm_painel_central.alx_voi_Registrar_Status_Bar_Usuario();
begin
self.StatusBar1.Panels[0].Text:= ' Usuário: ' + self.alx_str_user_nome;
self.StatusBar1.Panels[1].Text:= ' Nível de Acesso: ' + inttostr(self.alx_int_user_na_id);
end;
//============================================================================== function Talx_frm_painel_central.alx_boo_Usuario_Existe(alx_str_user_apelido_digitado: String): Boolean;
var
alx_str_sql_text : TStrings;
alx_boo_usuario_existe: Boolean;
alx_str_user_apelido : String;
begin
try
alx_str_sql_text:= TStringList.Create();
alx_str_sql_text.Add('SELECT USER_APELIDO FROM USERS ORDER BY USER_APELIDO ;');
self.ADOQuery_SGC_Login.Active:= False;
self.ADOQuery_SGC_Login.SQL.Clear();
self.ADOQuery_SGC_Login.SQL:= alx_str_sql_text;
self.ADOQuery_SGC_Login.Active:= True;
//------------
while not(self.ADOQuery_SGC_Login.Eof) do begin
alx_str_user_apelido:= self.ADOQuery_SGC_Login.Fields[0].AsString;
if (alx_str_user_apelido = alx_str_user_apelido_digitado ) then begin
alx_boo_usuario_existe:= true; break;
end
else begin
alx_boo_usuario_existe:= false;
end;
self.ADOQuery_SGC_Login.Next();
end;
//------------
except
on E:Exception do begin
ShowMessage('Ôpa, ocorreu um erro ao verificar a existência de um usuário! Veja: ' + E.Message);
end;
end;
result:= alx_boo_usuario_existe;
end;
//============================================================================== function Talx_frm_painel_central.alx_boo_Senha_Ok(alx_str_user_apelido_digitado: String ; alx_str_senha_digitada: String): Boolean;
var
alx_str_sql_text : TStrings;
alx_boo_senha_ok : Boolean;
alx_str_user_apelido : String;
alx_str_user_senha : String;
alx_int_na_id : Integer;
begin
try
alx_str_sql_text:= TStringList.Create();
alx_str_sql_text.Add('SELECT USER_APELIDO , USER_SENHA , USER_NA_ID FROM USERS ORDER BY USER_APELIDO ;');
self.ADOQuery_SGC_Login.Active:= False;
self.ADOQuery_SGC_Login.SQL.Clear();
self.ADOQuery_SGC_Login.SQL:= alx_str_sql_text;
self.ADOQuery_SGC_Login.Active:= True;
//------------
while not(self.ADOQuery_SGC_Login.Eof) do begin
alx_str_user_apelido:= self.ADOQuery_SGC_Login.Fields[0].AsString;
alx_str_user_senha := self.ADOQuery_SGC_Login.Fields[1].AsString;
alx_int_na_id := self.ADOQuery_SGC_Login.Fields[2].AsInteger;
if ((alx_str_user_apelido = alx_str_user_apelido_digitado) and (alx_str_user_senha = alx_str_senha_digitada) ) then begin
self.alx_voi_Registrar_Entrada_Usuario(alx_str_user_apelido , alx_int_na_id );
alx_boo_senha_ok:= true;
break;
end
else begin
alx_boo_senha_ok:= false;
end;
self.ADOQuery_SGC_Login.Next();
end;
//------------
except
on E:Exception do begin
ShowMessage('Ôpa, ocorreu um erro ao verificar a senha de um usuário! Veja: ' + E.Message);
end;
end;
result:= alx_boo_senha_ok;
end;
//============================================================================== procedure Talx_frm_painel_central.alx_voi_Preparar_Form_Caso_Usuario_E_Senha_Ok();
begin
self.alx_int_componentes_iniciais:= Application.ComponentCount;
self.Edit1.Color := clAqua;
self.Edit1.ReadOnly := True;
self.Edit2.Color := clAqua;
self.Edit2.ReadOnly := True;
self.Edit2.Text := 'edit2'; //... modifica o valor da senha ...
self.BitBtn15.Caption := 'saída lógica';
//-------------------
self.alx_voi_Habilitar_Botoes(True);
self.alx_voi_Habilitar_Menus(True);
self.alx_voi_Registrar_Status_Bar_Usuario();
end;
//============================================================================== procedure Talx_frm_painel_central.alx_voi_Preparar_Form_Caso_Usuario_Ok_Senha_Errada();
begin
self.Edit1.Color:= clGray;
self.Edit2.Color:= clYellow;
self.Edit2.SetFocus();
ShowMessage('ôpa, a senha do usuário [' + self.Edit1.Text + '] NÃO confere!' );
//-------------------
self.alx_voi_Habilitar_Botoes(False);
self.alx_voi_Habilitar_Menus(False);
end;
//============================================================================== procedure Talx_frm_painel_central.alx_voi_Preparar_Form_Caso_Usuario_Nao_Existe();
begin
self.Edit1.Color:= clRed; self.Edit1.SetFocus();
showmessage('ôpa, o usuário [' + self.Edit1.Text + '] NÃO existe!');
//-------------------
self.alx_voi_Habilitar_Botoes(False);
self.alx_voi_Habilitar_Menus(False);

end;
//==============================================================================

procedure Talx_frm_painel_central.alx_voi_Preparar_Form_Caso_Entrada_Logica();
begin
if (self.BitBtn15.Caption = 'entrada lógica') then begin
if(self.alx_boo_Usuario_Existe(self.Edit1.Text)) then begin
if(self.alx_boo_Senha_Ok(self.Edit1.Text , self.Edit2.Text)) then begin
self.alx_voi_Preparar_Form_Caso_Usuario_E_Senha_Ok();
end
else begin
self.alx_voi_Preparar_Form_Caso_Usuario_Ok_Senha_Errada();
end;
end
else begin
self.alx_voi_Preparar_Form_Caso_Usuario_Nao_Existe();
end;
end
else if(self.BitBtn15.Caption = 'saída lógica') then begin
self.alx_voi_Preparar_Form_Caso_Saida_Logica();
end;
end;
//============================================================================== procedure Talx_frm_painel_central.alx_voi_Preparar_Form_Caso_Saida_Logica();
begin
self.Edit1.Text:= 'digite o nome';
self.Edit1.ReadOnly:= False;
self.Edit1.Color:= clWhite;
self.Edit2.Text:= 'edit2';
self.Edit2.ReadOnly:= False;
self.Edit2.Color:= clWhite;
self.BitBtn15.Caption:= 'entrada lógica';
//-------------------
self.alx_voi_Destruir_Todos_Os_Forms_Criados();
self.alx_voi_Habilitar_Botoes(False);
self.alx_voi_Habilitar_Menus(False);
end;
//============================================================================== procedure Talx_frm_painel_central.alx_voi_Habilitar_Botoes(alx_boo_liberar: Boolean);
begin
self.BitBtn1.Enabled := True;
self.BitBtn2.Enabled := alx_boo_liberar;
self.BitBtn3.Enabled := alx_boo_liberar;
self.BitBtn4.Enabled := alx_boo_liberar;
self.BitBtn5.Enabled := alx_boo_liberar;
self.BitBtn6.Enabled := alx_boo_liberar;
self.BitBtn7.Enabled := alx_boo_liberar;
self.BitBtn8.Enabled := alx_boo_liberar;
self.BitBtn9.Enabled := alx_boo_liberar;
self.BitBtn10.Enabled:= alx_boo_liberar;
self.BitBtn11.Enabled:= alx_boo_liberar;
self.BitBtn12.Enabled:= alx_boo_liberar;
self.BitBtn13.Enabled:= alx_boo_liberar;
self.BitBtn14.Enabled:= alx_boo_liberar;
self.BitBtn15.Enabled:= True;
end;
//============================================================================== procedure Talx_frm_painel_central.alx_voi_Habilitar_Menus(alx_boo_liberar: Boolean);
begin
self.MainMenu1.Items[0].Items[0].Enabled:= True;
self.MainMenu1.Items[0].Items[1].Enabled:= alx_boo_liberar;
self.MainMenu1.Items[0].Items[2].Enabled:= alx_boo_liberar;
//------------
self.MainMenu1.Items[1].Items[0].Enabled:= alx_boo_liberar;
//------------
self.MainMenu1.Items[2].Items[0].Enabled:= True;
self.MainMenu1.Items[2].Items[1].Enabled:= True;
self.MainMenu1.Items[2].Items[2].Enabled:= True;
//------------
self.MainMenu1.Items[3].Items[0].Enabled:= alx_boo_liberar;
end;
//==============================================================================

//============================================================================== procedure Talx_frm_painel_central.BitBtn1Click(Sender: TObject);
begin
self.Close();
end;
//==================================================================== procedure Talx_frm_painel_central.FormCreate(Sender: TObject);
begin
self.alx_voi_Habilitar_Botoes(False);
self.alx_voi_Habilitar_Menus(False);
end;
//================================================================== procedure Talx_frm_painel_central.Sair1Click(Sender: TObject);
begin
self.Close();
end;
//================================================================== procedure Talx_frm_painel_central.BitBtn15Click(Sender: TObject);
begin
self.alx_voi_Preparar_Form_Caso_Entrada_Logica();
end;
//================================================================== procedure Talx_frm_painel_central.BitBtn2Click(Sender: TObject);
var
alx_frm_lancamentos_receitas: Talx_frm_sgc_lancamentos_receitas;
begin
alx_frm_lancamentos_receitas:= Talx_frm_sgc_lancamentos_receitas.alx_voi_Create(Application);
end;
//================================================================== procedure Talx_frm_painel_central.BitBtn11Click(Sender: TObject);
var
alx_int_count: Integer;
begin

alx_int_count:= Application.ComponentCount;
showmessage('Contagem de formulários: [' + inttostr(alx_int_count) + ']');
end;
//================================================================== procedure Talx_frm_painel_central.BitBtn6Click(Sender: TObject);
begin
self.alx_voi_Destruir_Todos_Os_Forms_Criados();
end;
//================================================================== end.

sexta-feira, 1 de junho de 2007

Rotina em DELPHI para Popular Grid de Atores no Sistema SVL

unit Unit_alx_atores;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, Grids, DBGrids, ComCtrls, jpeg, ExtCtrls, DB,
ADODB, Unit_alx_DataModule;

type
Tfrm_alx_atores = class(TForm)
Panel1: TPanel;
Image1: TImage;
Panel2: TPanel;
StatusBar1: TStatusBar;
DBGrid1: TDBGrid;
Edit1: TEdit;
Edit2: TEdit;
Panel3: TPanel;
BitBtn1: TBitBtn;
BitBtn2: TBitBtn;
BitBtn3: TBitBtn;
BitBtn4: TBitBtn;
BitBtn5: TBitBtn;
ID: TLabel;
Nome: TLabel;
ADOQuery1: TADOQuery;
DataSource1: TDataSource;
BitBtn6: TBitBtn;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure DBGrid1CellClick(Column: TColumn);
procedure DBGrid1KeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure BitBtn6Click(Sender: TObject);
private
{ Private declarations }
procedure alx_voi_Popular_Grid_Atores();
procedure alx_voi_Atualizar_Cartao_Atores();
public
{ Public declarations }
constructor alx_voi_Create(alx_obj_owner: TComponent);

end;



implementation

{$R *.dfm}

//==============================================================================
constructor Tfrm_alx_atores.alx_voi_Create(alx_obj_owner: TComponent);
begin
inherited Create(alx_obj_owner);
self.alx_voi_Popular_Grid_Atores(); //... POPULAR O GRID DE ATORES ...
self.alx_voi_Atualizar_Cartao_Atores(); //... atualizar o cartão de atores...
self.Show();
end;
//==============================================================================
procedure Tfrm_alx_atores.alx_voi_Popular_Grid_Atores();
var
alx_str_sql_texto: TStrings;
begin
try
alx_str_sql_texto:= TStringList.Create();
alx_str_sql_texto.Add('SELECT * FROM ATORES ORDER BY ATOR_NOME ;');
self.ADOQuery1.Active:= False;
self.ADOQuery1.SQL.Clear();
self.ADOQuery1.SQL:= alx_str_sql_texto;
self.ADOQuery1.Active:= True;
except
on E: Exception do begin
showmessage('Ôpa, ocorreu um erro ao popular o grid de atores! VEja: ' + E.Message );
end;
end;
end;
//==============================================================================
procedure Tfrm_alx_atores.alx_voi_Atualizar_Cartao_Atores();
begin
try
self.Edit1.Text:= self.ADOQuery1.Fields[0].AsString;
self.Edit2.Text:= self.ADOQuery1.Fields[1].AsString;
except
on E: Exception do begin
showmessage('Ôpa, ocorreu um erro ao atualizar o cartão de atores! VEja: ' + E.Message );
end;
end;
end;
//==============================================================================
procedure Tfrm_alx_atores.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
SELF:= NIL;
end;

procedure Tfrm_alx_atores.DBGrid1CellClick(Column: TColumn);
begin
self.alx_voi_Atualizar_Cartao_Atores();
end;

procedure Tfrm_alx_atores.DBGrid1KeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
self.alx_voi_Atualizar_Cartao_Atores();
end;

procedure Tfrm_alx_atores.BitBtn6Click(Sender: TObject);
begin
self.ADOQuery1.Next();
self.alx_voi_Atualizar_Cartao_Atores();
end;

end.

domingo, 27 de maio de 2007

Sistema Impactômetro desenvolvido em Java:



Neste sistema foi desenvolvido em Java um componente específico para renderizar todo o grafismo utilizado para descrever a variação da qualidade da água de um dado recurso natural.



sábado, 26 de maio de 2007

Rotina em DELPHI para Validar CPF e CNPJ


Esta "unit" tem a finalidade de testar o valor de um CPF digitado por um usuário
em uma interface adequada, conforme a figura ao lado.





















unit Unit_CPF_Painel_Central;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, Buttons, jpeg;
type
TFrm_CPF_Painel_Central = class(TForm)
GroupBox1: TGroupBox;
Edit1: TEdit;
Label1: TLabel;
BitBtn1: TBitBtn;
BitBtn2: TBitBtn;
Panel1: TPanel;
GroupBox2: TGroupBox;
Edit2: TEdit;
BitBtn3: TBitBtn;
BitBtn4: TBitBtn;
GroupBox3: TGroupBox;
Edit3: TEdit;
Label2: TLabel;
Label3: TLabel;
BitBtn5: TBitBtn;
Button1: TButton;
Memo1: TMemo;
Panel2: TPanel;
BitBtn6: TBitBtn;
Image1: TImage;
//===============
procedure BitBtn6Click(Sender: TObject);
procedure BitBtn1Click(Sender: TObject);
procedure BitBtn2Click(Sender: TObject);
//===============
private
{ Private declarations }
function alx_boo_CPF_Validado(alx_str_cpf_digitado: String) : Boolean;
function alx_boo_CNPJ_Validado(alx_str_cnpj_digitado: String): Boolean;
//===============
public
{ Public declarations }
end;

var
Frm_CPF_Painel_Central: TFrm_CPF_Painel_Central;

implementation

{$R *.dfm}
//==============================================================================
function TFrm_CPF_Painel_Central.alx_boo_CPF_Validado(alx_str_cpf_digitado: String): Boolean;
var
alx_int_position : Array [1..11] of Integer;
alx_int_controle_d1 : Integer; alx_int_controle_d2 : Integer;
alx_str_controle_1 : String; alx_str_controle_2 : String;
alx_boo_apoio : Boolean; alx_int_i : Integer;
alx_int_j : Integer;
begin
try
alx_int_controle_d1:= 0;
alx_int_controle_d2:= 0;
if (System.Length(alx_str_cpf_digitado) = 11) then begin
for alx_int_i:= 1 to 9 do begin
alx_int_position[alx_int_i]:= strtoint(alx_str_cpf_digitado [alx_int_i]);
alx_int_controle_d1:= alx_int_controle_d1 + alx_int_position[alx_int_i]*(11 - alx_int_i)
end;
alx_int_position[10]:= strtoint(alx_str_cpf_digitado[10]);
alx_int_position[11]:= strtoint(alx_str_cpf_digitado[11]);
//------------------
alx_int_controle_d1:= 11 - (alx_int_controle_d1 mod 11);
if(alx_int_controle_d1 >= 10) then begin
alx_int_controle_d1:= 0;
end;
for alx_int_j:= 1 to 9 do begin
alx_int_controle_d2:= alx_int_controle_d2 + alx_int_position[alx_int_j]*(12 - alx_int_j);
end;
alx_int_controle_d2:= alx_int_controle_d2 + alx_int_controle_d1*(2);
alx_int_controle_d2:= 11 - (alx_int_controle_d2 mod 11);
if(alx_int_controle_d2 >= 10) then begin
alx_int_controle_d2:= 0;
end;
//-------------------
alx_str_controle_1:= inttostr(alx_int_controle_d1) + inttostr(alx_int_controle_d2);
alx_str_controle_2:= alx_str_cpf_digitado[10] + alx_str_cpf_digitado[11];
//-------------------
if(alx_str_controle_1 = alx_str_controle_2) then begin
alx_boo_apoio:= true;
end
else begin
alx_boo_apoio:= false;
end;
//--------------------
end
else begin
self.Edit1.SetFocus();
showmessage('Você apresentou um CPF com [' + inttostr(System.Length(alx_str_cpf_digitado)) + '] digitos. Digite o CPF com 11 números! ');
alx_boo_apoio:= false;
end;
except
on E: Exception do begin
self.Edit1.SetFocus();
showmessage('Digite o CPF com 11 dígitos numéricos! Veja: ' + E.Message);
alx_boo_apoio:= false;
end;
end;
result:= alx_boo_apoio;
end;
//==============================================================================
function TFrm_CPF_Painel_Central.alx_boo_CNPJ_Validado(alx_str_cnpj_digitado: String): Boolean;
var
alx_int_position : Array [1..14] of Integer;
alx_int_controle_d1 : Integer;
alx_int_controle_d2 : Integer;
alx_str_controle_1 : String;
alx_str_controle_2 : String;
alx_boo_apoio : Boolean;
alx_int_i : Integer;
alx_int_j : Integer;
begin
try
alx_int_controle_d1:= 0;
alx_int_controle_d2:= 0;
if (System.Length(alx_str_cnpj_digitado) = 14) then begin
for alx_int_i:= 1 to 12 do begin
alx_int_position[alx_int_i]:= strtoint(alx_str_cnpj_digitado[alx_int_i]);
end;
alx_int_position[13]:= strtoint(alx_str_cnpj_digitado[13]);
alx_int_position[14]:= strtoint(alx_str_cnpj_digitado[14]);
//------------------
alx_int_controle_d1:= alx_int_position[1]*(5) + alx_int_position[2]*(4) + alx_int_position[3]*(3) + alx_int_position[4]*(2);
alx_int_controle_d1:= alx_int_controle_d1 + alx_int_position[5]*(9) + alx_int_position[6]*(8) + alx_int_position[7]*(7);
alx_int_controle_d1:= alx_int_controle_d1 + alx_int_position[8]*(6) + alx_int_position[9]*(5) + alx_int_position[10]*(4);
alx_int_controle_d1:= alx_int_controle_d1 + alx_int_position[11]*(3) + alx_int_position[12]*(2);
//------------------
alx_int_controle_d1:= 11 - (alx_int_controle_d1 mod 11);
if(alx_int_controle_d1 >= 10) then begin
alx_int_controle_d1:= 0;
end;
//------------------
alx_int_controle_d2:= alx_int_position[1]*(6) + alx_int_position[2]*(5) + alx_int_position[3]*(4) + alx_int_position[4]*(3);
alx_int_controle_d2:= alx_int_controle_d2 + alx_int_position[5]*(2) + alx_int_position[6]*(9) + alx_int_position[7]*(8);
alx_int_controle_d2:= alx_int_controle_d2 + alx_int_position[8]*(7) + alx_int_position[9]*(6) + alx_int_position[10]*(5);
alx_int_controle_d2:= alx_int_controle_d2 + alx_int_position[11]*(4) + alx_int_position[12]*(3) + alx_int_controle_d1*(2);
//------------------
alx_int_controle_d2:= 11 - (alx_int_controle_d2 mod 11);
if(alx_int_controle_d2 >= 10) then begin
alx_int_controle_d2:= 0;
end;
//-------------------
alx_str_controle_1:= inttostr(alx_int_controle_d1) + inttostr(alx_int_controle_d2);
alx_str_controle_2:= alx_str_cnpj_digitado[13] + alx_str_cnpj_digitado[14];
//-------------------
if(alx_str_controle_1 = alx_str_controle_2) then begin
alx_boo_apoio:= true;
end
else begin
alx_boo_apoio:= false;
end;
//--------------------
end
else begin
self.Edit2.SetFocus();
showmessage('Você apresentou um CNPJ com [' + inttostr(System.Length(alx_str_cnpj_digitado)) + '] digitos. Digite o CNPJ com 14 números! ');
alx_boo_apoio:= false;
end;
except
on E: Exception do begin
self.Edit2.SetFocus();
showmessage('Digite o CNPJ com 14 dígitos numéricos! Veja: ' + E.Message);
alx_boo_apoio:= false;
end;
end;
result:= alx_boo_apoio;
end;
//==============================================================================
procedure TFrm_CPF_Painel_Central.BitBtn6Click(Sender: TObject);
begin
self.Close();
end;
//==============================================================================
//=== ... ao clicar neste botão a verificação do CPF será realizada...
//==============================================================================
procedure TFrm_CPF_Painel_Central.BitBtn1Click(Sender: TObject);
begin
if(self.alx_boo_CPF_Validado(self.Edit1.Text)) then begin
showmessage('O cpf [' + self.Edit1.Text + '] está correto!');
end
else begin
showmessage('O cpf [' + self.Edit1.Text + '] NÃO ESTÁ correto!');
end;
end;
//==============================================================================
procedure TFrm_CPF_Painel_Central.BitBtn2Click(Sender: TObject);
var
alx_int_resto: Integer;
begin
alx_int_resto:= (4 mod 3);
showmessage('o resto da divisão de 4 por 3 é: [' + inttostr(alx_int_resto) + ']');
end;
//==============================================================================
//=== ... ao clicar neste botão a verificação de CNPJ será realizada...
//==============================================================================
procedure TFrm_CPF_Painel_Central.BitBtn3Click(Sender: TObject);
begin
if(self.alx_boo_CNPJ_Validado(self.Edit2.Text)) then begin
showmessage('O cnpj [' + self.Edit2.Text + '] está correto!');
end
else begin
showmessage('O cnpj [' + self.Edit2.Text + '] NÃO ESTÁ correto!');
end;
end;
//==============================================================================
end.

segunda-feira, 21 de maio de 2007

Rotina em DELPHI para verificar a senha de um usuário

Caros alunos, segue abaixo uma técnica de acesso a um banco de dados.
Não se esqueça de especificar um objeto ADOConnection no ""DataModule" de sua aplicação.

Saiba que o objeto ADOQuery1 da "unit" abaixo está apontando para o objeto ADOConnection por meio de sua propriedade "Connection".

unit UntVideo;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, DBCtrls, Mask, XPMan, UntDataModule, DB,
ADODB;

type
TForm1 = class(TForm)
Panel1: TPanel;
Button1: TButton;
Button2: TButton;
XPManifest1: TXPManifest;
Edit1: TEdit;
Edit2: TEdit;
Label1: TLabel;
Label2: TLabel;
ADOQuery1: TADOQuery;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
function alx_boo_Usuario_Existe(alx_str_user_apelido_digitado: String): Boolean;
function alx_boo_Senha_Ok(alx_str_user_apelido_digitado: String ; alx_str_senha_digitada: String): Boolean;
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

//==============================================================================
function TForm1.alx_boo_Usuario_Existe(alx_str_user_apelido_digitado: String): Boolean;
var
alx_str_sql_text : TStrings;
alx_boo_usuario_existe: Boolean;
alx_str_user_apelido : String;
begin
try
alx_str_sql_text:= TStringList.Create();
alx_str_sql_text.Add('SELECT FUNC_APELIDO FROM FUNCIONARIOS ORDER BY FUNC_APELIDO ;');
self.ADOQuery1.Active:= False;
self.ADOQuery1.SQL.Clear();
self.ADOQuery1.SQL:= alx_str_sql_text;
self.ADOQuery1.Active:= True;
//------------
while not(self.ADOQuery1.Eof) do begin
alx_str_user_apelido:= self.ADOQuery1.Fields[0].AsString;
if (alx_str_user_apelido = alx_str_user_apelido_digitado ) then begin
alx_boo_usuario_existe:= true;
break;
end
else begin
alx_boo_usuario_existe:= false;
end;
self.ADOQuery1.Next();
end;
//------------
except
on E:Exception do begin
ShowMessage('Ôpa, ocorreu um erro ao verificar a existência de um usuário! Veja: ' + E.Message);
end;
end;
result:= alx_boo_usuario_existe;
end;
//==============================================================================
function TForm1.alx_boo_Senha_Ok(alx_str_user_apelido_digitado: String ; alx_str_senha_digitada: String): Boolean;
var
alx_str_sql_text : TStrings;
alx_boo_senha_ok : Boolean;
alx_str_user_apelido : String;
alx_str_user_senha : String;
begin
try
alx_str_sql_text:= TStringList.Create();
alx_str_sql_text.Add('SELECT FUNC_APELIDO , FUNC_SENHA FROM FUNCIONARIOS ORDER BY FUNC_APELIDO ;');
self.ADOQuery1.Active:= False;
self.ADOQuery1.SQL.Clear();
self.ADOQuery1.SQL:= alx_str_sql_text;
self.ADOQuery1.Active:= True;
//------------
while not(self.ADOQuery1.Eof) do begin
alx_str_user_apelido:= self.ADOQuery1.Fields[0].AsString;
alx_str_user_senha := self.ADOQuery1.Fields[1].AsString;
if ((alx_str_user_apelido = alx_str_user_apelido_digitado) and (alx_str_user_senha = alx_str_senha_digitada) ) then begin
alx_boo_senha_ok:= true;
break;
end
else begin
alx_boo_senha_ok:= false;
end;
self.ADOQuery1.Next();
end;
//------------
except
on E:Exception do begin
ShowMessage('Ôpa, ocorreu um erro ao verificar a senha de um usuário! Veja: ' + E.Message);
end;
end;
result:= alx_boo_senha_ok;
end;
//==============================================================================




procedure TForm1.Button1Click(Sender: TObject);
begin
if(self.alx_boo_Usuario_Existe(self.Edit1.Text)) then begin
self.Edit1.Color:= clBlue;
showmessage('oi, o usuário existe!');
end
else begin
self.Edit1.Color:= clRed;
showmessage('oi, o usuário NÃO existe!');
end;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
if(self.alx_boo_Senha_Ok(self.Edit1.Text , self.Edit2.Text)) then begin
self.Edit2.Color:= clGreen;
showmessage('oi, a senha do usuário [' + self.Edit1.Text + '] confere!');
end
else begin
self.Edit2.Color:= clRed;
ShowMessage('ôpa, a senha do usuário [' + self.Edit1.Text + '] NÃO confere!');
end;
end;

end.

Rotina em DELPHI para instanciar um objeto

A "unit" abaixo possui uma procedure que instancia um objeto formulário a
partir do método construtor próprio da classe que controla o referido formulário.

unit Unit_ALX_Painel_Central;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, Unit_ALX_Clientes;

type
TFrm_ALX_Painel_Central = class(TForm)
BitBtn1: TBitBtn;
BitBtn2: TBitBtn;
BitBtn3: TBitBtn;
procedure BitBtn1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }

end;

var
Frm_ALX_Painel_Central: TFrm_ALX_Painel_Central;

implementation

{$R *.dfm}
//==============================================================================
procedure TFrm_ALX_Painel_Central.BitBtn1Click(Sender: TObject);
var
alx_frm_clientes: TFrm_ALX_Clientes;
begin
alx_frm_clientes:= TFrm_ALX_Clientes.alx_voi_Create(Application);
end;
//==============================================================================

Rotina em DELPHI para Método Construtor

unit Unit_ALX_Clientes;
interface
uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs;
type TFrm_ALX_Clientes = class(TForm)
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
procedure alx_voi_Tratar_Valores_Estaticos();
public
{ Public declarations }
constructor alx_voi_Create(alx_obj_owner: TComponent);
end;
var
alx_int_conta_form: Integer;

implementation
{$R *.dfm}

//==============================================================================
constructor TFrm_ALX_Clientes.alx_voi_Create(alx_obj_owner: TComponent);
begin
inherited Create(alx_obj_owner);
self.alx_voi_Tratar_Valores_Estaticos();
//... realiza as inicializações ...
self.Show);
end;
//==============================================================================
procedure TFrm_ALX_Clientes.alx_voi_Tratar_Valores_Estaticos();
begin
alx_int_conta_form := alx_int_conta_form + 1;
self.Caption:= 'Sistema ALX: Listagem de Clientes [' + inttostr(alx_int_conta_form) + ']';
end;
//==============================================================================
procedure TFrm_ALX_Clientes.FormClose(Sender: TObject; var Action: TCloseAction);
begin
self:= nil;
end;
//==============================================================================
end.

terça-feira, 15 de maio de 2007

Este sou eu


Petrobras na Bolívia

Penso que as instalações da Petrobras na Bolívia devem valer entre 5 e 15 bilhões de dólares americanos.

Por que será que a Petrobras e o governo Brasileiro fecharam o negócio com o governo Boliviano por aproximadamente 120 milhões com tanta pressa?

Por que será que não levaram o para o fórum internacional as questões associadas com a exigibilidade das cláusulas do contrato?