SharePoint Pals
 | Sign In
How to Use Cache Dependency in Client Side Object Model using C# – SharePoint 2013 Lists
by Sathish Nadarajan 4 Nov 2015
Author
SharePoint MVP
Visits   
Today  :   7     Total  :    5286

Almost in all of our applications, we will be using the Configuration Lists or some sort of List. To read the values from the lists, there is a request posted to the SharePoint Server from the Client. Though we use the JavaScript, JQuery for this purpose, actually the request fetches the data from the Content DB every time.

To avoid that, what we can do is, Caching the result set and keeping them in a Cache Variable. But again, there is a problem is, when the Config Value got updated, we may not get the latest values immediately. To avoid this, we need to have some sort of mechanism that will update our Cache Variable, as soon as the SharePoint Lists gets updated. In the internet, I could find there are certain classes readily available for the Server Side Object Model. As now a days, we are concerning more about the Client Object Model, I thought of customizing them for the CSOM and let us see how we are using the CacheDependancy Class from our Provider Hosted Application.

I have created a Separate class for this purpose and it will be really helpful for us to keep this handy.

 public class SPListCacheDependency : CacheDependency
     {
         private readonly SPListCacheDependencyEventArgs _eventArgs;
         private readonly Timer _timer;
         private readonly DateTime _lastModified;
         private readonly int _itemCount;
         private readonly string _uniqueId;
 
         public SPListCacheDependency(List list, ClientContext clientContext)
         {
             _lastModified = list.LastItemModifiedDate;
             if (list.LastItemDeletedDate > _lastModified)
             {
                 _lastModified = list.LastItemDeletedDate;
             }
 
             _itemCount = list.ItemCount;
 
             _uniqueId = list.Id.ToString() ;
 
 
             _eventArgs = new SPListCacheDependencyEventArgs(list, clientContext);
             _timer = new Timer(10000) { AutoReset = true }; // check every ten second
             _timer.Elapsed += MonitorChanges;
             _timer.Start();
         }
 
         public override string GetUniqueID()
         {
             return _uniqueId;
         }
 
         public bool HasObjectChanged(object source)
         {
             List list = (List)source;
             DateTime modified = list.LastItemModifiedDate;
 
             if (list.LastItemDeletedDate > modified)
                 modified = list.LastItemDeletedDate;
 
             return _lastModified != modified || _itemCount != list.ItemCount;
         }
 
         private void MonitorChanges(object sender, ElapsedEventArgs e)
         {
             try
             {
                 ClientContext context = _eventArgs.MyClientContext;
                 List list = context.Web.Lists.GetByTitle("RedirectAppConfigList");
                 context.Load(list);
                 context.ExecuteQuery();
                 ObjectChanged(list);
             }
             catch (ArgumentException)
             {
                 //Object has been deleted.
                 ObjectChanged(null);
             }
         }
 
         /// <summary>
         /// Raise event and stop timer if object has been updated
         /// </summary>
         /// <param name="item"></param>
         private void ObjectChanged(object item)
         {
             if (!HasObjectChanged(item) && item != null) return;
 
             _timer.Stop();
             NotifyDependencyChanged(this, _eventArgs);
         }
     }
 
     internal class SPListCacheDependencyEventArgs : EventArgs
     {
         public SPListCacheDependencyEventArgs(List list, ClientContext clientContext)
         {
 
             MyList = list;
             MyClientContext = clientContext;
         }
 
         public List MyList { get; private set; }
         public ClientContext MyClientContext { get; private set; }
     } 
 

By looking at the class, it may be looks like vague. Let us see each methods individually, so that it will be easy for us to understand.

 public SPListCacheDependency(List list, ClientContext clientContext)
         {
             _lastModified = list.LastItemModifiedDate;
             if (list.LastItemDeletedDate > _lastModified)
             {
                 _lastModified = list.LastItemDeletedDate;
             }
 
             _itemCount = list.ItemCount;
 
             _uniqueId = list.Id.ToString() ;
 
 
             _eventArgs = new SPListCacheDependencyEventArgs(list, clientContext);
             _timer = new Timer(10000) { AutoReset = true }; // check every ten second
             _timer.Elapsed += MonitorChanges;
             _timer.Start();
         }
 

The above is the constructor, on which, we are attaching a timer for every ten seconds. This value, we can increase based up on our refresh need.

Irrespective of the List being updated or not, every ten seconds, we are going to monitor the changes.

Now, let us look at the MonitorChanges method.

 private void MonitorChanges(object sender, ElapsedEventArgs e)
         {
             try
             {
                 ClientContext context = _eventArgs.MyClientContext;
                 List list = context.Web.Lists.GetByTitle("RedirectAppConfigList");
                 context.Load(list);
                 context.ExecuteQuery();
                 ObjectChanged(list);
             }
             catch (ArgumentException)
             {
                 //Object has been deleted.
                 ObjectChanged(null);
             }
         }

