Pages

Monday, October 6, 2008

How to encapsulate static/shared strongly typed properties to expose cache and session variables

The code examples below were created to simplify handling of HttpContext Cache and Session variables. The advantage of static/shared properties is that they are strongly typed which avoids the potential for spelling mistakes.
What is nice is that some of the variables are initialized the first time they are requested and refreshed from an xml source file every 15 minutes. This allows the values to be changed for debugging without resetting IIS.

//---------------------------------------------------------------------
//CacheHandler.vb:
//---------------------------------------------------------------------
Code:
Imports System.Web

'Static/shared class for handling cache variables
Public Class CacheHandler

    'This declares a static/shared strongly typed property to expose cache variable

    'Declare a string variable to hold the key name of the cache variable
    'and use this string variable instead of typing the key name
    'in order to avoid spelling mistakes

    Const CacheHandlerTimeInterval As Double = 15   'Interval in Minute
    Private Shared _FileManagerKey As String = "FileManager"
    Private Shared _CacheHandlerTimerKey As String = _FileManagerKey + ".CacheHandlerTimer"

#Region "HelperMethods"
    '
    'Gets a cache string value
    '
    'The type of the cache value
    'The key name of the cache value
    'Stored string
    Private Shared Function GetCacheValue(Of T)(ByVal key As String) As T
        'object value = null;
        'try
        '{
        '   value = HttpContext.Current.Cache.Get[key];
        '}
        'catch {}
        'if (value == null)
        '   return default(T);

        'return (T)value;

        Return DirectCast((If(HttpContext.Current.Cache.[Get](key), Nothing)), T)
    End Function

    '
    'Sets a cache string value
    '
    'The key name of the cache value
    'Storing string
    Public Shared Sub SetCacheValue(Of T)(ByVal key As String, ByVal value As T)
        If value Is Nothing Then
            _CacheHandlerTimerLastExpired = DateTime.Now
            HttpContext.Current.Cache.Insert(key, _CacheHandlerTimerLastExpired, Nothing, _CacheHandlerTimerLastExpired.AddMinutes(CacheHandlerTimeInterval), TimeSpan.Zero, CacheItemPriority.Normal, Nothing)
        Else
            'Put in Try/Catch because sometimes the cache may not be available.
            Try
                HttpContext.Current.Cache.Insert(key, value)
            Catch
            End Try
        End If
    End Sub
#End Region

    Private Shared _CacheHandlerTimerLastExpired As DateTime

    Public Shared ReadOnly Property IsCacheHandlerTimerExpired(ByVal ProcessLastExpired As DateTime) As Boolean

        Get
            If SessionHandler.IsFileHandlerTester Then
                Return True
            End If

            'Check for nothing
            Dim CacheHandlerTimerValue As Object = HttpContext.Current.Cache.Item(CacheHandler._CacheHandlerTimerKey)
            If IsNothing(CacheHandlerTimerValue) Then
                _CacheHandlerTimerLastExpired = DateTime.Now
                HttpContext.Current.Cache.Insert(_CacheHandlerTimerKey, _CacheHandlerTimerLastExpired, Nothing, _CacheHandlerTimerLastExpired.AddMinutes(CacheHandlerTimeInterval), Nothing, Caching.CacheItemPriority.Normal, Nothing)
                Return True
            Else
                If IsNothing(ProcessLastExpired) OrElse ProcessLastExpired < _CacheHandlerTimerLastExpired Then
                    Return True
                Else
                    Return False
                End If
            End If

        End Get

    End Property
    Private Shared _ProcessTypesKey As String = "ProcessTypes"
    Private Shared _FileManagerProcessTypesKey As String = _FileManagerKey + "." + _ProcessTypesKey
    Private Shared _ProcessTypesLastExpired As DateTime

    Public Shared ReadOnly Property ProcessTypes(Optional ByVal bNoLog As Boolean = False) As String

        Get
            Dim Expired As Boolean = CacheHandler.IsCacheHandlerTimerExpired(_ProcessTypesLastExpired)

            'If value nothing or FileManager CacheHandlerTimer expired
            Dim value As Object = GetCacheValue(Of String)(CacheHandler._FileManagerProcessTypesKey)
            If value Is Nothing OrElse Expired Then
                _ProcessTypesLastExpired = DateTime.Now
                'Get settings variables from FileManager.xml. NoLog used to prevent recursive loop.
                Dim oConfig As New OPC.Library.Web.ConfigReader(_FileManagerKey, OPC.Library.Web.Location.DownloadShare, NoLog:=bNoLog)
                value = oConfig.GetItem(_ProcessTypesKey, True)
                'If missing
                If IsNothing(value) Then
                    value = ""
                End If
                SetCacheValue(Of String)(CacheHandler._FileManagerProcessTypesKey, value.ToString())
            End If

            Return value
        End Get

    End Property

    Private Shared _Extension304ExceptionsItem As String = "Extension304Exceptions"
    Private Shared _Extension304ExceptionsKey As String = _FileManagerKey + "." + _Extension304ExceptionsItem
    Private Shared _Extension304ExceptionsLastExpired As DateTime

    Public Shared ReadOnly Property Extension304Exceptions() As String

        Get
            Dim Expired As Boolean = CacheHandler.IsCacheHandlerTimerExpired(_Extension304ExceptionsLastExpired)

            'If value nothing or FileManager CacheHandlerTimer expired
            Dim value As Object = GetCacheValue(Of String)(CacheHandler._Extension304ExceptionsKey)
            If value Is Nothing OrElse Expired Then
                _Extension304ExceptionsLastExpired = DateTime.Now
                'Get settings variables from FileManager.xml
                Dim oConfig As New OPC.Library.Web.ConfigReader(_FileManagerKey, OPC.Library.Web.Location.DownloadShare)
                value = oConfig.GetItem(_Extension304ExceptionsItem)
                'If missing
                If IsNothing(value) Then
                    value = ""
                End If
                SetCacheValue(Of String)(CacheHandler._Extension304ExceptionsKey, value.ToString())
            End If

            Return value
        End Get

    End Property

