Our ASP.Net application uses a variety of global settings that are used throughout the application. The settings are stored in the database as Key/Value pairs.
At the Application start event, we load these into the HttpRuntime.Cache
object and then use them as required. All settings are handled via a Class. Here is the simplified code for the class.
Public Class ConfigClass
' Other variables, properties & methods removed for clarity
' Functions in DAL are not shown here
' Called from Application Start event
Public Shared Sub LoadAppConfig()
Dim lCfg As DataTable = DAL.GetDataTable("Select ConfigID, Value from AppConfig Order By ConfigID")
If lCfg IsNot Nothing Then
For li_Lp As Integer = 0 To lCfg.Rows.Count - 1
HttpRuntime.Cache.Add(lCfg.Rows(li_Lp)("ConfigID").ToString, lCfg.Rows(li_Lp)("Value").ToString, Nothing, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, Caching.CacheItemPriority.NotRemovable, Nothing)
Next
lCfg = Nothing
End If
End Sub
' Returns the value of a single setting
Public Shared Function GetAppConfig(ByVal as_ConfigID As String) As String
If HttpRuntime.Cache(as_ConfigID) Is Nothing Then ' If nothing in cache, try DB
Dim lOBj As Object = DAL.ExecuteSQL("Select Value from AppConfig Where ConfigID=@ConfigID", DAL.SQLType.sqlScalar, Nothing, "@ConfigID", as_ConfigID).Scalar
If lOBj Is Nothing Then ' If no such setting, return empty string
Return String.Empty
Else ' If found, add to cache and return
HttpRuntime.Cache.Add(as_ConfigID, lOBj.ToString, Nothing, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, Caching.CacheItemPriority.NotRemovable, Nothing)
Return lOBj.ToString
End If
Else
Return HttpRuntime.Cache(as_ConfigID).ToString
End If
End Function
' Method to delete a setting
Public Shared Sub DeleteAppConfig(ByVal as_ConfigID As String)
If DAL.ExecuteSQL("Delete From AppConfig Where ConfigID=@ConfigID", DAL.SQLType.sqlNQ, Nothing, "@ConfigID", as_ConfigID).IsSuccess Then HttpRuntime.Cache.Remove(as_ConfigID)
End Sub
End Class
The code is working just fine and I've not encountered any problems. There are about 30 settings loaded into the cache when the application starts.
Is there any better method of storing and accessing "global" settings? Can I improve on this anyhow?
It may be the best - however modern Database systems are very good at caching often requested data into memory. So on a system with plenty of memory spare, it may not make much difference.