Tuesday, June 24, 2014

Cache!

Based on this, I got an example of using the cache in an ASP.NET MVC application working. I will keep a simple model in the cache in the example that follows. In C# my object looks like so:

namespace PiggyBank.Models
{
   public class Money
   {
      public decimal Amount { get; set; }
      public string Curreny { get; set; }
   }
}

 
 

A view manages what goes in the cache and looks like this:

 
 

More specifically, the Razor markup for the view looks like this:

@{
   Layout = null;
}
@model PiggyBank.Models.Money
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
   @Html.EditorFor(model => model.Amount)
   @Html.EditorFor(model => model.Curreny)
   @:...are in the bank.
   <input type="submit" value="change this?"/>
}
<a href="/">refresh</a>

 
 

The "refresh" link will just go to the same URL one is already at while the form itself updates the cache. The view should always show what is in the cache so clicking the "refresh" link will not show the user what he/she first saw upon spinning up the app if he/she has changed the cache with the form. I am pleased to say that it all works! My controller is as follows. I had to add in the System.Runtime.Caching namespace to get this to work. It was not an included reference by default for an ASP.NET MVC Web API application.

using System;
using System.Runtime.Caching;
using System.Web.Mvc;
using PiggyBank.Models;
namespace PiggyBank.Controllers
{
   public class HomeController : Controller
   {
      private string _piggybankinnards = "piggybankinnards";
      private ObjectCache _cache{ get { return MemoryCache.Default; } }
      
      public ActionResult Index()
      {
         Money money = GetCache() as Money;
         return View(money);
      }
      
      [HttpPost]
      public ActionResult Index(Money money)
      {
         SetCache(money);
         return View(money);
      }
      
      private object GetCache()
      {
         if (_cache[_piggybankinnards] != null)
         {
            return _cache[_piggybankinnards];
         } else {
            return new Money()
            {
               Amount = 0m,
               Curreny = "Dollars"
            };
         }
      }
      
      private void SetCache(Money money)
      {
         if (_cache[_piggybankinnards] != null)
         {
            _cache.Remove(_piggybankinnards);
         }
         CacheItemPolicy life = new CacheItemPolicy();
         life.AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(30);
         _cache.Add(new CacheItem(_piggybankinnards, money), life);
      }
   }
}

No comments:

Post a Comment