0%

Modifying Windows Live Writer blog content in PublishNotificationHook plugins' OnPrePublish

I’m writing a PublishNotificationHook plugin for Windows Live Writer (don’t worry, I will soon reveal what it is), and I noticed that there doesn’t seem to be a way to control the contents (text or HTML) of the blog post in this type of plugin.

Further digging led me to understand that there used to be a method modify the contents via Reflection, as described by ScottIsAFool, Live Writer MVP and author of many great plugins, using his WriterUtils, however this doesn’t seem to work anymore with the latest version of Live Writer 2011.

I had discovered that on a Japanese blog called SharpLab, someone had posted a way to excavate an internal BlogManager object, which is used by Live Writer to edit the actual blog posts. The code needed a slight modification, but with the result I was able to modify the contents of my blog post!

I extracted this into an extension method, use this at your own risk!

// based on an old blog post in Japanese: http://blog.sharplab.net/computer/cprograming/windowslivewriter/433/
// The field was moved to a base type in the latest version of Live Writer

using System.Reflection;
using WindowsLive.Writer.Api;
using WindowsLive.Writer.Extensibility.BlogClient;
using WindowsLive.Writer.PostEditor;

namespace WindowsLiveWriterPlugin.Extensions
{
public static class PublishingContextExtensions
{
public static void ReplaceText(this IPublishingContext publishingContext, string newText)
{
FieldInfo fieldInfo = publishingContext.GetType().BaseType.GetField("_editingContext", BindingFlags.NonPublic | BindingFlags.Instance);
BlogPostEditingManager manager = (BlogPostEditingManager)fieldInfo.GetValue(publishingContext);
BlogPost blogPost = (BlogPost)publishingContext.PostInfo;

blogPost.Contents = newText;

manager.EditPost(new BlogPostEditingContext(manager.BlogId, blogPost));
}
}
}