Tuesday, 19 July 2011

Session Management

Tasked with upgrading a legacy survey application, i noticed they don't have any defensive programming surrounding their access to HttpContext.Current.Session.

So i changed it from direct access calls such as:


To utilize a TryParse pattern like this:

    ''' <summary>
    ''' Safely retrieves a the value of the given Key from Session
    ''' </summary>
    ''' <returns>False if Session is Nothing or if the given Key is not in Session, True if successful</returns>
    Public Shared Function TryGetSessionValue(ByVal Key As String, ByRef out_result As Object) As Boolean

        If Not System.Web.HttpContext.Current.Session Is Nothing Then
            If Not System.Web.HttpContext.Current.Session(Key) Is Nothing Then
                out_result = System.Web.HttpContext.Current.Session(Key)
                Return False
                'Throw New Exception(String.Format(Constants.ERR_MISSING_SESSION_KEY, Key))
            End If
            Return False
            'Throw New Exception(Constants.ERR_INVALID_SESSION)
        End If

        Return True
    End Function

You've probably noticed the commented out Throw statements - before utilizing the TryParse pattern, i was planning on having this method Throw exceptions so the Application crashes if Session is not valid. But this was a bit harsh...

Instead I now leave it up to the caller to decide their missing Session value means - eg is it Critical, LogOnly or Ignore levels of severity...

No comments:

Post a Comment