Lentidão na conexão (as vezes)

19/06/2008

0

Boa tarde pessoal,
estou quase ficando doido aqui com meu sistema..e por isso mais uma vez venho solicitar a ajuda de vcs meus amigos...

O problema é o seguinte..
Tenho um sistema que roda em uma rede(rede essa que não tenho nenhum relato de lentidão etc)..
Pus meu software para rodar, e o que acontece é o seguinte, dá o famoso 1 minuto nele, que ele para de responder fica lento para abrir as telas, não faz a consulta direito, e depois volta.... esse problema é mto intermitente por isso fico achando estranho.
Já notei uma certa lentidão qdo duas pessoas vão incluir um registro...parece que demora para abrir as tabelas, o detalhe é que as tabelas não tem 20 registros...

Como poderia identificar se meu problema é no software, no bd(sqlserver2000) ou na minha rede???
precisaria de algumas dicas..

um teste que fiz foi instalar o sql server em outra máquina, mas o problema persiste..

valew!!!


Responder

Posts

19/06/2008

Lucas.corp

pelo que tu me descreveste amigo, parece que é problema na programação mesmo, mas se tu não achares nada de imediato que possa estar causando o problema, procure fazer testes com outros equipamentos em casa ou com outra versão do windows...
esses probleminhas são muito chatos mesmo, e o pior é que no fim de tudo, quase sempre é uma coisa simples de resolver...
boa sorte!


Responder

19/06/2008

Jm

e aí lucas.corp,
andei fazendo vários testes aqui e realmente o problema está no meu software... agora não consigo descobrir onde..

Descobri a seguinte coisa...

Eu incluo em uma máquina, vai tdo bem.
incluo em outra, vai tudo bem,
Qdo estou incluindo em uma máquina e outra começa a incluir, aí começam os problemas.. ele fica lento, na maioria das vezes ele dá erro na hora de gravar

"A linha não pode ser localizada para atualização. Alguns valores podem ter sido alterados desde que ela foi lida pela última vez."


ou seja incluir simultaneamente ele dá erro na maioria das vezes...
estranho isso né..

trabalho com delphi 7, sql server 2000 e conexão ADO..

Seria algum tipo de isolamento??? tá tdo padrão por enquanto..

vai aí o código do formulário que está dando erro...
unit UfrmLigacao;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, DBCtrls, Buttons, Grids, DBGrids, ExtCtrls, ComCtrls,
  Mask,DB, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient;

type
  TfrmOcorrencias = class(TForm)
    PCOcorrencias: TPageControl;
    TsInformacoes: TTabSheet;
    GroupBox1: TGroupBox;
    Label1: TLabel;
    Label2: TLabel;
    Label3: TLabel;
    Label4: TLabel;
    Label11: TLabel;
    edDataAtendimento: TDBEdit;
    edContatoLigacao: TDBEdit;
    edatendente: TDBEdit;
    edTelefone: TDBEdit;
    edhorainicio: TDBEdit;
    Label10: TLabel;
    Label6: TLabel;
    dbContratante: TDBLookupComboBox;
    Label5: TLabel;
    dbSituacao: TDBLookupComboBox;
    Label7: TLabel;
    dbObs: TDBMemo;
    Panel3: TPanel;
    btnIncluir: TSpeedButton;
    btnExcluir: TSpeedButton;
    btnalterar: TSpeedButton;
    btnabortar: TSpeedButton;
    btngravar: TSpeedButton;
    TsOcorrencia: TTabSheet;
    GroupBox2: TGroupBox;
    Label8: TLabel;
    Label14: TLabel;
    edDescOcorrencia: TDBRichEdit;
    edlocalOcorrencia: TDBEdit;
    btnLocalizar: TSpeedButton;
    Label9: TLabel;
    dbClassificacao: TDBLookupComboBox;
    btntelefone: TSpeedButton;
    btnLocais: TSpeedButton;
    EDLIGACAO: TDBEdit;
    Label12: TLabel;
    dbTipoContato: TDBLookupComboBox;
    lblverificanumero: TLabel;
    lbllembrete: TLabel;
    dbgOcorrencias: TDBGrid;
    Label15: TLabel;
    dbNivelUrgencia: TDBLookupComboBox;
    procedure btnIncluirClick(Sender: TObject);
    procedure Habilita;
    procedure FormActivate(Sender: TObject);
    procedure FormKeyPress(Sender: TObject; var Key: Char);
    procedure btnabortarClick(Sender: TObject);
    procedure btngravarClick(Sender: TObject);
    procedure btnalterarClick(Sender: TObject);
    procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure edTelefoneEnter(Sender: TObject);
    procedure dbSituacaoExit(Sender: TObject);
    procedure dbContratanteKeyPress(Sender: TObject; var Key: Char);
    procedure edTelefoneKeyPress(Sender: TObject; var Key: Char);
    procedure btnLocaisClick(Sender: TObject);
    procedure dbClassificacaoKeyPress(Sender: TObject; var Key: Char);
    procedure EnviaMSG(nivelUrgencia :String);
    procedure edDescOcorrenciaKeyPress(Sender: TObject; var Key: Char);
    procedure edContatoLigacaoKeyPress(Sender: TObject; var Key: Char);
    procedure dbSituacaoKeyPress(Sender: TObject; var Key: Char);
    procedure btntelefoneClick(Sender: TObject);
    procedure edDescOcorrenciaEnter(Sender: TObject);
    procedure edDescOcorrenciaExit(Sender: TObject);
    procedure dbgOcorrenciasCellClick(Column: TColumn);
    procedure dbgOcorrenciasDrawColumnCell(Sender: TObject;
      const Rect: TRect; DataCol: Integer; Column: TColumn;
      State: TGridDrawState);
    procedure FormCreate(Sender: TObject);
    procedure dbgOcorrenciasDblClick(Sender: TObject);
    procedure edlocalOcorrenciaKeyPress(Sender: TObject; var Key: Char);
    function verificacampos : integer;
    procedure dbNivelUrgenciaKeyPress(Sender: TObject; var Key: Char);
    procedure dbNivelUrgenciaEnter(Sender: TObject);
    procedure dbObsEnter(Sender: TObject);
    procedure dbObsExit(Sender: TObject);
    procedure verificaFone;
    procedure dbTipoContatoKeyPress(Sender: TObject; var Key: Char);
    procedure pesquisaNumero;
    procedure dbObsKeyPress(Sender: TObject; var Key: Char);
  private
    { Private declarations }
    flagacompanhamento : string;
    function testaSituacao : integer;    //função utilizada para testar a conexão e tentar minimizar os erros.
    procedure WMHotkey(var Msg: TWMHotkey); message WM_HOTKEY;
  public
    { Public declarations }
  end;

