ServerVar Class - ASP.NET

This page is part of the Class Library Pages collection.
Click the icon to see the index.
This class depends on the Parser class, found here.

Overview

The ServerVar class provides a means of working with Server Variables in any ASP.NET website.

Implementation

  1. Copy the source code, found below
  2. Modify the Key enum to suit your requirements
  3. Modify the static constructor to fill the _dict dictionary.

Source Code

VB.NET

Imports Microsoft.VisualBasic
Imports System.Collections.Generic

Public Class ServerVar

    Public Enum Key
        UserType
        FirstName
        LastName
        EmailId
    End Enum

    Private Shared _dict As Dictionary(Of Key, String)

    Shared Sub New()

        _dict = New Dictionary(Of Key, String)()
        _dict.Add(Key.UserType, "HTTP_USERTYPE")
        _dict.Add(Key.FirstName, "HTTP_FIRSTNAME")
        _dict.Add(Key.LastName, "HTTP_LASTNAME")
        _dict.Add(Key.EmailId, "HTTP_EMAILID")

    End Sub
    Public Shared Function GetKey(ByVal key As Key) As String

        Return _dict(key)

    End Function
    Public Shared Function GetValue(ByVal key As Key, Optional ByVal defaultValue As String = "") _
    As String

        Dim s As String = ""

        Dim request As HttpRequest = HttpContext.Current.Request

        If request IsNot Nothing Then
            s = request.QueryString(_dict(key))
            If s Is Nothing Then
                s = ""
            End If
        End If

        If s.Length = 0 Then
            s = defaultValue
        End If

        Return s

    End Function
    Public Shared Function TryGetValue(Of T)(ByVal key As Key, ByRef value As T) As Boolean

        Return Parser(Of T).TryParse(GetValue(key), value)

    End Function
    Public Shared WriteOnly Property [Set](ByVal key As Key) As String
        Set(ByVal value As String)
            Try
                _dict(key) = value
            Catch ex As Exception
                Throw ex
            End Try
        End Set
    End Property
End Class

C#

TODO