On this method, we are taking up with List from the ClientContext and sending it to the method ObjectCached.

And this is the method which we are expecting.

 public bool HasObjectChanged(object source)
         {
             List list = (List)source;
             DateTime modified = list.LastItemModifiedDate;
 
             if (list.LastItemDeletedDate > modified)
                 modified = list.LastItemDeletedDate;
 
             return _lastModified != modified || _itemCount != list.ItemCount;
         }
 
 

This is the one which will decide whether there is any change happened or not. Based on this, we will make sure that the Cached object is null or not.

Now, let us see, how to call this from our Provider Hosted App.

On the PageLoad, am trying to get the ListItemCollection from the Cache.

 protected void Page_Load(object sender, EventArgs e)
         {
              
             var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
 
             using (var clientContext = spContext.CreateUserClientContextForSPHost())
             {
 
                 clientContext.Load(clientContext.Web, web => web.Title);
                 clientContext.ExecuteQuery();
                  
 
                 Microsoft.SharePoint.Client.ListItemCollection lstItmCln = HttpContext.Current.Cache.Get("MyCacheKey") as Microsoft.SharePoint.Client.ListItemCollection;
 
                  
 
                 if (lstItmCln == null)
                 {
                     List list = clientContext.Web.Lists.GetByTitle("RedirectAppConfigList");
                     clientContext.Load(list);
                     clientContext.ExecuteQuery();
 
 
                     var query = new Microsoft.SharePoint.Client.CamlQuery
                     {
                         ViewXml = @"<View>
                                         <Query>
                                              
                                         </Query>
                                     </View Scope='RecursiveAll'>"
                     };
 
 
 
                     Microsoft.SharePoint.Client.ListItemCollection listItemCollection = list.GetItems(query);
 
                     clientContext.Load(listItemCollection);
                     clientContext.ExecuteQuery();
 
                      
 
                     HttpContext.Current.Cache.Add("MyCacheKey", listItemCollection, new SPListCacheDependency(list, clientContext), System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
 
 
                     Microsoft.SharePoint.Client.ListItem item = listItemCollection.FirstOrDefault(t => Convert.ToString(t.FieldValues["Title"]) == "Admin" && Convert.ToString(t.FieldValues["ConfigurationCategory"]) == "Choice2");
                     if (item != null)
                     {
                         Response.Write("</br>Configuration VAlue : " + item["ConfigurationValue"].ToString());
                     }
                 }
 
                  
             }
         }
 

The above code is self-explanatory. Here, what we are doing is, trying to read the values from the Cache object. If it is null, then go to the list again. The decision is done by the Dependancy class which we created in the beginning.

I request the users to customize the Class based on their need. Though we can make this as a re-usable component, for the time being am leaving this to the readers.

Happy Coding,

Sathish Nadarajan.

blog comments powered by Disqus

SharePoint Pals

Pals
SharePoint Pals, a community portal for SharePoint developers, Administrators and End Users. Let's join hands and share the point together.
Read this on mobile

Training

Angular Js Training In Chennai
Advanced Angular Js training with real world developer scenarios
Angular Js, Web Api and Ionic for .Net Developers
All in one client side application development for .Net developers
Angular Js For SharePoint Developers
Get ready for the future. Its no more just C#

Get Connected

SharePoint Resources

SharePoint 2013 and 2010 Web Parts
Free Web Parts with Source Code for SharePoint Community




SharePoint 2013 Books and Tutorials
Collection of free SharePoint 2013 books and tutorials (eBooks, pdfs)

Supported By

Contribute your article and be eligible for a one month Free Subscription for Plural Sight. The Author of the most popular New Article (published in the previous month) will be awarded with a Free One month Plural Sight Subscription. Article can be sent to articles@sharepointpals.com in a word document.

Related Resources

Recent Tweets

Twitter January 15, 00:25
How To Enable Target Value And Actual Value In #D3 Gauge Chart https://t.co/VxSi4QnNrC

Twitter January 15, 00:24
How To Open #SharePoint List Hyperlink Column In Modal #Popup Window https://t.co/EQ7HkoZDkX

Twitter January 15, 00:24
Quick Introduction To #Asp.NetCore And It’s Features https://t.co/zAXObHCFpH

Twitter January 15, 00:22
How To Configure #PerformancePoint Services To Use Secure Store In #SharePoint 2013 https://t.co/LEwnUoI7EY

Twitter January 15, 00:21
How To Block Or Disable #Office365 Services https://t.co/Yvp2VPFIRP

Follow us @SharePointPals
Note: For Customization and Configuration, CheckOutRecent Tweets Documentation