Friday, October 9, 2015

Caching in Plugins

Do you need to cache some information as part of your Plugin Assembly?


Shared variable has some limitations. You cannot set an expiry for it and access it from other plugins

There are lot of Practical usages, you can add it on the comments section.
Scenario 1:
Accept or Process only one request in every hour even though you have lot of request came in.
Ex: Lottery system Accept only one email/sms record in an Hour

Scenario 2
As part of my implementation, I am sending an alert if third party system integration got failed. I have done the third party integration through CRM asynchronous plugin. I want to avoid multiple alerts on third party system unavailability and accumulate all the failed records while bulk processing scenario.

You can have multiple ways to do it.

Here I used a cache object as part of plugin implementation, it can set on first occurrence of the specific  error. Cached object is accessible on next plugin execution until it got expires



Here is one way. Create a cache as part of your plugin.
private static ObjectCache cache = MemoryCache.Default;
       /// <summary>
        /// This to Create static data in between Plugins
        /// </summary>
        /// <param name="DownTime">KeyName</param>
        /// <param name="count">Value</param>
 /// <returns></returns>
        private bool CreateCacheItem(string DownTime, bool count)
        {
            CacheItemPolicy policy = new CacheItemPolicy();
            policy.Priority = CacheItemPriority.Default;
            policy.AbsoluteExpiration = DateTimeOffset.Now.AddHours(2);
            if (GetMyCachedItem(DownTime) != null)
            {

                cache.Set(DownTime, count);
            }
            else
            {
                cache.Set(DownTime, count);
            }
            return true;
        }



        /// <summary>
        /// Get Cached Data
        /// </summary>
        /// <param name="CacheKeyName"></param>
        /// <returns></returns>
        private Object GetMyCachedItem(String CacheKeyName)
        {
            return cache[CacheKeyName] as Object;
        }


Happy Coding!

No comments: