Monday, December 06, 2010

How To Implement a Windows Live Writer Plug-in That Checks For Missing Tags

What Is This Plug-in Anyway?
This plug-in will remind you to add the proper tags if they are missing. Trying to post without proper tagging when the plug-in is installed will result with the following dialog. Clicking on the Cancel button (which is the default) will abort the publish operation and will let you update the categories. The list of required categories is saved in a simple text file (required_categories.txt) next to the plug-in dll.

How It Was Built?
Following are the full instruction on how to build such a plug-in.
You can find the full source here.

Create new class library project named CheckMissingTagsPlugin. Make sure you use .NET framework 3.5 since .NET 4 plugins are not supported.
Add reference to WindowsLive.Writer.Api, located in C:\Program Files\Windows Live\Writer.
Add reference to System.Windows.Forms, located in the GAC.
Create a class named CheckMissingTags that inherits from PublishNotificationHook.
Apply attribute WriterPluginAttribute to the class.

[WriterPlugin("EF0CAF97-12C2-4446-BDC4-19EE53781351", "Check For Missing Tags")]
public class CheckMissingTags : PublishNotificationHook
{
}

Override the method OnPrePublish. Here we can check for missing categories and notify the user.

public override bool OnPrePublish(IWin32Window dialogOwner, IProperties properties, IPublishingContext publishingContext, bool publish)
{
   // get list of required categories
   string[] requiredCategories;
   if (File.Exists(FileName))
   {
       requiredCategories = File.ReadAllLines(FileName);
   }
   else
   {
       // warn about missing required categories
       string message =
           "Missing categories file: " + FileName + "\n" +
           "Post anyway?";
       DialogResult dialogResult = MessageBox.Show(
           dialogOwner,
           message,
           "Warning",
           MessageBoxButtons.OKCancel,
           MessageBoxIcon.Warning,
           MessageBoxDefaultButton.Button2);
       // allow post only if user selected OK
       return dialogResult == DialogResult.OK;


Read more: Arik Poznanski's Blog