Superclasse form base per programmi gestionali (e non) #2 - log, exception call stack, application toolbox

Ora che lo scheletro di una superclasse form da ereditare è pronto andiamo a vedere cosa succede se vogliamo implementare le seguenti caratteristiche:


toolbox
Iniziamo dalla fine.
Pensando all'implementazione di nuove caratteristiche direttamente all'interno della superclasse non si può fare a meno di pensare di prevedere una classe esterna, che sopravviva a tutte le istanze delle varie form dell'ipotetico gestionale. Questa classe che chiameremo TBaseForm_ToolBox avrà diversi compiti:


Questa sarà la prima classe che verrà istanziata dall'applicazione e la prima che verrà valorizzata. Solo successivamente verranno create le form (sottoclassi di TBaseForm) le quali si autoconfigureranno secondo le impostazioni che troveranno nell'istanza della "toolbox".

Segue un esempio di codice dove la toolbox viene istanziata e vengono inizializzate alcune proprietà, tra cui, la path del log che dovranno rispettare tutte le form.
Codice: [Seleziona]

procedure TForm1.FormCreate(Sender: TObject);
begin

  bftoolbox := TBaseForm_ToolBox.Create;
  bftoolbox.Exception_ShowMessage:=TRUE;
  {$IFDEF LINUX}
  bftoolbox.LogPath := '/tmp';
  {$ENDIF}
  {$IFDEF WINDOWS}
  bftoolbox.LogPath := 'c:\tmp';
  {$ENDIF}
  lbLog.Caption:=bftoolbox.LogPath ;

  Caption := bftoolbox.LogPath;
  if not ForceDirectoriesUTF8(bftoolbox.LogPath) then
     ShowMessage('Directory' + LineEnding + Caption + LineEnding + 'non creata!');

end;


gestione automatica dei log
Se andiamo a rivedere l'articolo precedente notiamo che ogni azione che l'utente può richiedere è suddivisa in sotto-azioni (che in realtà sono eventi).
Ad esempio la conferma di una operazione di insert viene effettuata con il seguente schema:


Sicuramente vi sarà capitato di dover indagare per un bug o per un collo di bottiglia ed altrettanto sicuramente avrete pensato che un log con tanto di tempi vi avrebbe aiutato molto nel lavoro. Cosa c'è di meglio quindi che implementare un log trasparente?
Il log viene così gestito:
Codice: [Seleziona]

procedure TfmBaseForm.DoConfirm;
var SaveGuiMode: TBaseForm_GuiMode;
    BFCR: TBaseForm_BFCR;