var
  frmOcorrencias: TfrmOcorrencias;
  acomp_tipocontato : integer;
  acomp_numero,acomp_contato,acomp_ligacao : string;


implementation

uses UDM, UfrmPrincipal, UfrmLogin, UfrmPesquisaEndereco,
  UfrmPesquisaTelefone, UfrmAcompanhamento, UfrmSituacaoProtocolo;

{$R *.dfm}

function TfrmOcorrencias.testaSituacao : integer;
   var contador : integer;
begin
   contador := 0;
   If DM.Conexao.InTransaction then
      contador := contador + 1;
   If DM.Atendimento.Active then
      contador := contador + 1;
   If DM.Atendimento.State in [dsInsert,dsEdit] then
      contador := contador +1;

   result := contador;
end;

procedure TfrmOcorrencias.pesquisaNumero;
begin
   DM.QVerificaNumero.Close;
   DM.QVerificaNumero.SQL.Clear;
   DM.QVerificaNumero.SQL.Add(´SELECT C.NOME AS NOME FROM CLIENTE C INNER JOIN ITENSCONTATOCLIENTE I ON C.CODCLIENTE = I.CODCLIENTE WHERE(I.CODTIPOCONTATO = :PCODTIPOCONTATO) AND (I.NUMERO = :PNUMERO)´);
   DM.QVerificaNumero.Parameters.ParamByName(´PCODTIPOCONTATO´).Value := dbTipoContato.KeyValue;
   DM.QVerificaNumero.Parameters.ParamByName(´PNUMERO´).Value         := Trim(edTelefone.Text);
   DM.QVerificaNumero.Open;
   If not DM.QVerificaNumero.IsEmpty then
      begin
         If DM.QVerificaNumero.RecordCount = 1 then
            begin
               DM.AtendimentoContato.Value := DM.QVerificaNumeroNOME.Value;
               edContatoLigacao.SetFocus;
               edContatoLigacao.SelectAll;
               lblverificanumero.Visible := False;
               DM.QVerificaNumero.Close;
            end;
      end
   Else
      begin
         DM.QVerificaNumero.Close;
         DM.QVerificaNumero.SQL.Clear;
         DM.QVerificaNumero.SQL.Add(´SELECT IDETIFICACAO_ORGAO AS NOME FROM TELEFONES_UTEIS WHERE FONE_ORGAO = :PFONE_ORGAO´);
         DM.QVerificaNumero.Parameters.ParamByName(´PFONE_ORGAO´).Value := Trim(edTelefone.Text);
         DM.QVerificaNumero.Open;
         If not DM.QVerificaNumero.IsEmpty then
            begin
               If DM.QVerificaNumero.RecordCount = 1 then
                  begin
                     DM.AtendimentoContato.Value := DM.QVerificaNumeroNOME.Value;
                     edContatoLigacao.SetFocus;
                     edContatoLigacao.SelectAll;
                     lblverificanumero.Visible := False;
                     DM.QVerificaNumero.Close;
                  end;
            end
         Else If Trim(edContatoLigacao.Text) <> ´´ then
            DM.AtendimentoContato.Value := ´´;

         lblverificanumero.Visible := True;
         edContatoLigacao.SetFocus;
         DM.QVerificaNumero.Close;
      end;
