This blog is part of a series of blog post about the Q42.WinRT open source toolkit for Windows 8.

The open source Q42.WinRT library contains helpers for caching images and data in your application. A lot of data from API calls and images used in your app come directly from the internet. But if the user opens your app when he is offline, it would be great if all the data is still available.

Caching Images

Showing an image from an URL in XAML is easy.
<Image Source="http://www.mydomain.com/image.png" />

This shows a nice image. The image is loaded from the specified URL and can only be shown when there's an internet connection. When the app is closed and re-open, the image will be downloaded again.

The Q42.WinRT library contains an attached property called ImageExtensions.CacheUri. Using it in your app is just as easy as setting the source property:
<Image q42controls:ImageExtensions.CacheUri="http://www.mydomain.com/image.png" />

Now the image is cached. The first time it will be downloaded and stored in the local storage. The second time the image is rendered, the cached image is used and no download is made. This is a great solution for images that don't change and saves bandwidth. Don't use if for images that get updated frequently!

The image cache uses a custom component called WebDataCache. It can store the result of any URL input to the local storage and returns a custom URI to the stored data in the ms-appdata:///local/ format.

Caching results from API calls

The Q42.WinRT library also contains a nice little helper to cache the result of an API call that has a string or object as result which is serializable to JSON result.

Using this cache is easy:
JsonCache.GetAsync("samplekey", () => LongRunningOperation())

If the cache key "samplekey" is found, it will return the result directly from the cache. If the key is not found, it will run the "LongRunningOperation". The return type of the LongRunningOperation can be a string or object or list of objects. These will be serialized to JSON using Newtonsoft.Json and written to the local storage.
When the data is loaded, the objects will be deserialized and returned immediately.

The data and  image caching is part of the open source Q42.WinRT library. A fully working sample is available in the Q42.WinRT library on GitHub:
https://github.com/Q42/Q42.WinRT