Archive for 'C#'

I spent the weekend working on writing a better API wrapper for Litmos, if you don’t know what Litmos is it’s a Learning Management System; it’s quite simple and uses ExtJS in some parts and has a nice REST API for management which is the part I’ve been wrapping.

Litmos itself provides a .NET 3 WCF service however it’s limited and requires you to know/understand the underlying REST calls. I removed these requirements and wrote it as an object orientated framework for .NET 2.0. Currently it’s only available as a repository checkout from Google Code but I’m working on a proper binary release.

Check out the project space here.

Quick ASP.NET Caching (0)

July 17th, 2009 by Lloyd, under AJAX, ASP.NET, C#, Web Development.

One thing we’ve often found useful but underused is response caching, especially in the Web 2.0 world. There are a variety of options available and here’s a quick example of how to use the built in caching in ASP.NET.

For our example we’re going to cache for no more than 10 minutes, you can alter this as suits you. We’re also caching on an absolute time-scale but ASP.NET lets you also set a sliding time-scale.

public void ProcessRequest(HttpContext context)
{
        // Set Content Type
        context.Response.ContentType = "application/json";

        // Set key
        string key = "mydata";

        // Check cache for our hash
        object cache = context.Cache.Get(key);

        if (cache != null) {
            // Write out cached item
            context.Response.Write("/* From Cache */\r\n");
            context.Response.Write(cache.ToString());
            context.Response.Flush();

            // Return
            return;
        }

        // Get JSON from database or wherever
        string json = "{test:'Hello'}";

        context.Response.Write(json);
        context.Response.Flush();

        // Add response to cache
        context.Cache.Insert(
            key,
            json,
            null,
            DateTime.UtcNow.AddMinutes(10),
            System.Web.Caching.Cache.NoSlidingExpiration
        );
}

What happens is on the request we first check the cache for key. If we find that the cached item exists we retrieve this from the cache and dump that into the response.

If the item doesn’t exist however we generate the item content, be it a database call or whatever. Here this is mostly some kind of JSON so once we have the content we’d normally return we again dump that into the response but this time we also add it to the cache with the same key.

Caching is great for reducing load on databases and processing time, especially with commonly returned data such as dropdown lists who’s data rarely changes.

For further reading and a more fuller introduction to ASP.NET caching click here.