VSTO Data Caching

Tags: Dev

I spent more hours than I'd like figuring out why data caching didn't work for me in a Word-based VSTO solution.   I did what I needed to implement a cached property:

  • Public property
  • Marked with Cached attribute
  • Type to be cached marked as Serializable

I saved the document on closing (after writing to the cached field), yet no luck.   After messing around for some time, I finally decided to test out serializing the type.   Since it's specifically XML serialization that must succeed I used the XmlSerializer object, wrote to a MemoryStream, then displayed the result in a message box.

Ah ha!   As soon as I tried to explicitly serialize it, it failed and gave me the exception.   It turned out that one of my serializable classes was marked fine and used public properties where needed, but had a private get declared.   Of course this makes sense that it's a problem since the framework can't deserialize a property that it can't set!   I just changed it to a public get and set and now it works!   Apparently the VSTO framework swallowed the exception so I just couldn't tell before.   Word to the wise!

The reason I had a private setter was the property was a collection.   I wanted consumers of the object to be able to get and work with the collection, but there's no reason for the collection to be replaced.   I changed it in the setter to throw an exception if set is invoked when the value is already non-null.   Simple solution!
Add a Comment