Archive for April, 2009

Flush Cache for Publishing Pages

Thursday, April 16th, 2009

A while back I wrote some custom code that redirected the user directly to the edit mode of a publishing page. This was done by passing querystring parameters “ControlMode=Edit&DisplayMode=Design”. The only problem was that if the user had hit the page before the publishing console was cached and would not display the right buttons for edit mode. Using Reflector I found out that the Publishing Console uses a cache and that there where internal classes for managing the cache. With a little bit of reflection I could call into these classes and flush the cache.

private static void FlushItemCachedState(string page, SPSite site)
    Assembly assembly = Assembly.GetAssembly(typeof(PublishingPage));
    Type cacheManagerType = assembly.GetType("Microsoft.SharePoint.Publishing.CacheManager");
    MethodInfo miGetManager = cacheManagerType.GetMethod("GetManager", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance, null, new Type[] { typeof(SPSite) }, null);
    object manager = miGetManager.Invoke(null, new object[] { site });
    PropertyInfo piObjectFactory = cacheManagerType.GetProperty("ObjectFactory");
    object objectFactory = piObjectFactory.GetValue(manager, null);
    Type cacheObjectFactoryType = assembly.GetType("Microsoft.SharePoint.Publishing.CachedObjectFactory");
    MethodInfo miFlushItem = cacheObjectFactoryType.GetMethod("FlushItem", new Type[] { typeof(string) });
    string cacheKey = new Uri(page).LocalPath;
    miFlushItem.Invoke(objectFactory, new object[] { cacheKey });