NCache, simple caching of objects.

In the previous post I have introduced you to NCache architecture. In this post we will create our first cache (locally) and we will write some C# code to interact with this cache.

For the purpose of this series I have created a very simple WPF 4.0 application available from my SkyDrive (see below at the end of this post) that you can download and run locally; but of course you need to install NCache in your development machine.

SNAGHTML347a43

With this very simple WPF application (even if very simple it works with IoC and MVVM) I have a Listbox that will provide a list of items (books titles). The list will be retrieved with the first command from a database, with the second command from the cache and with the third command the cache will be cleared. The cache is populated automatically after you retrieve the data from the database.

Note: I am including the full source code of this series but this is not a series about MVVM and/or WPF so I will not provide that code inside the posts in order to stay focus on the topic, which is NCache.

Create a new local cache

First of all we need to create a new cache in NCache and this can be easily accomplished using the UI of NCache. Open you instance of NCache and create a new local cache, which is going to be more than enough for our demo.

The following picture shows the steps you need to follow to create a default local cache in your system.

image

  1. Create a new local cache
  2. Select the current machine as the destination of the local cache
  3. Name the cache
  4. Configure the memory allowed by this cache
  5. Configure the objects lifecycle for the cache

At this point, NCache will create the new cache and if you have configure it to startup the cache right away, the NCache IDE will open a new window showing you the NCache health status. From this window you can monitor the amount of objects created by the cache and many other functionalities.

Retrieve the data from the database

In this project I have created a very simple database structure that contains a table with a bunch or rows, each row represents a Book record. The data is retrieved using Entity Framework and this is the code used to populate the Listbox:

   1: public IList<Book> GetListOfBooks()

   2: {

   3:     using (var orm = new ORM())

   4:     {

   5:         var results = orm.GetListOfBooks();

   6:         return results

   7:             .Select(result => 

   8:                 new Book {Title = result.Title, ISBN = result.ISBN})

   9:                 .ToList();

  10:     }

  11: }

The data is then DataBound to a WPF listbox using the MVVM pattern:

   1: <ListBox 

   2:    Grid.Column="0" Grid.Row="1" Grid.RowSpan="3" 

   3:    Style="{StaticResource ListboxStyle}" 

   4:    ItemsSource="{Binding Books,IsAsync=True}">

   5:     <ListBox.ItemTemplate>

   6:         <DataTemplate>

   7:             <StackPanel>

   8:                 <TextBlock Text="{Binding ISBN}" />

   9:                 <TextBlock Text="{Binding Title}" />

  10:             </StackPanel>

  11:         </DataTemplate>

  12:     </ListBox.ItemTemplate>

  13: </ListBox>

And the listbox shows the final results:

SNAGHTML2369f4c

Retrieve the data from the cache

The second command of the UI is calling the cache, instead of calling the database, to retrieve the data. But, how does it work? I have drawn below a very simple logical flow that my application follows in order to retrieve the data from the cache, when available.

image

And this is how it works:

   1: // initialize the cache

   2: using (Cache cache = NCache.InitializeCache("Cache"))

   3: {

   4:     var list = new List<Book>();

   5:     // if cache empty, populate the cache

   6:     if (cache.Count == 0)

   7:     {

   8:         IList<Book> books = GetListOfBooks();

   9:         foreach (Book book in books)

  10:         {

  11:             cache.Add(book.ISBN, book);

  12:         }

  13:     }

  14: }

Of course this is just a simple implementation to show you how the NCache mechanism works. It is like working with a simple dictionary of objects if you are not implementing NCache on top of another caching framework.

As soon as you add the items to the cache, the NCache management studio will show you the new objects cached in the system:

image

Few final notes

  • First of all you need to orchestrate your application in a way that the cache will be bootstrapped with the application, bootstrapping the cache in a method of the data layer like I did it is absolutely wrong!
  • The objects contained inside the cache, like any other cache system, must be serializable otherwise you will receive a nice runtime exception from NCache.