end;

procedure TfrmOcorrencias.verificaFone;
var i : integer;
    valor : string;
begin
    If Trim(edtelefone.Text) <> ´´ then
       begin
          for i := 0 to length(Trim(edtelefone.Text)) do
             begin
                valor := copy(trim(edtelefone.Text),i,1);
                If valor = ´*´ then
                  begin
                     DM.AtendimentoCodTipoContato.Value := 2;
                     dbTipoContato.SetFocus;
                     exit;
                  end;
                 DM.AtendimentoCodTipoContato.Value := 3;
                 dbTipoContato.SetFocus;
             end;
       end
    Else
       begin
          Application.MessageBox(´Número de telefone inválido.´,´Telefone´,MB_OK+MB_ICONERROR);
          edtelefone.SetFocus;
       end;
end;


Function TfrmOcorrencias.verificacampos : integer;
var erros : integer;
begin
   erros := 0;

   If Trim(dbSituacao.Text) = ´´ then
      erros := erros + 1;

   If ((Trim(dbContratante.Text) = ´´) and (Trim(dbSituacao.Text) <> ´LIGAÇÃO PERDIDA´)) then
      erros := erros + 1;

   If flagacompanhamento = ´N´ then
      begin
         If Trim(dbSituacao.Text) = ´OCORRÊNCIA´ then
            begin
               If Trim(edlocalOcorrencia.Text) = ´´ then
                  erros := erros + 1;

               If Trim(edDescOcorrencia.Text) = ´´ then
                  erros := erros + 1;

               If Trim(dbClassificacao.Text) = ´´ then
                  erros := erros + 1;

               If Trim(dbNivelUrgencia.Text) = ´´ then
                  erros := erros + 1;

            end;
      end;

    result := erros;
end;

Function RetCodigo(Valor:integer; flag :string):string;
var valortemp:string;
begin
   valortemp := InttoStr(Valor);
   While length(valortemp) < 6 do
      valortemp := ´0´+valortemp;
   Result:= flag + ´-´ + valortemp;
end;

procedure TfrmOcorrencias.WMHotkey(var Msg: TWMHotkey);
begin
  case Msg.HotKey of
    1:begin
         If edTelefone.Focused then
            begin
               Application.CreateForm(TfrmPesquisaTelefone,frmPesquisaTelefone);
               frmPesquisaTelefone.ShowModal;
            end;
      end;
    2:begin
         If edlocalOcorrencia.Focused then
            begin
               Application.CreateForm(TfrmPesquisaEndereco,frmPesquisaEndereco);
               frmPesquisaEndereco.ShowModal;
            end;
      end;

    3:begin
         If edDescOcorrencia.Focused then
            begin
               Application.MessageBox(´Não disponível tela de atalho´,´Informação´,MB_OK+MB_ICONINFORMATION);
            end;
      end;
  end;
end;


procedure TfrmOcorrencias.EnviaMSG(nivelUrgencia :String);
begin
   Try
      If not FrmLogin.CSocketLigacao.Connected then
        try
           FrmLogin.CSocketLigacao.Connect;
        Except
        end;
      FrmLogin.CSocketLigacao.WriteLn(´NOVO´+nivelUrgencia);
   except
   end;
end;

procedure TfrmOcorrencias.Habilita;
begin
   btnincluir.Enabled  := not btnincluir.Enabled;
   btnexcluir.Enabled  := not btnexcluir.Enabled;
   btnalterar.Enabled  := not btnalterar.Enabled;
   btnabortar.Enabled  := not btnabortar.Enabled;
   btngravar.Enabled   := not btngravar.Enabled;
   btntelefone.Enabled := not btntelefone.Enabled;
end;

procedure TfrmOcorrencias.btnIncluirClick(Sender: TObject);
   var erro : string;
