ASP.NET MVC 3 Beta: Caching charts

In my previous posting about charts in ASP.NET MVC 3 I gave you basic idea about how to use them. In this posting I will show you something cool – we will optimize performance of our application by caching charts so we don’t have to generate them on every request.

Caching charts

Let’s starts with example form previous posting where cache was not used.

public ActionResult MyChart()
{
   
var model = new ChartModel
();
   
var
data = model.GetChartData();

   
new Chart(400, 200, ChartTheme
.Blue)
        .AddTitle(
"Price enquiries"
)
        .DataBindTable(data,
"X"
)
        .Write(
"png"
);

   
return null;
}

I added cache example as different action to my application to illustrate that cache support can be added using only couple of lines of code. Take a look at this code.

public ActionResult MyCachedChart()
{
   
const string chartKey = "MyCachedChart"
;
   
var chart = Chart
.GetFromCache(chartKey);

   
if (chart == null
)
    {
       
var model = new ChartModel
();
       
var
data = model.GetChartData();

        chart =
new Chart(400, 200, ChartTheme
.Blue)
                .AddTitle(
"Chart cached: "
+ DateTime.Now)
                .DataBindTable(data,
"X"
);
        chart.SaveToCache(chartKey, 1,
false
);
    }

    chart.Write(
"png"
);
   
return null;
}

We use constant key when dealing with cache. If we get chart from cache then we use the cached version. If there is no cached version we will create new chart, bind it to data and cache the instance. In this code chart is saved to cache for one minute. After that cache expires.

Application with two charts

And here is the result of our work. You can test caching by refreshing the page and reading the title of second chart. The title changes after cache timeout that is 1 minute in our application.

ASP.NET MVC application with cached chart

Although upper chart does not change it is created again and again for every request.

Conclusion

We took code example from my previous posting and added couple of lines of code to it so our charts are cached for one minute. It was extremely simple change that took no markable amount of our time. You can change the cache timeout and you can also turn on sliding expiration if it fits to your scenario better – just modify the last two parameters of WriteToCache() method.

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    2 thoughts on “ASP.NET MVC 3 Beta: Caching charts

    Leave a Reply

    Your email address will not be published. Required fields are marked *