开发者

Where to store single data types for websites

I'm using asp.net mvc. How or where do I store single pieces of data? For eg. SubscriptionFee, or IsSiteOffline.

I asked a question about user-settings here. Should I do something like this for sitesettings or is there another way apart from the database? I'd like my user to change these setting开发者_JAVA技巧s from the site itself.

I will be using EntityFramework code-first and would love if I could do something like: settings.SubscriptionFee.


Preferably, especially since you would like to allow the users to change these settings, store them in whatever data store you have as back end, like SQL or else.

To use the settings you can bring them in the application cache and create dependency to the data store so any update will expire your cache. You can even use a static class for that, but you will have to implement the management yourself.


Typically, you'll put those settings into the <appSettings> section of your Web.config file.

A standard ASP .NET MVC 3 application comes with a few settings already (inside of the <configuration> element):

  <appSettings>
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="MyCustomSetting" value="abcd1234" />
  </appSettings>

To reference them in your application, you use the ConfigurationManager class:

using System.Configuration;

string value = ConfigurationManager.AppSettings["MyCustomSetting"];

As was said before, though, it may be better to create a configuration table in your data back-end (ie, SQL Server or whatever you use) and grab them from there.

In one of my (non-MVC) applications, I created a static SysProperties class that would use the application's cache to keep them cached for at least 5 minutes. This example doesn't use the Entity Framework, but it could very easily be adapted:

public static class SysProperties
{
    public static string SMTPServer
    {
        get
        {
            return GetProperty("SMTPServer").ToString();
        }
    }

    public static decimal TicketFee
    {
        get
        {
            return Convert.ToDecimal(GetProperty("TicketFee"));
        }
    }

    private static object GetProperty(string PropertyName)
    {
        object PropertyValue = null;
        if (HttpContext.Current != null)
            PropertyValue = HttpContext.Current.Cache[PropertyName];

        if (PropertyValue == null)
        {
            SqlCommand cmSQL = new SqlCommand("SELECT Value FROM tblProperty WHERE Name = @PropertyName");
            cmSQL.Parameters.AddWithValue("@PropertyName", PropertyName);

            DataTable dt = Functions.RunSqlCommand(cmSQL);

            PropertyValue = dt.Rows[0][0];

            if (HttpContext.Current != null)
                HttpContext.Current.Cache.Insert(PropertyName, PropertyValue, null, DateTime.UtcNow.AddMinutes(5), System.Web.Caching.Cache.NoSlidingExpiration);

            return PropertyValue;
        }
        else
        {
            return PropertyValue;
        }
    }
}

Note: You could use this same technique with the ConfigurationManager to retrieve these values from the Web.config file instead of from a database.

Just another free-be, this is some code that I've used to take advantage of SQL Server's SqlCacheDependency. You'd have to enable the SQL Server Broker, but this allows you to keep values cached in memory until the value has changed in SQL Server. That way, you don't have an arbitrary 5-minute expiration.

This function was intended retrieve things with a two-part identifier (like the full name of a user), so it takes three parameters: - The SQL query to run in case the value isn't cached - The unique ID of the item you're wanting to retrieve (ie, the User ID) - An arbitrary string that identifies the type of data (ie, "UserFullName", "UserEmail")

You could very easily adapt this to retrieve things with one-part identifiers:

// Static constructor ensures that SqlDependency.Start is called before
// we try to use any SqlCacheDependencies   
static Functions()
{
    SqlDependency.Start(ConnectionString);
}

public static string GetUserFullName(string UserName)
{
    return GetSqlCachedValue("SELECT FirstName + ' ' + LastName FROM dbo.tblUser WHERE UserName = @Id", UserName, "UserFullName").ToString();
}

public static string GetEventNameFromId(int Id)
{
    return GetSqlCachedValue("SELECT EventName FROM dbo.tblEvents WHERE EventID = @Id", Id, "EventName").ToString();
}

private static object GetSqlCachedValue(string Query, object Id, string CacheName)
{
    // Get the cache
    System.Web.Caching.Cache currentCache = HttpContext.Current.Cache;

    object Value = null;

    // We use a standard naming convention for storing items in the application's cache
    string cacheKey = string.Format("{0}_{1}", CacheName, Id.ToString());

    // Attempt to retrieve the value
    if (currentCache != null && currentCache[cacheKey] != null)
        Value = currentCache[cacheKey];

    // If the value was not stored in cache, then query the database to get the value
    if (Value == null)
    {
        // Run the query provided to retrieve the value. We always expect the query to have the @Id parameter specified, that we can use
        // to plug-in the Id parameter given to this function.
        SqlCommand Command = new SqlCommand(Query);
        Command.Parameters.AddWithValue("@Id", Id);

        // Generate a cache dependency for this query
        System.Web.Caching.SqlCacheDependency dependency = new System.Web.Caching.SqlCacheDependency(Command);

        // Run the query
        DataTable dt = RunSqlCommand(Command);

        if (dt.Rows.Count == 1)
        {
            // Grab the value returned
            Value = dt.Rows[0][0];

            // Save the value in the cache, so next time we don't have to query SQL Server
            if (currentCache != null)
            {
                currentCache.Insert(cacheKey, Value, dependency);
            }
        }
    }

    // return the final value
    return Value;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