begin
   try
      flagacompanhamento := ´N´;
      lblverificanumero.Visible := false;
      DM.Conexao.BeginTrans;
      DM.Atendimento.Append;
      //Preenchendo campos
      DM.AtendimentoOperador.AsString := OPERADOR;
      DM.AtendimentoData.Value := Date;
      DM.AtendimentoHora.Value := TimetoStr(time);
      //verifica se é Ligação recebida ou efetuada
      If TIPOLIGACAO = ´E´ then
         begin
            DM.AtendimentoTipoLigacao.Value := ´EFETUADA´;
            EDLIGACAO.Color := clLime;
            EDLIGACAO.Font.Color := clBlack;
         end
      Else If TIPOLIGACAO = ´R´ then
         begin
            DM.AtendimentoTipoLigacao.Value := ´RECEBIDA´;
            EDLIGACAO.Color := clRed;
            EDLIGACAO.Font.Color := clBlack;
         end;
      // fim do verifica se é Ligação recebida ou efetuada

      If not DM.TipoContato.IsEmpty then
         DM.AtendimentoCodTipoContato.Value := DM.TipoContatoCodTipoContato.AsInteger + 1;

      //Fim do Preenchendo campos

      Habilita;
      dbTipoContato.DragMode    := dmManual;
      dbSituacao.DragMode       := dmManual;
      dbContratante.DragMode    := dmManual;
      dbClassificacao.DragMode  := dmManual;
      dbNivelUrgencia.DragMode  := dmManual;

      If testaSituacao <> 3 then
         begin
            Showmessage(´Tente incluir novamente´);
            exit;
            close;
         end;


      edTelefone.SetFocus;
   except
      on E: Exception do
            begin
               erro := ´Erro ao incluir registro!´+#13+E.Message;

               Application.MessageBox(Pchar(erro),´Cadastro´,MB_OK+MB_ICONERROR);
               Habilita;
               dbTipoContato.DragMode       := dmAutomatic;
               dbSituacao.DragMode    := dmAutomatic;
               dbTipoContato.DragMode := dmAutomatic;
               dbClassificacao.DragMode  := dmAutomatic;
               dbNivelUrgencia.DragMode  := dmAutomatic;
            end;
   end;
end;

procedure TfrmOcorrencias.FormActivate(Sender: TObject);
begin
   flagacompanhamento := ´´;

   //zerando variáveis que serão utilizadas no acompanhamento
   acomp_tipocontato := 0;
   acomp_numero      := ´´;
   acomp_contato     := ´´;
   acomp_ligacao     := ´´;
   //fim do zerando variáveis que serão utilizadas no acompanhamento

   DM.Atendimento.Active         := true;
   DM.Ocorrencia.Active          := true;;
   DM.TipoContato.Active         := true;;
   DM.SituacaoLigacao.Active     := true;
   DM.Contratante.Active         := true;
   DM.Classificacao_Ocorr.Active := true;
   DM.Acompanhamento.Active      := true;
   DM.Nivel_Urgencia.Active      := true;

   //Retira a opção "Sem contato" da tabela tipo contato que não pode estar disponível nesse módulo
   DM.TipoContato.Filtered := false;
   DM.TipoContato.Filter   := ´TipoContato <>´+QuotedStr(´Sem Contato´);
   DM.TipoContato.Filtered := True;
   //Fim do Retira a opção "Sem contato" da tabela tipo contato que não pode estar disponível nesse módulo
   PCOcorrencias.Pages[1].tabvisible := false;

   If ((TIPOLIGACAO = ´E´) OR (TIPOLIGACAO = ´R´)) then
      btnIncluir.Click;
end;

procedure TfrmOcorrencias.FormKeyPress(Sender: TObject; var Key: Char);
begin
   If key = 13 then
      Perform(wm_nextdlgctl,0,0);
end;

procedure TfrmOcorrencias.btnabortarClick(Sender: TObject);
   var erro : string;
begin
   try
      DM.Atendimento.Cancel;
      If DM.Conexao.InTransaction then
         DM.Conexao.RollbackTrans;
      Habilita;
      dbTipoContato.DragMode   := dmAutomatic;
      dbSituacao.DragMode      := dmAutomatic;
      dbContratante.DragMode   := dmAutomatic;
      dbClassificacao.DragMode := dmAutomatic;
      dbNivelUrgencia.DragMode := dmAutomatic;
      close;
   except
      on E: Exception do
            begin
               erro := ´Erro ao abortar registro!´+#13+E.Message;

               Application.MessageBox(Pchar(erro),´Cadastro´,MB_OK+MB_ICONERROR);
               Habilita;
               close;
            end;
   end;
end;

procedure TfrmOcorrencias.btngravarClick(Sender: TObject);
  var codigo : integer;
      flag,tipoOcorrencia,msg,nivelUrgencia: string;
      erro : string;