End Class 


//---------------------------------------------------------------------
//SessionHandler.vb:
//---------------------------------------------------------------------
Code:
Imports System.Web

'Static/shared class for handling session variables
Public Class SessionHandler

    'This declares a static/shared strongly typed property to expose session variable

    'Declare a string variable to hold the key name of the session variable
    'and use this string variable instead of typing the key name
    'in order to avoid spelling mistakes

    Private Shared _RefererKey As String = "ContentHeader.Referer"

    Public Shared Property Referer() As String
        'This is managed by FileHandler.SaveRequestHeaders()
        Get
            'Check for nothing
            Dim RefererValue As Object = HttpContext.Current.Session(SessionHandler._RefererKey)
            If IsNothing(RefererValue) Then
                'Set Empty String
                RefererValue = String.Empty
            End If

            Return RefererValue.ToString
        End Get

        Set(ByVal value As String)
            HttpContext.Current.Session(SessionHandler._RefererKey) = value
        End Set

    End Property

    Private Shared _TraceLogDateKey As String = "TraceLog.TraceLogDate"

    Public Shared Property TraceLogDate() As String
        'If this managed by TraceLog
        Get
            'Check for nothing
            Dim TraceLogDateValue As Object = HttpContext.Current.Session(SessionHandler._TraceLogDateKey)
            If IsNothing(TraceLogDateValue) Then
                'Set current Datetime
                TraceLogDateValue = Now
                HttpContext.Current.Session(SessionHandler._TraceLogDateKey) = TraceLogDateValue
            ElseIf TraceLogDateValue.ToString.Length = 0 Then
                'Set current Datetime
                TraceLogDateValue = Now
                HttpContext.Current.Session(SessionHandler._TraceLogDateKey) = TraceLogDateValue
            End If

            Return TraceLogDateValue.ToString
        End Get

        Set(ByVal value As String)
            HttpContext.Current.Session(SessionHandler._TraceLogDateKey) = value
        End Set

    End Property

End Class


//---------------------------------------------------------------------
//CookieHandler.vb:
//---------------------------------------------------------------------
Code:
Imports System
Imports System.Web
Imports System.Text.RegularExpressions

'
' Static/shared class for handling cookie variables
' This class declares a static/shared strongly typed property to expose cookie variables.
' By declaring the string variables to hold the key names of the variables
' and use these string variables instead of typing the key name you will avoid
' spelling mistakes and provide a uniform capcilasion that is easyer to manage.
'
Public Class CookieHandler

#Region "Private HelperMethods"
'
' SetPersistCookie is abstracted cookie class for setting persistent cookie values.
'
'string of cookie name you wish to set
'string of value you wish to assign to the cookie
Public Shared Sub SetPersistCookie(ByVal CookieName As String, ByVal CookieValue As String)
    Dim oCookie2 As New HttpCookie(CookieName)
    oCookie2.Value = CookieValue
    oCookie2.Expires = DateTime.Now.AddYears(1)
    HttpContext.Current.Response.Cookies.Add(oCookie2)
End Sub

'
' SetCookie is abstracted cookie class for setting cookie values.
'
'string of cookie name you wish to set
'string of value you wish to assign to the cookie
Public Shared Sub SetCookie(ByVal CookieName As String, ByVal CookieValue As String)
    Dim oCookie2 As New HttpCookie(CookieName)
    oCookie2.Value = CookieValue
    HttpContext.Current.Response.Cookies.Add(oCookie2)
End Sub

'
' GetCookie is abstracted class for retrieving cookie values
'
'Cookie name
'Cookie string value. If cookie not set, returns ""
Public Shared Function GetCookie(ByVal CookieName As String) As String
    If HttpContext.Current.Request.Cookies(CookieName) IsNot Nothing Then
        Return HttpContext.Current.Request.Cookies(CookieName).Value
    Else
        Return ""
    End If
End Function
#End Region

Private Shared _UserCountryIDKey As String = "UserCountryID"

'
' PublicUser selected Country ID.
' This property is managed by PublicUser class.
'
Public Shared Property UserCountryID() As Integer
    Get
        'If UserCountryID not defined
        Dim value As String = GetCookie(_UserCountryIDKey)
        If value Is Nothing OrElse value = "" Then
            value = "-1"
        End If
        Return Convert.ToInt32(value)
    End Get

    Set(ByVal value As Integer)
        SetPersistCookie(_UserCountryIDKey, value.ToString())
    End Set
End Property

End Class

No comments: