Saturday, 19 January 2013

New Object Caching Option Introduce in .Net 4.0 with C# Examples and VB.Net Examples

Click to Download C# Example CachingFileDependencyInCSharp.zip
Click to Download VB.NET Example CachingFileDependencyInVBNet.zip


Before .Net 4.0 we are using System.Web.Caching.Cache object. Now in .Net 4.0 introduce same system.web.caching functionality in System.Runtime.Caching.dll everything was rebuilt into the new namespace of System.Runtime.Caching.

The reason for this is that the System.Web.Caching.Cache object was so useful that other application developers like Windows Forms, Windows Presentation Foundation apps, and more were need to bring the System.Web namespace into their projects to make use of this cache object. So, to remove this dependency this was all extracted out and extended with the System.Runtime.Caching namespace.

As an ASP.NET developer, we can still use of the System.Web.Caching.Cache object just as we did in all the earlier versions of ASP.NET. It isn’t going away. However, it is important to note that as the .NET Framework evolves, the .NET team will be making its investments into the System.Runtime.Caching namespace rather than System.Web.Caching.

This means that over time, we will most likely see additional enhancements in the System.Runtime.Caching version that changes does not appear in the System.Web.Caching namespace as you might expect.  it does not also mean that we need to move everything over to the new System.Runtime.Caching namespace to make sure we are following the strategic path of Microsoft, because the two caches are managed together under the covers.

Here is example for this.

In this example we are using the cache from the System.Runtime.Caching namespace. We are taking one Label control that shows the name of a user that is stored in an XML file. Name of the XML file is "Userdetail.xml". This file exist in root location of project. HostFileChangeMonitor class look at directories and file paths and monitor for change. So, when the XML file changes, that triggers an invalidation of the cache.

By Running this code when first time this code run you can see user name "Lion" on screen after the you again refresh the page you again see user name "Lion" on page. But after when you change user name in XML file and refresh the page you see the new user name "Tiger" on screen. You will get more idea by debugging the code. You can download sample example using above link.

XML File ("UserDetail.xml") :
<?xml version="1.0" encoding="utf-8" ?>
<usernames>
  <user>Tiger</user>
</usernames>

C#. Net Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Xml.Linq;

public partial class FileDependencyExample : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ObjectCache objCache = MemoryCache.Default;

        string objUserNameFromXml = objCache["UserNameFromXmlFile"] as string;

        if (objUserNameFromXml == null)
        {
            List<string> LstFilePath = new List<string>();

            LstFilePath.Add( Server.MapPath("UserDetail.xml"));

            CacheItemPolicy objPolicy = new CacheItemPolicy();

            objPolicy.ChangeMonitors.Add(new HostFileChangeMonitor(LstFilePath));

            XDocument objXdoc = XDocument.Load(Server.MapPath("UserDetail.xml") );

            var objQuery = from t in objXdoc.Elements("usernames")
                            select t.Value;

            objUserNameFromXml = objQuery.First().ToString();

            objCache.Set("UserNameFromXmlFile", objUserNameFromXml, objPolicy);

        }

        lblUserName.Text = objUserNameFromXml;
    }
}

VB.Net Examples :


Imports System.Collections.Generic
Imports System.Linq
Imports System.Runtime.Caching
Imports System.Xml.Linq

Partial Class FileDependencyExample
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim objCache As ObjectCache = MemoryCache.Default

        Dim objUserNameFromXml As String = TryCast(objCache("UserNameFromXmlFile"), String)

        If objUserNameFromXml Is Nothing Then

            Dim LstFilePath As New List(Of String)()

            LstFilePath.Add(Server.MapPath("UserDetail.xml"))

            Dim objPolicy As New CacheItemPolicy()

            objPolicy.ChangeMonitors.Add(New HostFileChangeMonitor(LstFilePath))

            Dim objXdoc As XDocument = XDocument.Load(Server.MapPath("UserDetail.xml"))

            Dim objQuery = From u In objXdoc.Elements("usernames")
                            Select u.Value

            objUserNameFromXml = objQuery.First().ToString()


            objCache.Set("UserNameFromXmlFile", objUserNameFromXml, objPolicy)
        End If

        lblUserName.Text = objUserNameFromXml

    End Sub
End Class

Output ("Before Changing User Name") :


Output ("After Changing User Name") :

Note : If you are getting error messaging on importing "System.Runtime.Caching" namespace at that time go to the project and "Add Reference" of System.Runtime.Caching.dll.

1 comment:

  1. It is really a great work and the way in which u r sharing the knowledge is excellent.Thanks for helping me to understand basic concepts. As a beginner in Dot Net programming your post help me a lot.Thanks for your informative article. dot net training in velachery | dot net training institute in velachery

    ReplyDelete