begin
   Try
      tipoOcorrencia := ´´;

      If verificacampos > 0 then
         begin
            Application.MessageBox(´Não foram preenchidos todos os campos obrigatórios!´,´Campos obrigatórios´,MB_OK+MB_ICONERROR);
            frmOcorrencias.SetFocus;
            exit;
         end;

      If flagacompanhamento = ´N´ then
         begin
            If DM.dsOcorrencia.State in [dsInsert] then
               begin
                  DM.Contratante.Edit;
                  codigo := DM.ContratanteSequencia.Value + 1;
                  flag   := DM.ContratanteFlag.Value;
                  DM.ContratanteSequencia.Value := DM.ContratanteSequencia.Value + 1;
                  DM.Contratante.Post;
                  DM.OcorrenciaProtocolo.Value := RetCodigo(codigo,flag);
                  DM.OcorrenciaDescricaoOcorrencia.Value := Trim (edDescOcorrencia.Text);
                  DM.OcorrenciaFinalizada.Value := ´0´;
                  DM.OcorrenciaAcompanhamento_valido.Value := ´0´;
                  DM.OcorrenciaResolvendo.Value := ´0´;
                  DM.Ocorrencia.Post;
                  nivelUrgencia  := InttoStr(DM.OcorrenciaCodNivelUrgencia.Value);
                  tipoOcorrencia := DM.OcorrenciaProtocolo.Value;
               end;
            If DM.dsOcorrencia.State in [dsEdit] then
               begin
                  DM.Ocorrencia.Post;
               end;
            DM.Atendimento.Post;
            DM.Conexao.CommitTrans;
            Habilita;
            Application.MessageBox(´Registro cadastrado com sucesso!´,´Inclusão - Ocorrências´,mb_ok+MB_ICONEXCLAMATION);

            If Trim(tipoOcorrencia) <> ´´ then
              begin
                 msg := ´Protocolo gerado número - ´ + tipoOcorrencia;
                 Application.MessageBox(Pchar(msg) ,´Protocolo´,MB_OK+MB_ICONINFORMATION);
                 msg := ´´;
                 EnviaMSG(nivelUrgencia); // Envia mensagem para os Resolvedores
              end;
            close;
         end

      Else If flagacompanhamento = ´S´ then
         begin
            PCOcorrencias.TabIndex := 1;
            DM.Conexao.CommitTrans;
            Habilita;
            close;
         end;

   except
      on E: Exception do
            begin
               erro := ´Erro ao gravar registro!´+#13+E.Message;
               Application.MessageBox(Pchar(erro),´Cadastro´,MB_OK+MB_ICONERROR);
               Habilita;
               If DM.Conexao.InTransaction then
                  DM.Conexao.RollbackTrans;
            end;
   end;
end;

procedure TfrmOcorrencias.btnalterarClick(Sender: TObject);
   var erro : string;
begin
   try
      DM.Conexao.BeginTrans;
      DM.Atendimento.Edit;
      Habilita;
      dbTipoContato.DragMode   := dmManual;
      dbSituacao.DragMode      := dmManual;
      dbContratante.DragMode   := dmManual;
      dbClassificacao.DragMode := dmManual;
      dbNivelUrgencia.DragMode := dmManual;
   except
      on E: Exception do
            begin
               erro := ´Erro ao alterar registro!´+#13+E.Message;

               Application.MessageBox(Pchar(erro),´Cadastro´,MB_OK+MB_ICONERROR);
               Habilita;
               dbTipoContato.DragMode       := dmAutomatic;
               dbSituacao.DragMode    := dmAutomatic;
               dbTipoContato.DragMode := dmAutomatic;
               dbClassificacao.DragMode  := dmAutomatic;
               dbNivelUrgencia.DragMode  := dmAutomatic;
            end;
   end;
end;

procedure TfrmOcorrencias.FormCloseQuery(Sender: TObject;
  var CanClose: Boolean);
begin
   If btngravar.Enabled then
       begin
          Application.MessageBox(´Para finalizar a Operação clique em "Abortar" ou "Gravar"´,´Informação´,mb_ok);
          CanClose := false;
       end;
end;

procedure TfrmOcorrencias.FormClose(Sender: TObject;
  var Action: TCloseAction);
begin
   DM.Atendimento.Close;
   DM.Ocorrencia.Close;
   DM.TipoContato.Close;
   DM.SituacaoLigacao.Close;
   DM.Contratante.Close;
   DM.Classificacao_Ocorr.Close;
   DM.QVerificaOcorrencia.Close;
   DM.Acompanhamento.Close;
   DM.Nivel_Urgencia.Close;
   //limpando o filtro
   DM.TipoContato.Filtered := false;
   DM.TipoContato.Filter   := ´´;
   action := cafree;
end;

procedure TfrmOcorrencias.edTelefoneEnter(Sender: TObject);
begin
   edTelefone.SelectAll;
