WCF Caching and you

 

A Little Background

So I was working on a project where I needed to build a web service that used the Lync SDK to get various information about a user within our corporate network and update it to our corporate intranet. Some of which was their status, Note ( this is that little bubble over your picture or icon), phone number, Office location etc..).

As I’m sure you can tell immediately, some of this information stays the same for the most part (like phone number and Office location), but there is a portion of this that is quite dynamic and changes often. Some of which are status and note. After determining this and realizing that I am going to have update this information through some form of AJAX, the best idea in this case would be some sort of polling mechanism. At First I thought a subscription mechanism similar to how you subscribe to the Lync users and groups would be best, but the length of time it would take not only to write the code, but also the fact that the subscription would be so short made this option moot.

So here I am deciding how to poll Lync, but then things like… well how often do I poll? What if 600 people are all polling Lync at the same time, wouldn’t that cause the Lync server to get a little upset? I would say it would and I would also say don’t poll too often. Ok, so now I got this far, how does one cache in WCF. Well, there are ways to do this, although I find it a little upsetting on how complicated some tutorials out there make it when you don’t want to go nuts, you just want to cache stuff for a bit. Then I came across this nice tutorial by Patrick Talmadge. He showed a very easy way to cache an object for x time and then dispose of it. PERFECT… lets get started on the code.

 

Lets start the code noise….

So here we go. I am going to assume that you have some prior knowledge to Web Services and how the use interfaces. I will do other tutorials on that, but this is strictly about caching.

So First I made myself a Small generic person class with a few public properties.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WCFCaching
{
    public class Person
    {

        public string  Name { get; set; }
        public string Department { get; set; }
        public string Title { get; set; }
        public string PhoneNumber { get; set; }
    }
}

}

Once this was finished, I created two private routines in the Service.svc file ( not the interface) . The first method did a  GetUsers which populated a locate in memory list of server Person objects.

private List<Person> GetPeople()
      {
          List<Person> peoples = new List<Person>();

          try
          {
              peoples.Add(new Person() { Name = "Sheldon Cooper", Department = "Software Engineering", Title = "Software Engineer", PhoneNumber = "6112" });
              peoples.Add(new Person() { Name = "Superman", Department = "Software Engineering", Title = "Software Engineer", PhoneNumber = "7337" });
              peoples.Add(new Person() { Name = "Howard Walawitz", Department = "Software Engineering", Title = "Software Engineer", PhoneNumber = "4897" });
              peoples.Add(new Person() { Name = "Spiderman", Department = "President", Title = "Software Engineer", PhoneNumber = "5552" });
              peoples.Add(new Person() { Name = "Angel", Department = "Software Engineering", Title = "Software Engineer", PhoneNumber = "4814" });
              peoples.Add(new Person() { Name = "Buffy Vampire", Department = "Vice President", Title = "Manager of Corporate America", PhoneNumber = "5412" });

          }

          catch (Exception ex)
          {

          }

          return peoples;
      }

 

The second method calls GetUsers() and compares the username passed to the ones in the list and returns

the user the caller passed in matches.

private Person GetUser(string user)
       {
           Person returnStuffs = new Person();

           try
           {
               List<Person> peoples = GetPeople();

               foreach (Person person in peoples)
               {
                   if (user == person.Name)
                       returnStuffs = person;
               }

           }

           catch (Exception ex)
           {

           }

           return returnStuffs;
       }

 

 

Now we can make the call that we need to do all the magical coolness. Below you will see that there is

a  Cache object. This private object will be set inside the FindUser method. The Add method in the Cache object allows you to assign a key to the Cache to reference later. In this case, the user string parameter is being used as the key. Then, when I se the Get Method in the cache object, it allows you to get the cache and then test if it is null. If the cache object is empty, we do the search in the database, if not, the cache is returned instead.

 

private Cache _cacheData = HttpRuntime.Cache;

      public Person FindUser(string user)
      {

     
         Person person = ((Person)(_cacheData.Get(user)));

          if (person != null)
          {
              return person;
          }

          else
          {
              person = GetUser(user);

              string key = user;

              var cache = _cacheData.Add(key, person, null, DateTime.Now.AddMinutes(1), System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
          }
        
          return person;
      }

One thing you will also notice in the second and foutth parameters are very important for the Add method. The second parameter actually passes the object you would like to cache and the fourth parameter is the Time you would like the cache to exist until it is deleted by the system. In this case, it is one minute or 60 seconds.

Advertisements

About Gregg Coleman

I am Senior-level Software Engineer working primarily these days with .NET. I have a good working knowledge of ASP.NET MVC, Web Forms, WCF web services and Windows Services. I spend much of my time in the Web Services (SOAP and REST) world in my current job designing and implementing various SOA architectures. I have been in the software engineering industry for about 6 years now and will not now nor ever consider myself an "expert" in programming because there is always so much to learn. My favorite thing about designing software is there are always new emerging technologies and something to learn every day! My current job has me spending much of my job on the bleeding edge of technologies and changing gears all the time, so I'm never bored and always challenged. On my spare time I enjoy weight training, reading and venturing to new places near by. Of course programing and learning new technologies are another hobby of mine.
This entry was posted in C#, Programming, WCF and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s