Posted by Bart Snyckers under
SharePoint | Tags:
Caching,
WebPart |
Leave a Comment
To boost the loadtime of your WebParts (and so the page on which the WebPart is added) in SharePoint, you can use caching methodologies for content that doesn’t change that often. You can find excellent tutorials on the internet about WebPart Caching Options, for example on this blog. But often these WebParts can be customized via properties (through ‘Modify Shared Web Part’) and you want to clear the cache when you do so to reflect the changes you have made a moment ago. As long as you stick to the standard WebBrowsable (& Personalizable) properties, you will have a hard time defining when to clear the cache and when not. The problem is that you can’t clear the cache everytime you call the setter of a property! As soon as one property is changed, these values are stored in the content database. Everytime the WebPart is added on the page, it’s initialized with the default values. The content database is queried and if new values could be found, these are set on the WebPart. Simple to follow, the set method for each property is called and so is the clear cache function (overhead since it’s called multiple times, but this could be solved with a simple boolean). There are however some techniques to avoid this:
1. You could store an object with the actual property values whenever you store your content in cache. Everytime you are loading the cache, you verify that the property values of the WebPart haven’t changed.
2. You create a custom editorpart for your WebPart and leave it almost empty. You have to override at least two methods, ‘ApplyChanges’ and ‘SyncChanges’. The ‘ApplyChanges’ method is called everytime OK or Apply is pressed. Inside this method, you get a reference to the WebPart via a cast from the WebPartToEdit property. If not nothing, you can just call a Clear Cache method you have written inside the WebPart class. The other method, ‘SyncChanged’ can be left blank. Don’t forget to implement the default and paramaterized constructor, you will need them later. In the WebPart class, you simply override the ‘CreateEditorParts’ method and add the new editorpart to the collection.
Although both techniques work, I prefer the second one, since it’t more robust to changes. You don’t have to change any line of code on the clear cache principle if you add a new property, standard or custom. In the first technique, the property value store and the compare have to change.