end;

procedure TfrmOcorrencias.dbSituacaoExit(Sender: TObject);
begin
   If Trim(dbSituacao.Text) = ´OCORRÊNCIA´ then
      PCOcorrencias.Pages[1].tabvisible := True
   Else
      PCOcorrencias.Pages[1].tabvisible := False;
end;

procedure TfrmOcorrencias.dbContratanteKeyPress(Sender: TObject;
  var Key: Char);
begin
   If ((key = #13) or (key = 9)) then
      begin
         If Trim(dbSituacao.Text) = ´´ then
            begin
               Application.MessageBox(´Contratante inválido!´+´13´+´Preencha corretamente o campo!´,´Contratante´,MB_OK+MB_ICONERROR);
               dbContratante.SetFocus;
               exit;
            end;
         If Trim(dbSituacao.Text) = ´ACOMPANHEMENTO DE OCORRÊNCIA´ then
            begin
               frmOcorrencias.Hide;
               flagacompanhamento := ´S´;
               //variáveis que serão usadas no acompanhamento
                acomp_tipocontato := dbTipoContato.KeyValue;
                acomp_numero      := Trim(edTelefone.Text);
                acomp_contato     := Trim(edContatoLigacao.Text);
                acomp_ligacao     := Trim(EDLIGACAO.Text);
               //fim das variáveis que serão usadas no acompanhamento
               Application.CreateForm(TfrmSituacaoProtocolo,frmSituacaoProtocolo);
               frmSituacaoProtocolo.ShowModal;
            end

         Else If PCOcorrencias.Pages[1].tabvisible then
            begin
               PCOcorrencias.TabIndex := 1;
               Try
                  DM.Atendimento.Post;
                  DM.Atendimento.Edit;
                  DM.Ocorrencia.Append;
                  edlocalOcorrencia.SetFocus;
                except
                   Dm.Conexao.RollbackTrans;
                   Application.MessageBox(´Erro ao tentar incluir os telefones!´,´Inclusão de registro´,MB_OK+MB_ICONERROR);
                   close;
               end;
            end
         Else
            dbObs.SetFocus;
      end;
   If key = 27 then
     dbSituacao.SetFocus;
end;

procedure TfrmOcorrencias.edTelefoneKeyPress(Sender: TObject;
  var Key: Char);
begin
   If key = #13 then
      verificaFone;

   If not (key in [´0´..´9´,´*´,8]) then
     key := 0;

end;

procedure TfrmOcorrencias.btnLocaisClick(Sender: TObject);
begin
   Application.CreateForm(TfrmPesquisaEndereco,frmPesquisaEndereco);
   frmPesquisaEndereco.ShowModal;
end;

procedure TfrmOcorrencias.dbClassificacaoKeyPress(Sender: TObject;
  var Key: Char);
begin
  If ((key = 13) or (key = 9)) then
     dbNivelUrgencia.SetFocus;

end;

procedure TfrmOcorrencias.edDescOcorrenciaKeyPress(Sender: TObject;
  var Key: Char);
begin
   Key := AnsiUpperCase(Key)[Length(Key)];
end;

procedure TfrmOcorrencias.edContatoLigacaoKeyPress(Sender: TObject;
  var Key: Char);
begin
   If key = 27 then
     edTelefone.SetFocus;
end;

procedure TfrmOcorrencias.dbSituacaoKeyPress(Sender: TObject;
  var Key: Char);
begin
   If key = #27 then
     edContatoLigacao.SetFocus;
end;

procedure TfrmOcorrencias.btntelefoneClick(Sender: TObject);
begin
   Application.CreateForm(TfrmPesquisaTelefone,frmPesquisaTelefone);
   frmPesquisaTelefone.ShowModal;
end;

procedure TfrmOcorrencias.edDescOcorrenciaEnter(Sender: TObject);
begin
  KeyPreview := false;
end;

procedure TfrmOcorrencias.edDescOcorrenciaExit(Sender: TObject);
begin
  KeyPreview := True;
end;

procedure TfrmOcorrencias.dbgOcorrenciasCellClick(Column: TColumn);
var  Frm : TForm;
     MM  : TDBMemo; //declarar DBCtrls no uses
begin
   If dbgOcorrencias.SelectedField = DM.QVerificaOcorrenciaDESCRICAOOCORRENCIA then
      begin
         Frm:=TForm.Create(nil);
         try
            Frm.Width       := 300;
            Frm.Height      := 160;
            Frm.Top         := Mouse.CursorPos.y;
            Frm.Left        := Mouse.CursorPos.x;
            Frm.BorderStyle := bsToolWindow;
            Frm.Caption     := ´Protocolo : ´ + DM.QVerificaOcorrenciaPROTOCOLO.AsString;
            MM              := TDBMemo.Create(nil);
            MM.Color        := clInfoBk;
            MM.Font.Color   := clMaroon;
            try
               MM.parent     := Frm;
               MM.Align      := alclient;
               mm.DataSource := DM.dsQVerificaOcorrencia;
               MM.DataField  := ´DESCRICAOOCORRENCIA´;
               Frm.ShowModal;
            finally
               MM.free;
            end;
         finally
            Frm.free;
         end;
      end;
end;

procedure TfrmOcorrencias.dbgOcorrenciasDrawColumnCell(Sender: TObject;
  const Rect: TRect; DataCol: Integer; Column: TColumn;
  State: TGridDrawState);
begin
  if (gdSelected in State) then
   begin
    //define uma cor de fundo
    dbgOcorrencias.Canvas.Brush.Color := clInfoBk;
    dbgOcorrencias.Canvas.Font.Color  := clMaroon;
    dbgOcorrencias.Canvas.FillRect(Rect); // pinta a célula.
    dbgOcorrencias.DefaultDrawDataCell(rect,Column.field,State);
   end;
end;

procedure TfrmOcorrencias.FormCreate(Sender: TObject);
begin
   If not RegisterHotkey(Handle, 1, MOD_CONTROL,ord(´N´)) then
      Application.MessageBox(´Erro ao programar o atalho para Números de telefones.´,´Programar atalhos´,MB_OK+MB_ICONERROR);

   If not RegisterHotkey(Handle, 2, MOD_CONTROL,ord(´L´)) then
      Application.MessageBox(´Erro ao programar o atalho para Endereços.´,´Programar atalhos´,MB_OK+MB_ICONERROR);

   If not RegisterHotkey(Handle, 3, MOD_CONTROL,ord(´D´)) then
      Application.MessageBox(´Erro ao programar o atalho para Ocorrências pré-cadastradas.´,´Programar atalhos´,MB_OK+MB_ICONERROR);

end;

procedure TfrmOcorrencias.dbgOcorrenciasDblClick(Sender: TObject);
begin
   If not DM.QVerificaOcorrencia.IsEmpty then
      begin
         flagacompanhamento := ´S´;
         //Primeiramente cancelar a nova Ocorrencia
         If DM.dsOcorrencia.State in [dsInsert,dsEdit] then
            DM.Ocorrencia.Cancel;
         //Primeiramente cancelar a nova Ocorrencia

         //Mudar a situação da ligação para Acompanhamento
         If flagacompanhamento = ´S´ then
            begin
               DM.SituacaoLigacao.Locate(´Descricao´,´ACOMPANHEMENTO DE OCORRÊNCIA´,[]);
               DM.AtendimentoCodSituacao.Value := DM.SituacaoLigacaoCodSituacao.Value;
               DM.AtendimentoObs.Value  := ´Referente ao Protocolo : ´ + DM.QVerificaOcorrencia.fieldbyName(´PROTOCOLO´).Value;
               DM.Atendimento.Post;
            end;
         //Fim do Mudar situação

         //variáveis que serão usadas no acompanhamento
          acomp_tipocontato := dbTipoContato.KeyValue;
          acomp_numero      := Trim(edTelefone.Text);
          acomp_contato     := Trim(edContatoLigacao.Text);
          acomp_ligacao     := Trim(EDLIGACAO.Text);
         //fim das variáveis que serão usadas no acompanhamento

         DM.Atendimento.Locate(´CODATENDIMENTO´,Trim(DM.QVerificaOcorrencia.fieldbyName(´CODATENDIMENTO´).Value),[]);
         Application.CreateForm(TfrmAcompanhamento,frmAcompanhamento);
         frmAcompanhamento.gbResumoOcorrencia.Caption := ´Resumo da Ocorrência : Protocolo - ´ + DM.QVerificaOcorrencia.fieldbyName(´PROTOCOLO´).Value;
         frmOcorrencias.Hide;
         frmAcompanhamento.ShowModal;
     end;

end;

procedure TfrmOcorrencias.edlocalOcorrenciaKeyPress(Sender: TObject;
  var Key: Char);
begin
   If ((key = #13) or (key = 9)) then
      If Trim(edlocalOcorrencia.Text) <> ´´ then
         begin
            DM.QVerificaOcorrencia.Close;
            DM.QVerificaOcorrencia.Parameters.ParamByName(´PCODCONTRATANTE´).Value  := dbContratante.KeyValue ;
            DM.QVerificaOcorrencia.Parameters.ParamByName(´PLOCALOCORRENCIA´).Value := Trim(edlocalOcorrencia.Text)+´¬´;
            DM.QVerificaOcorrencia.Open;

            If not DM.QVerificaOcorrencia.IsEmpty then
               begin
                  frmOcorrencias.Top     := frmOcorrencias.Top  -  80;
                  frmOcorrencias.Height  := frmOcorrencias.Height + 200 ;
                  dbgOcorrencias.Height := 200;
               end;
         end
      Else
         begin
            Application.MessageBox(´Endereço inválido´,´Endereço´,MB_OK+MB_ICONERROR);
            edlocalOcorrencia.SetFocus;
         end;
end;

procedure TfrmOcorrencias.dbNivelUrgenciaKeyPress(Sender: TObject;
  var Key: Char);
begin
  If key = #13 then
     If btngravar.Visible then
        btngravar.Click;
end;

procedure TfrmOcorrencias.dbNivelUrgenciaEnter(Sender: TObject);
begin
   If DM.Ocorrencia.State in [dsInsert] then
      begin
         If Trim(dbClassificacao.Text) <> ´´ then
             DM.OcorrenciaCodNivelUrgencia.Value := DM.Classificacao_OcorrCodNivelUrgencia.Value;
      end;
end;

procedure TfrmOcorrencias.dbObsEnter(Sender: TObject);
begin
   lbllembrete.Font.Color := clRed;

   If Trim(dbSituacao.Text) = ´RONDA A PÉ´ then
       lbllembrete.Caption := ´Informe o local onde o veículo ficou estacionado!´
   Else
       lbllembrete.Caption := ´Somente acrescente observação se for extremamente necessário para o entendimento da ligação.´;
end;

procedure TfrmOcorrencias.dbObsExit(Sender: TObject);
begin
   lbllembrete.Font.Color := clMaroon;
end;

procedure TfrmOcorrencias.dbTipoContatoKeyPress(Sender: TObject;
  var Key: Char);
begin
   If key = #27 then
      edtelefone.SetFocus;

   If key = 13 then
      begin
         if dbTipoContato.KeyValue = 3 then
            begin
               If length(Trim(edtelefone.Text)) = 8 then
                  begin
                     DM.AtendimentoNumero.Value := ´(11) ´+copy(trim(edtelefone.Text),1,4)+´-´+copy(trim(edtelefone.Text),5,4);
                     pesquisaNumero;
                  end
               Else If length(Trim(edtelefone.Text)) = 10 then
                  begin
                     DM.AtendimentoNumero.Value := ´(´+copy(trim(edtelefone.Text),1,2)+´) ´+copy(trim(edtelefone.Text),3,4)+´-´+copy(trim(edtelefone.Text),7,4);
                     pesquisaNumero;
                  end

               Else If length(Trim(edtelefone.Text)) = 11 then
                  begin
                     If (copy(Trim(edtelefone.Text),1,1) = ´0´) then
                        begin
                           DM.AtendimentoNumero.Value := ´(´+copy(trim(edtelefone.Text),2,2)+´) ´+copy(trim(edtelefone.Text),4,4)+´-´+copy(trim(edtelefone.Text),8,4);
                           pesquisaNumero;
                        end;
                  end
            end
         else
            pesquisaNumero;
      end;

end;

procedure TfrmOcorrencias.dbObsKeyPress(Sender: TObject; var Key: Char);
begin
   If key = #13 then
      btngravar.Click;
end;

end.



Responder

20/06/2008

Lucas.corp

opa...
dei uma olhada no código todo e pelo que tu me disse concluí que os problemas começam ao criar e então ATIVAR o formulário:
No final do procedimento de activate tu já tá mandando incluir o registro mas não posta ele no final do procedimento de inclusão, e só posta ao acionar o botão de gravar certo?
pelo método como é feito a manipulação de dados está ocorrendo a lentidão e o erro ao gravar, já que em uma máquina só, com um registro em aberto não há problemas certo.
experimente postar o registro no final do procedimento de inclusão e quando precisar adicionar informações abra-o e poste logo em seguida.. se for possível

testa aí e me avisa
qualquer coisa se entendi errado me diga que vo dá mais uma pensada aqui. mas acho que estamos no caminho.
valeu!


Responder

20/06/2008

Lucas.corp

ah, olhei denovo e me liguei agora cara! é isso mesmo...

´A linha não pode ser localizada para atualização. Alguns valores podem ter sido alterados desde que ela foi lida pela última vez.´


ele tá se perdendo pois tu abre dois registros e o programa não sabe manipular os dois ao mesmo tempo...


Responder

Assista grátis a nossa aula inaugural

Assitir aula

Saiba por que programar é uma questão de
sobrevivência e como aprender sem riscos

Assistir agora

Utilizamos cookies para fornecer uma melhor experiência para nossos usuários, consulte nossa política de privacidade.

Aceitar