Friday, July 29, 2011

ASP.NET 2 caching, MVC3 OutputCache with Razor

ASP.NET 2.0
 
Web caching technology in ASP.NET and C# is helpful 
for popular website reducing its server workload and improving access 
times. This tutorial will show you how to use web caching save data to 
RAM, and improve data access times therefore.
First, import the namespace of System.Web.Caching
using System.Web.Caching
Try Server Intellect for Windows Server Hosting. Quality and Quantity!
Declare the variables
static bool itemRemoved = false;
static CacheItemRemovedReason reason;
CacheItemRemovedCallback onRemove = null;
We used over 10 web hosting companies before we found Server Intellect. Their dedicated servers and add-ons were setup swiftly, in less than 24 hours. We were able to confirm our order over the phone. They respond to our inquiries within an hour. Server Intellect's customer support and assistance are the best we've ever experienced.
Define the method of AddItemToCache, it will use Cache.Add to add items to cache

public void AddItemToCache(Object sender, EventArgs e)
{
itemRemoved = false;

onRemove = new CacheItemRemovedCallback(this.RemovedCallback);

if (Cache["Key1"] == null)
Cache.Add("Key1", "Caching", null, DateTime.Now.AddSeconds(60), TimeSpan.Zero, CacheItemPriority.High, onRemove);
}

Define the method of RemoveItemFromCache, it will use Cache.Remove to remove items from cache

public void RemoveItemFromCache(Object sender, EventArgs e)
{
if (Cache["Key1"] != null)
Cache.Remove("Key1");
}
If you're ever in the market for some great Windows web hosting, try Server Intellect. We have been very pleased with their services and most importantly, technical support.
When using the method of Cache.Remove , it will be leaded to invoke RemovedCallback method

public void RemovedCallback(String k, Object v, CacheItemRemovedReason r)
{
itemRemoved = true;
reason = r;
}
If you're looking for a really good web host, try Server Intellect - we found the setup procedure and control panel, very easy to adapt to and their IT team is awesome!
Page_Load

protected void Page_Load(object sender, EventArgs e)
{
if (itemRemoved)
{
Response.Write("RemovedCallback event raised.");
Response.Write("<BR>");
Response.Write("Reason: <B>" + reason.ToString() + "</B>");
}
else
{
Response.Write("Value of cache key: <B>" + Server.HtmlEncode(Cache["Key1"] as string) + "</B>");
}
}
We chose Server Intellect for its dedicated servers, for our web hosting. They have managed to handle virtually everything for us, from start to finish. And their customer service is stellar.
The HTML of the web page

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>

<body>
<Form id="Form1" runat="server">
<input id="Submit1" type=submit OnServerClick="AddItemToCache" value="Add Item To Cache" runat="server"/>
<input id="Submit2" type=submit OnServerClick="RemoveItemFromCache" value="Remove Item From Cache" runat="server"/>
</Form>

</body>
</html>
 
 
ASP.NET 4.0 RAZOR
 
@{
    var cacheItemKey = "Time";
    var cacheHit = true;
    var time = WebCache.Get(cacheItemKey);

    if (time == null) {
        cacheHit = false;
    }

    if (cacheHit == false) {
        time = @DateTime.Now;
        WebCache.Set(cacheItemKey, time, 1, false);
    }
}<!DOCTYPE html>
<html>
<head>
    <title>WebCache Helper Sample</title>
</head>
<body>
    <div>
        @if (cacheHit) {
            @:Found the time data in the cache.
        } else {
            @:Did not find the time data in the cache.
        }
    </div>
    <div>
        This page was cached at @time.
    </div>
</body>
</html>
 
OR
 
[OutputCache(Duration=10, VaryByParam="none")]
public ActionResult Index()
{
    return View();
}
 
OR 

public ActionResult Index()
{
    WebCache.Set(key, data, minutesToCache, false);
    return View();
}
 
 
OR
Гараар бичсэн Cache чадвартай объектын жишээ

public abstract class DataLoader
    {
        private static readonly Hashtable _buffer = new Hashtable();
        private static readonly Hashtable _cached = new Hashtable();
       
        // Data Buffer
        protected void setBuffer(dynamic data)
        {
            setBuffer(this.GetType().FullName, data);
        }

        private void setBuffer(string type, dynamic data)
        {
            Hashtable hash = null;
            if (_buffer.ContainsKey(type))
                hash = (Hashtable)_buffer[type];
            else
            {
                hash = new Hashtable();
                _buffer.Add(type, hash);
            }
            if (hash.ContainsKey(WebSites.Current.Name))
                hash[WebSites.Current.Name] = data;
            else
                hash.Add(WebSites.Current.Name, data);
        }

        protected dynamic getBuffer()
        {
            return getBuffer(this.GetType().FullName);
        }

        private dynamic getBuffer(string type)
        {
            Hashtable hash = null;
            if (_buffer.ContainsKey(type))
                hash = (Hashtable)_buffer[type];
            else
            {
                hash = new Hashtable();
                _buffer.Add(type, hash);
            }
            if (hash.ContainsKey(WebSites.Current.Name))
                return hash[WebSites.Current.Name];
            else
                return null;
        }

        public object Ready(int cacheSecond, params object[] args)
        {
            dynamic data = getCache();
            if (data == null)
            {
                data = Load();
                setCache(cacheSecond, data);
            }
            return data;
        }

        protected abstract dynamic Load();

        protected void setCache(int cacheSecond, dynamic data)
        {
            string type = GetType().FullName;
            Hashtable hash = null;

            if (_cached.ContainsKey(type))
                hash = (Hashtable)_cached[type];
            else
            {
                hash = new Hashtable();
                _cached.Add(type, hash);
            }
           
            DataCacheModel model = new DataCacheModel();
            model.set(cacheSecond, data);
           
            if (hash.ContainsKey(WebSites.Current.Name))
                hash[WebSites.Current.Name] = model;
            else
                hash.Add(WebSites.Current.Name, model);
        }

        protected dynamic getCache()
        {
            string type = GetType().FullName;
            Hashtable hash = null;

            if (_cached.ContainsKey(type))
                hash = (Hashtable)_cached[type];
            else
            {
                hash = new Hashtable();
                _cached.Add(type, hash);
            }
            if (hash.ContainsKey(WebSites.Current.Name))
                return ((DataCacheModel)hash[WebSites.Current.Name]).get();
            else
                return null;
        }
    }

No comments: