Create cache configuration objects for ASP. NET [reprint]

Source: Internet
Author: User
Create cache configuration objects for ASP. NET released on: 4/1/2004 | updated on: 4/1/2004

Steven A. Smith

Aspalliance.com

Applicable:

Microsoft ASP. NET

Abstract:Learn how the cacheconfig helper class improves cache policies in ASP. NET applications, how to improve cache data reuse, and how to significantly reduce the number of code lines to implement cache using best practices. This document is based on ASP. NET Caching: techniques and best pratices. (7 page printing)

Download cacheconfigdemo. MSI.

Content on this page

Introduction
Configuration
First use
Basic Method: decache
Usage: Add cache support for the data access layer
Summary
Resources

Introduction

If you have not read ASP. NET Caching: Techniques and Best Practices, please read. This article is mainly based on the content of this article, especially the best practices. This article describesCacheconfigClass, which provides packaging for cache objects in Microsoft ASP. NET. This class exposes a very simple method to complete most of the public cache work in ASP. NET applications. UseCacheconfigClass, you can enable or disable caching through the flip configuration settings, manage all cache items and their cache duration through the configuration settings, or use only one line of code, use the best practices described in the previous article to access the cache.

Back to Top

Configuration

CacheconfigRead all configuration settings from the Web. config file. The specified section and each key value in the Section are defined as static strings by default, as shown in Sample Code 1.

Sample Code1.Configuration section and key name

protected static string cacheSettingsConfigName = "CacheSettings"; protected static string EnableCachingKey = "EnableCaching"; protected static string RequireKeyDefinitionInConfigKey =    "RequireKeyDefinitionInConfig"; protected static string DefaultCacheDurationUnitsKey =    "DefaultCacheDurationUnits"; protected static string DefaultCacheDurationValueKey =    "DefaultCacheDurationValue"; 

By default, allCacheconfigConfiguration settings are stored in the custom configuration section named "cachesettings. This section is defined as a simple namevaluecollection, just like the built-in appsettings configuration section. The new configuration section must be defined in Web. config, as shown in code example 2.

Sample Code2.InWeb. configDefinitionCachesettingsConfiguration section

<configSections> <section name="CacheSettings"    type="System.Configuration.NameValueFileSectionHandler, System,    Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"    /> </configSections> 

The <configsections> element must be the first element in the web. config configuration element.

Once this section is defined in Web. config and the appropriate key is added, it will be managed in the ApplicationCacheconfigClass. Sample Code 3 shows the sample cachesettings section.

Sample Code3. cachesettingsKey and Value

<CacheSettings> <!-- true/false --> <add key="EnableCaching" value="true" /> <!-- true/false --> <add key="RequireKeyDefinitionInConfig" value="true" /> <!-- seconds, minutes, or hours --> <add key="DefaultCacheDurationUnits" value="seconds" /> <!-- integer --> <add key="DefaultCacheDurationValue" value="30" /> <!-- Cache Keys and Durations -  use "default" for value to use default otherwise integer. --> <add key="AuthorsDataTable" value="default" /> <add key="AuthorsDataTableByState" value="10" /> </CacheSettings> 

First four key pairsCacheconfigThe most influential behavior. The last few keys define the cache key names and cache duration of all objects. These objects are stored inCacheconfig. Table 1 describes the effects of the previous configuration values.

Table1.Configuration settings and their effects

Set Description

Enablecaching

True/false. When it is false,CacheconfigIt is disabled and does not write or read from the cache.

Requirekeydefinitioninconfig

True/false. If it is trueCacheconfigIf a key is provided but not in Web. config, an exception is thrown.

Defaultcachedurationunits

"Seconds", "Minutes", or "hours ". Defines the unit for the duration value specified in the next section. The default cache duration for items added to the cache but not specified period.

Defaultcachedurationvalue

(Integer ). Specify the length of time that an item should be stored in the cache. Use the unit defined in defaultcachedurationunits. The default cache duration for items added to the cache but not specified period.

Because this is onlyCacheconfigSo it is very simple. In the future, the enhancement feature may support other types of key dependencies, such as files, and store the file path in the configuration just like the current settings. Most of the caches are from Microsoft SQL server? So the time-based Cache is sufficient (at least until the built-in support for ASP. NET cache APIS is invalid ).

Back to Top

First use

CacheconfigIs a completely static class (shared in Microsoft Visual Basic), which means it can never be directly instantiated. However, its method can be used directly. However, it does have a constructor that calls a constructor whenever a method is called for the first time. The static constructor executes the following tasks:

•

Load the cachesettings configuration section to the local namevaluecollection.

•

Set the local enablecaching variable according to the configuration settings.

•

Set the local requirekeydefinition variable according to the configuration settings.

•

Set the local defaultcacheduration timespan according to the configuration settings.

•

Check whether httpcontext (required for caching) is available. If not, set enablecaching to false (avoid errors when calling the data access layer from a Windows form application at design time or from a Windows form application ).