begin
   SaveGuiMode := GuiMode;
   try
      // create record for intermethod communications
      with BFCR do begin
        Test.result:=TRUE;
        Test.CanForce:= FALSE;
        Test.MsgTestFailed:='';
        Test.MsgToForce:='';
      end;

      // test
      if Assigned(OnConfirmTest) then
         try
            if Assigned(FEventLog) then
               FEventLog.Log('DoConfirm / OnConfirmTest');
            OnConfirmTest(Self, BFCR);
            if not BFCR.Test.result then
               if Assigned(FEventLog) then
                  FEventLog.Log('DoConfirm / OnConfirmTest / Test Failed');
               if BFCR.Test.CanForce then begin
                  if MessageDlg('ATTENTION', BFCR.Test.MsgTestFailed + #10#10 + BFCR.Test.MsgToForce,
                                mtConfirmation, [mbYES, mbNo], 0)  mrYes then
                     exit;
                  if Assigned(FEventLog) then
                     FEventLog.Log('DoConfirm / OnConfirmTest / Execution Forced');
               end else begin
                  if BFCR.Test.MsgTestFailed  '' then
                     ShowMessage(BFCR.Test.MsgTestFailed);
                  exit;
               end;
         except
            on e: exception do begin
               raise TBaseForm_Exception_ConfirmTest.Create('Where: TEST FOR CONFIRM' + #10 + e.Message);
            end;
         end;

      // set gui
      case SaveGuiMode of
         bfgmInsert: GuiMode := bfgmConfirmInsertInProgress;
         bfgmEdit  : GuiMode := bfgmConfirmEditInProgress;
      end;

      // before Confirm
      if Assigned(OnConfirmBefore) then
         try
            if Assigned(FEventLog) then
               FEventLog.Log('DoConfirm / OnConfirmBefore');
            OnConfirmBefore(Self, BFCR);
         except
            on e: exception do begin
               raise TBaseForm_Exception_ConfirmBefore.Create('Where: BEFORE CONFIRM' + #10 + e.Message);
            end;
         end;

      // Confirm
      if Assigned(OnConfirmExecute) then
         try
            if Assigned(FEventLog) then
               FEventLog.Log('DoConfirm / OnConfirmExecute');
            OnConfirmExecute(Self, BFCR);
         except
            on e: exception do begin
               raise TBaseForm_Exception_ConfirmExecute.Create('Where: EXECUTE CONFIRM' + #10 + e.Message);
            end;
         end;

      // after Confirm
      if Assigned(OnConfirmAfter) then
         try
            if Assigned(FEventLog) then
               FEventLog.Log('DoConfirm / OnConfirmAfter');
            OnConfirmAfter(Self, BFCR);
         except
            on e: exception do begin
               raise TBaseForm_Exception_ConfirmAfter.Create('Where: AFTER CONFIRM' + #10 + e.Message);
            end;
         end;

      GuiMode := bfgmBrowse;

   except
      on e: exception do begin
         ManageException(e);
         GuiMode := SaveGuiMode;
      end;
   end;
end;


Per l'attivazione invece si è ricorso al "toolbox" e ad una proprietà particolare di nome Behavior (di tipo set).
Possiamo quindi assegnare 2 valori a Behavior:


Codice: [Seleziona]


type
  TBaseForm_Behavior = (..., bfb_InstanceLog, bfb_ClassLog, ...);



procedure TfmBaseForm.UpdateBehavior;
begin

   ...

  if (bfb_InstanceLog in FBehavior)
     or
     (bfb_ClassLog in FBehavior) then begin

     if not Assigned(FEventLog) then begin
        FEventLog := TEventLog.Create(self);
        FEventLog.LogType := ltFile;
        FEventLog.Active := FALSE;
     end;

     if Assigned(ToolBox) then begin
        ForceDirectoriesUTF8(ToolBox.LogPath);
        FEventLog.FileName := ToolBox.LogPath;
        if RightStr(FEventLog.FileName, 1)  PathDelim then
           FEventLog.FileName := FEventLog.FileName + PathDelim;
        FEventLog.FileName := FEventLog.FileName + ClassName;
        if bfb_InstanceLog in FBehavior then
           FEventLog.FileName := FEventLog.FileName + FormatDateTime('yyyy-mm-dd_hhnnss', Now);
        FEventLog.FileName := FEventLog.FileName + '.log';
        FEventLog.Active := TRUE;
        FEventLog.Log('UpdateBehavior / Log Activate');
     end;

   ...

  end;



lo stack delle eccezioni
Si tratta di una procedura inserita all'interno della "toolbox" e che viene messa a disposizione di tutte le form.

Il codice è il seguente ed è stato utilizzato prendendolo pari pari da una pagina wiki: http://wiki.freepascal.org/Logging_exceptions#Dump_exception_call_stack
Però, in caso di eccezione, viene salvato automaticamente nel log!

Codice: [Seleziona]

function TBaseForm_ToolBox.DumpExceptionCallStack(E: Exception): string;
var
  I: Integer;
  Frames: PPointer;
  Report: string;
begin
  Report := 'Program exception! ' + LineEnding +
    'Stacktrace (ToolBox):' + LineEnding + LineEnding;
  if E  nil then begin
    Report := Report + 'Exception class: ' + E.ClassName + LineEnding +
    'Message: ' + E.Message + LineEnding;
  end;
  Report := Report + BackTraceStrFunc(ExceptAddr);
  Frames := ExceptFrames;
  for I := 0 to ExceptFrameCount - 1 do
    Report := Report + LineEnding + BackTraceStrFunc(Frames[I]);
  result := Report;
end;


i sorgenti
Li potete scaricare da questo post: http://www.lazaruspascal.it/index.php?topic=1392.msg7956#msg7956


Buon lavoro.

SMF 2.0.8 | SMF © 2011, Simple Machines
Privacy Policy
SMFAds for Free Forums
TinyPortal © 2005-2012

Go back to article