jueves, 18 de diciembre de 2008

Un ejemplo práctico II.

En esta segunda entrega del ejemplo práctico pretendo mostrar:

  1. Las posibilidades de obtener las trazas de toda consulta realizada en la capa DAL.
  2. Las diferentes formas de inicialización, carga y utilización de los objetos.
  3. La implementación de transacciones en el modelo.
  4. Utilización de las conexiones.

Como es interesante conocer en todo momento los tiempos de carga de los objetos, el modelo dispone de un mecanismo de notificación de comienzo y fin de carga (OnBeginLoad y OnEndLoad). Pero esto lo veremos más adelante. Ahora solo agregar el código para un Timer mas preciso.

No recuerdo muy bien dónde encontré el código en C# pero creo que fue en www.kalme.de.

Este el código de Dal.Core.DXTimer.vb, archivo que hay que añadir al proyecto DAL aunque, ahora tras algún tiempo, estoy empezando a cuestionarme si no debiera estar en otra Capa. No obstante el cambio de localización de esta clase no compromete en nada el modelo.

Imports System
Imports System.Runtime.InteropServices

Namespace Dal
  Public Class DXTimer

#Region " imported functions "
    <System.Security.SuppressUnmanagedCodeSecurity()> _
    Private Declare Function QueryPerformanceFrequency Lib "kernel32" (ByRef PerformanceFrequency As Long) As Boolean
    <System.Security.SuppressUnmanagedCodeSecurity()> _
    Private Declare Function QueryPerformanceCounter _
    Lib "kernel32" (ByRef PerformanceCount As Long) As Boolean
#End Region

    ' The last number of ticks.
    Private Shared lLastTime As Long = 0
    ' The current number of ticks.
    Private Shared lCurrentTime As Long = 0
    ' The number of ticks per second for this system.
    ' This will be a constant value.
    Private Shared lTicksPerSecond As Long = 0
    ' Indicates if the Timer is initialized
    Private Shared bInitialized As Boolean = False
    ' The elapsed seconds since the last GetElapsedSeconds() call.
    Private Shared dElapsedSeconds As Double = 0.0
    ' The elapsed milliseconds since the last   GetElapsedMilliseconds() call.
    Private Shared dElapsedMilliseconds As Double = 0.0

    ' Property to query the ticks per second  for this system (Timer has to be initialized).
    Public Shared ReadOnly Property TicksPerSecond() As Long
      Get
        Return lTicksPerSecond
      End Get
    End Property

    ' The initialization of the timer. Tries to query
    ' performance frequency and determines if performance
    ' counters are supported by this system.
    Public Shared Sub Init()
      ' Try to read frequency. 
      ' If this fails, performance counters are not supported.
      If QueryPerformanceFrequency(lTicksPerSecond) = False Then
        Throw New Exception("Performance Counter not supported on this system!")
      End If
      ' Initialization successful
      bInitialized = True
    End Sub

    ' Starts the Timer. This set the initial time value.
    ' Timer has to be initialized for this.
    Public Shared Sub Start()
      ' Check if initialized
      If bInitialized = False Then
        Throw New Exception("Timer no initializado!")
      End If

      ' Initialize time value
      QueryPerformanceCounter(lLastTime)

    End Sub


    ' Gets the elapsed milliseconds since the last
    ' call to this function. Timer has to be initialized
    ' for this.
    ' Returns The number of milliseconds.
    Public Shared Function GetElapsedMilliseconds() As Double

      ' Check if initialized
      If bInitialized = False Then
        Throw New Exception("Timer no initializado!")
      End If

      ' Get current number of ticks
      QueryPerformanceCounter(lCurrentTime)

      ' Calculate number of milliseconds since last call
      dElapsedMilliseconds = (Convert.ToDouble(lCurrentTime - lLastTime) / Convert.ToDouble(lTicksPerSecond)) * 1000.0

      ' Store current number of ticks for next call
      lLastTime = lCurrentTime

      ' Return milliseconds
      Return dElapsedMilliseconds
    End Function


    ' Gets the elapsed seconds since the last call
    ' to this function. Timer has to be initialized for this.

    ' Returns The number of seconds.
    Public Shared Function GetElapsedSeconds() As Double
      ' Check if initialized
      If bInitialized = False Then
        Throw New Exception("Timer no initializedo!")
      End If
      ' Get current number of ticks
      QueryPerformanceCounter(lCurrentTime)

      ' Calculate elapsed seconds
      dElapsedSeconds = Convert.ToDouble(lCurrentTime - lLastTime) / Convert.ToDouble(lTicksPerSecond)

      ' Store current number of ticks for next call
      lLastTime = lCurrentTime

      ' Return number of seconds
      Return dElapsedSeconds
    End Function

    Public Shared Rnd As New Random(DateTime.Now.Millisecond)
  End Class
End Namespace

No hay comentarios: