ASP..
In order to complete this walkthrough, you will need:
· Microsoft Visual Studio 2010.
· Two text files, each containing a small amount of text. You will display the contents of the text files in a Web page.
You will start by creating an ASP.NET Web site.
To create an ASP.NET Web site
1. Start Visual Studio 2010 or Visual Web Developer Express 2010.
2. In the File menu, click New Web Site. (If you do not see this option, click New, and then click Web Site.)
The New Web Site dialog box is displayed.
3. Under Installed Templates, click Visual Basic or C# and then select ASP.NET Web Site.
4.
1. In Solution Explorer, right-click the name of the project and then click Add Existing Item.
2. In the Add Existing Item dialog box, select the text file that you want to use for this walkthrough, and then click Add to add one text file.
3. Repeat the steps to add the second text file
To use the caching classes that are defined in the System.Runtime.Caching namespace in an ASP.NET application, you must add a reference to the namespace.
To add a reference the Website
4. In Solution Explorer, right-click the name of the Web site and then click Add Reference.
5. Select the .NET tab, select System.Runtime.Caching, and then click OK..
To add controls to the page
6. From the Standard tab of the Toolbox, drag two Button controls to the Default.aspx page.
7. In the Properties window, set the Text property of one of the Button controls to Get from Built-In Cache. Accept the default ID property.
8. Set the Text property of the other Button control to Get from Custom Cache. Accept the default ID property.
9.:.
To create an instance of the built-in memory cache object
10. Double-click the Get from Built-In Cache button to create an event handler in the Default.aspx.cs or Default.aspx.vb file.
11. At the top of the file (before the class declaration), add the following using (C#) or Imports (Visual Basic) statements.
[Visual Basic]
Imports System.Runtime.Caching
Imports System.IO
[C#]
using System.Runtime.Caching;
using System.IO;
12. In the event handler, add the following code to instantiate the cache.
Dim cache As ObjectCache = MemoryCache.Default
ObjectCache cache = MemoryCache.Default;
The System.Runtime.Caching.ObjectCache class provides an in-memory object cache.
Note The System.Runtime.Caching.ObjectCache class is a replacement for the System.Web.Caching.Cache class. In ASP.NET 4, caching is implemented by using the System.Runtime.Caching.ObjectCache class.
13. Add the following code to read the contents of a cache entry named filecontents.
Dim fileContents As String = TryCast(cache("filecontents"), String)
string fileContents = cache["filecontents"] as string;
14. Add code to perform the following tasks:
a. Check whether the cache entry named filecontents exists. If the specified cache entry does not exist, you must read the text file and add it as a cache entry to the cache.
b. Create a new System.Runtime.Caching.CacheItemPolicy object that specifies that the cache expires after 10 seconds.
c. Create a collection for the file paths you want to monitor and to add the path of the text file to the collection.
d. Add a new System.Runtime.Caching.HostFileChangeMonitor object to the collection of change monitors for the cache entry. The System.Runtime.Caching.HostFileChangeMonitor object monitors the text file's path and notifies the cache if changes occur. In this example, the cache entry will automatically expire if the contents of the file changes.
e. Read the contents of the text file.
f. Insert the contents of the file into the cache object as a System.Runtime.Caching.CacheItem instance. You specify information about how the cache entry should be evicted by passing the System.Runtime.Caching.CacheItemPolicy object as a parameter Set method.
The following example shows code that accomplishes these tasks.
If fileContents Is Nothing Then
Dim policy As New CacheItemPolicy()
policy.AbsoluteExpiration = _
DateTimeOffset.Now.AddSeconds(10.0)
Dim filePaths As New List(Of String)()
Dim cachedFilePath As String = Server.MapPath("~") & _
"\cacheText.txt"
filePaths.Add(cachedFilePath)
policy.ChangeMonitors.Add(New _
HostFileChangeMonitor(filePaths))
' Fetch the file contents.
fileContents = File.ReadAllText(cachedFilePath) & _
vbCrLf & " Using built-in cache " & _
DateTime.Now.ToString()
cache.Set("filecontents", fileContents, policy)
End If);
}
15. Add the following code to display the cached file content in a Label control.
Label1.Text = fileContents
Label1.Text = fileContents;
Next, you will create a custom cache class named CustomCache. In this example, the custom class will inherit from the build-in System
16. In Solution Explorer, right-click the name of the Web site and then click Add New Item.
The New Item dialog box is displayed.
17. Under Installed Templates, select Visual Basic or Visual C# and the select Class.
18. In the Name text box, enter the name CustomCache and then click Add.
19. In the dialog box that appears, click Yes to put the class in the App_Code folder
20. In the code editor, replace the existing contents of the class file with the following code:
Imports System
Imports System.Web
Namespace CustomCacheSample
Public Class CustomCache
Inherits MemoryCache
Public Sub New()
MyBase.New("defaultCustomCache")
End Sub
Public Overrides Sub Set(ByVal item As CacheItem, _
ByVal policy As CacheItemPolicy)
Set(item.Key, item.Value, policy, item.RegionName)
Public Overrides Sub Set(ByVal key As String, _
ByVal value As Object, _
ByVal absoluteExpiration As DateTimeOffset, _
Optional ByVal regionName As String = Nothing)
Set(key, value, New CacheItemPolicy _
With {.AbsoluteExpiration = absoluteExpiration}, _
regionName)
ByVal value As Object, _
ByVal policy As CacheItemPolicy, _
Optional ByVal regionName As String = Nothing)
MyBase.Set(CreateKeyWithRegion(key, regionName), _
value, policy)
Public Overrides Function GetCacheItem(ByVal key As String, _
Optional ByVal regionName As String = Nothing) As CacheItem
Dim temporary As CacheItem = _
MyBase.GetCacheItem(CreateKeyWithRegion(key, regionName))
Return New CacheItem(key, temporary.Value, regionName)
End Function
Public Overrides Function Get(ByVal key As String, _
Optional ByVal regionName As String = Nothing) As Object
Return MyBase.Get(CreateKeyWithRegion(key, regionName))
Public Overrides ReadOnly Property DefaultCacheCapabilities() _
As DefaultCacheCapabilities
Get
Return (MyBase.DefaultCacheCapabilities Or _
System.Runtime.Caching.DefaultCacheCapabilities.CacheRegions)
End Get
End Property
Private Function CreateKeyWithRegion(ByVal key As String, _
ByVal region As String) As String
Return "region:" & (If(region Is Nothing, "null_region", _
region)) & ";key=" & key
End Class
End Namespace
using System;
using System.Web;;
}
21. Save the file..
To create an instance of the custom cache object and add a cache entry
22. Switch to or open the Default.aspx file.
23. Double-click the Get from Custom Cache button to create an event handler in the Default.aspx.cs or Default.aspx.vb file.
24. At the top of the file (before the class declaration), add the following Imports (Visual Basic) or using (C#) statements to add the namespace the custom class is in.
Imports CustomCacheSample
using CustomCacheSample
25. In the class declaration, add the following code to instantiate the custom cache. You must create and keep the reference of the custom cache to prevent it from going out of scope.
Private Static customCache As ObjectCache = _
New CustomCache()
Private ReadOnly Property RegionCache() As ObjectCache
Get
Return customCache
End Get
End Property
private static ObjectCache customCache =
new CustomCache();
private ObjectCache RegionCache { get { return customCache; } }
26. In the event handler, add the following code to read the contents of a cache entry named CustomFilecontents from the RegionCache cache.
Dim CustomFileContents As String = _
TryCast(RegionCache.[Get](" CustomFileContents ", "Region_A"), String)
string CustomFileContents = RegionCache.Get("CustomFileContents", "Region_A") as string;
27. Add code to perform the following tasks:
a. Check whether the cache entry named CustomeFilecontents exits. If the specified cache entry does not exist, you must read the text file and add it as a cache entry to the cache.
b. Read the text file
c. System.Runtime.Caching.ObjectCache.InfiniteAbsoluteExpiration field as a parameter in the Set method. Instead, items will expire only when there is memory pressure.
The following example shows how to accomplish these tasks
Note The “Using custom cache” string is added to the text of the text file to help you identify the cached data when you test the page later in this walkthrough.
If CustomFileContents Is Nothing Then
' Fetch the file contents.
"\cacheText2.txt"
CustomFileContents = File.ReadAllText(cachedFilePath) _
& " Using custom cache " & + DateTime.Now.ToString()
' For this cache region, don't bind a file-change monitor.
RegionCache.Set("CustomFileContents", CustomFileContents,
ObjectCache.InfiniteAbsoluteExpiration, "Region_A")
if (CustomFileContents == null)
//Fetch the file contents
string cachedFilePath = Server.MapPath("~") + "\\cachedText.txt";
filePaths.Add(cachedFilePath);
CustomFileContents = File.ReadAllText(cachedFilePath) +
" Using custom cache " + "\n" + DateTime.Now.ToString();
// For this cache region, don't bind a file-change monitor
RegionCache.Set("CustomFileContents", CustomFileContents,
ObjectCache.InfiniteAbsoluteExpiration, "Region_A");
28. Add the following code to display the cached file content in a Label control.
Label1.Text = CustomFileContents
Label1.Text = CustomFileContents;
29.
You can now test the application.
To test caching in the ASP.NET Web site
30. Press CTRL+F5 to run the application.
31. Click Get from Built-in Cache.
The cached content in the text file is displayed in the label. Notice the "Using built-in cache" statement and the time stamp at end of the file.
32. Click Get from Custom Cache.
The cached content in the text file is displayed in the label. Notice the "Using custom cache" statement at the end of the file.
33. Click Get from Built-in Cache again.
The timestamp is unchanged. This indicates the cached content is displayed.
34. Wait 10 seconds or more and then click Get from Built-in Cache again.
This time a new timestamp is displayed. This indicates that the policy lets the cache expire after 10 seconds and that new cached content is displayed.
35. Click Get from Custom Cache.
The cached content in the text file is displayed in the label. Notice the "Using custom cache" statement and the time stamp at the end of the file.
36. Click Get from Custom Cache again. The timestamp is unchanged. This indicates the cached content is displayed.
37. Wait 10 seconds or more and then click Get from Custom Cache again.
The timestamp is still unchanged. This indicates that the cache does not expire based on a policy. However, when the server starts run low on memory, the cache will automatically expire.
- Philip AttipoeASP.NET User EducationThis posting is provided "AS IS" with no warranties, and confers no rights.
- Philip AttipoeASP.NET User EducationThis posting is provided "AS IS" with no warranties, and confers no rights.