How to Use Cache Dependency in Client Side Object Model using C# – SharePoint 2013 Lists

Sathish Nadarajan
 
Solution Architect
November 4, 2015
 
Rate this article
 
Views
9542

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.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Leave a comment