When the first referenceCacheconfigThe static constructor is called only once. However, because all the settings are stored in Web. config, any update will cause the application to be completely restarted, which of course means the next callCacheconfigThe static constructor is run again and the latest value is retrieved.

Back to Top

Basic Method: decache

The only method I call isDecache.DecacheReturns a value for the given key from the cache request. If this value does not exist in the cache,DecacheThe cache will be refilled using the method provided as the callback function, and the result of this method will be returned.CacheconfigIt can also be usedEncache ()The method is simple to add an item to the cache, but this function is rarely used.

Each data type to be cached must have a separateDecacheMethod. TheCacheconfigOnly datatable objects are supported in Version 1.0. This can easily be extended to include other objects, including system. Object (if you want the final flexibility to go beyond the strong type check), but doing so requires a lot of repetitive code. Once C # supports versatility, it can avoid a lot of such repetitive code, hoping to generate a new version of the tool.

Decachedatatable ()The method supports several reloads:

(string key, GetDataTableCallback  callback)

-When the cache needs to be empty, at least one key and one delegate are required to fill the cache.

(string key, GetDataTableCallback callback, object[]  callbackArguments)

-An array of parameters that contain callback methods.

(string key, GetDataTableCallback callback, object[]  callbackArguments, TimeSpan cacheDuration)

-Contains a duration, which will overwrite any information specified for the key in Web. config.

(string key, GetDataTableCallback callback, object[]  callbackArguments, TimeSpan cacheDuration, bool IgnoreCache)
IgnoreCache 

-If it does not exist, it is regarded as false. Setting it to true will force the cache to be skipped and the request value from the original source will be skipped.

The getdatatablecallback delegate is defined:

public delegate DataTable GetDataTableCallback(object[] args); 

In most cases, the existing method used to request data from the data source does not use the (object [] ARGs) signature. Therefore, the common practice is to use this signature to create a new private or protection method, and call it from the existing method. This example is as follows.

Back to Top

Usage: Add cache support for the data access layer

The downloadable sample application contains a very simple web application, this application has a web form used to list the authors in the pubs database and a metadata class used to query the pubs to obtain the data of these authors. Data CategoryAuthor. CSTo minimize the amount of code required for data access using Microsoft Data Access application blocks. Before adding cache support, it contains two methods:Listauthors ()AndListauthors (string state). Each method returns a datatable with authors table content. The latter uses the value of the State column to filter. Before adding cache supportListauthors ()The method is shown in sample code 4.

Sample Code4.Simple data access method not supported by Cache

public static DataTable ListAuthors() {    return SqlHelper.ExecuteDataset(ConnectionString,        CommandType.Text,        "SELECT * FROM Authors").Tables[0]; } 

UseCacheconfigTo add cache support for this method, you must first create a new overload that matches the signature of the getdatatablecalllback delegate. This means that you must return a datatable and accept an object array as its unique parameter. We will move the actual data access code to this new method, as shown in code example 5.

Sample Code5.Move the actual data access code to the method that matches the delegate.

protected static DataTable ListAuthors(object[] args) {    return SqlHelper.ExecuteDataset(ConnectionString,       CommandType.Text,       "SELECT * FROM Authors").Tables[0]; }

After creating a new method, change the original method to useCacheconfig. decache ()Method, and send a new reference to itListauthors (object [])Method callback function. Code Example 6 showsListauthors ().

Sample Code6. listauthors (), Now changed to include cache support

public static DataTable ListAuthors() {    GetDataTableCallback callback =  new GetDataTableCallback(Author.ListAuthors);    return CacheConfig.DeCacheDataTable("AuthorsDataTable",  callback, new SqlParameter[]{null}); } 

The provided sample code containsListauthors ()Is used to support filtering by state. It shares protection methods by slightly modifying the SQL statement and using the parameter arrays sent to it.

Back to Top

Summary

By referencingCacheconfigIt is used for all the cache operations supported by it. You can control more cache policies and have more confidence in using best practices to reference cache. Although it is limited to a able object and the expiration time of the current form is absolute, by using any dependencies you want to define,CacheconfigClass can be easily extended to encapsulate any other types of serializable objects that need to be cached.

Back to Top

Resources

ASP. NET Caching: Techniques and Best Practices

About the author

Steven A. Smith, Microsoft ASP. net mvp, is the President and owner of aspalliance.com. He is also the owner and chief lecturer of aspsmith Ltd (A. Net-focused training company. He has written two books: ASP. NET developer's cookbook and ASP. NET by example. He has also published articles in the msdn and aspnetpro magazines. Steve will give speeches at meetings every year. He is a member of ineta speaker's bureau and aspinsiders. Steve has a master's degree in enterprise management and a bachelor's degree in computer science engineering.

An email can be sent to the ssmith@aspalliance.com to contact Steve.

Go to the original English page


 

Back to Top

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.