Geeks With Blogs

@azamsharp
  • azamsharp The WWDC app says that there are new videos but there is nothing under videos!!! about 507 days ago
  • azamsharp Can I post my opinion on iOS 7 Beta or is it under NDA or something? about 507 days ago
  • azamsharp iOS 7 BETA installed successfully! about 507 days ago
  • azamsharp iOS 7 BETA installed! Now restoring! I am on NET10 which uses AT&T network. Hopefully 3G will still work! Lets c.. about 507 days ago
  • azamsharp The missing of button borders in Xcode 5 makes it hard to determine the clickable area. about 507 days ago
  • azamsharp I might wait for iOS to be released before I can put it on my device! Don't want a bricked or unstable device! about 507 days ago
  • azamsharp Android has many features that no one uses, number of versions that no one upgrades to and thousands of apps that no one pays for. about 507 days ago
  • azamsharp Maybe it is just me but the new iOS 7 UI looks like Windows Phone 8 UI! #maybeIamCrazy about 507 days ago
  • azamsharp Anyone using H20 network upgraded to iOS 7 BETA Keep me updated if you face any problems. about 507 days ago
  • azamsharp @merowing_ You already downloaded it! I cannot even load the developer's website! :( about 507 days ago

AzamSharp Some day I will know everything. I hope that day never comes.

Data Caching allows you to hold the items in the memory (Cache) so you don't have to access the database on each and every request. A common pattern when performing data caching is shown below:

 if (Cache["Rooms"] == null)
            {
                // get the rooms
                var rooms = from r in virtualRoomDC.tblRooms
                            select r;

                Cache["Rooms"].Insert("Rooms", rooms);

            }

            return Cache["Rooms"] as IEnumerable<tblRoom>;

First, we check if the Cache[Key] is null or not. If the Cache[Key] is null then we ask the database for the items. Once, we get the items we put it in the Cache using a Key/Value combination. Now, the next time we request for those items it will be loaded from the Cache and not fetched from the database. This greatly reduces the load on the database server and hence improve performance.

I think it will be very beneficial if we could achieve the same pattern using the minimum amount of code. For this purpose I created a custom attribute called CacheAttribute which when placed on a method caches the result of the method. The CacheAttribute takes a single argument which is the cache time in seconds. Take a look at the CacheAttribute implementation below:

 [AttributeUsage(AttributeTargets.Method)]
    public class CacheAttribute : System.Attribute
    {
        private int _timeInSeconds;

        public CacheAttribute(int timeInSeconds)
        {
            _timeInSeconds = timeInSeconds;
        }

        public int TimeInSeconds
        {
            get { return _timeInSeconds; }
            set { _timeInSeconds = value; }
        }
    }

Now, to use the CacheAttribute I will just place it on the method as show below:

 [CacheAttribute(10)]
        public IEnumerable<tblRoom> GetAllRooms()
        {          
                // get the rooms
                var rooms = from r in virtualRoomDC.tblRooms
                            select r;               

                return rooms;
        }

This means that the result of the GetAllRooms method will be cached for "10" seconds. Now, let's call this method from the UI.

var time = (DateTime) MethodInvoker.Invoke<RoomRepository>("GetAllRooms", null);

Currently, I am returning the cached datetime object but practically you will return the return parameter of the method invoked. Here is the implementation of the MethodInvoker class.

 public static object Invoke<T>(string methodName, object values)
        {
            if (HttpContext.Current.Cache.Get(methodName) == null)
            {                                               
                Type t = typeof(T);

                MethodInfo method = t.GetMethod(methodName);
                CacheAttribute cacheAtt = (CacheAttribute)method.GetCustomAttributes(typeof(CacheAttribute), false)[0];

                object o = Activator.CreateInstance(t);
                object result = null;

                if (values != null)
                {
                    result = method.Invoke(o, new object[] { values });
                }

                HttpContext.Current.Cache.Insert(methodName, DateTime.Now, null, DateTime.Now.AddSeconds(cacheAtt.TimeInSeconds), TimeSpan.Zero);
            }


            return HttpContext.Current.Cache[methodName];
        }

Once, again I am putting the cached datetime into the HttpContext.Current.Cache but you will put the result of the method call. Now, when I call this method multiple times I will get the cached data for the first 10 seconds. Once the cache time is expired I will get the fresh copy from the database. Take a look at the screen shot below:DynamicCacheUSingAtteibute

Posted on Saturday, February 16, 2008 10:09 AM | Back to top


Comments on this post: Data Caching Using Custom Attributes

No comments posted yet.
Your comment:
 (will show your gravatar)
 


Copyright © Mohammad Azam | Powered by: GeeksWithBlogs.net | Join free