Geekbeing

I hack, I break, I fix.

Caching in ASP .NET (With C# Examples) – Part 1

| Comments

It hasn’t really ever got to me, until now, that even though at work I’m using ASP .NET on daily basis I wasn’t blogging that much about it. And so I thought this gotta change. I’m not a berserker, blindly believing in everything Microsoft does, but I’ve been working with Windows, Active Directory, Visual Studio, .NET Framework long enough to tell you that amount of technologies they have developed is just striking. People often tend to think Microsoft is Windows and Office and then maybe some geeky software like Visual Studio. But this is so not true. From now on I’ll definitely focus some more on Redmond’s breed, starting off today with caching in ASP .NET.

Basically there are three main types of caching:

  1. Output cache – by declaring @OutputCache directive in .aspx page.  There are two required attributes - Duration and VaryByParam). Durations instructs for how long results should be cached, VaryByParam allows caching the same page if different values for a given parameter are passed in query string. Sample solution available for download presents how it works. VaryByParam.aspx page presents this behavior, there are five links, each of them with @OutputCache set to 60, configured to vary by parameter called ‘varryingParam’, click around and see how the application behaves.
  2. Fragment caching – in my mind it’s a subset of Output caching but this time used on controls (.ascx). Since control using @OutputCache directive is dynamically built and served on first request (very first request or each first subsequent after cache for a given control expires) you cannot dynamically modify the control, this will result in NullReferenceException when you refresh the page. This is because effectively control won’t be created if you access the page where it’s used before cache expires(BrokenForm.aspx and CorrectForm.aspx show you how to use and break it)
  3. Data caching – this is the widest topic, with a lot of knowledge to cover. I’ll create  a separate post on this one. Basically whenever we would like to spare a few roundtrips to the database or calling the web-service, or running time demanding calculation, in general – everywhere where getting the result we would like to present/make use of takes a lot of time and where at the same time we can assume information is not volatile. Or at least that it is volatile in such a minor extent we can safely ignore it for our purposes.

This focuses on caching in general, without getting into details of any of the abovementioned techniques and we haven’t even scratched the surface of data caching. I’ll try to come up with something really nice to show you, in the meantime – I’d love to hear your comments and suggestions (e.g. to update the samples, add more examples, more explanations on anything). I hope this helps and here’s sample solution again - Geekbeing.Caching. Happy caching.

Comments