Archive for category How To

IE8 Accelerators

With the release of a much more stable IE8 (beta 1 was truly, truly awful), I am now able to actually try some of the cool things that are in IE8. One of these things are the accelerators that you can install. What this means is you could highlight some text on a page and get a little icon appear in the page giving you some options for that highlighted text:

Some of the accelerators are for searching on Google/Live Search, looking stuff up on maps, etc. Now, the cool thing is you can create your own, so I’ve created one that’s for IMDB that will look up the highlighted text on IMDB, whether it be actor/actress/movie. So using the above example, this will give you the following context menu:

This will then take you to the IMDB results, in this case, it takes me to http://www.imdb.com/name/nm0515116/ which is Blake Lively’s IMDB page. If there are multiple people with the same name then it will give you the search results where you can choose. So how did I make it? It’s simple, head on over to the MSDN OpenService Accelerators Developer Guide and read what’s going on there. Then it’s just a case of creating your own xml file. Mine looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<os:openServiceDescription
    xmlns:os="http://www.microsoft.com/schemas/openservicedescription/1.0">
    <os:homepageUrl>http://www.imdb.com</os:homepageUrl>
    <os:display>
        <os:name>Look up on IMDB</os:name>
        <os:icon>http://www.imdb.com/favicon.ico</os:icon>
        <os:description>Look up someone on IMDB</os:description>
    </os:display>
    <os:activity category="Search">
        <os:activityAction context="selection">            
            <os:execute action="http://www.imdb.com/find?s=all&amp;q={selection}" />                
        </os:activityAction>
    </os:activity>
</os:openServiceDescription> 

Now, the only thing about making your own accelerator is the xml file has to be hosted on an actual domain and be callable from http or https. I thought this would be fine, just stick it on my www.scottisafool.co.uk domain, job done. But no, my host (1and1) seems to not be letting me access my ftp server, so I was stuck. Then I remembered good ol’ Windows Live. So both the xml file, and a simple html file are now both hosted on my SkyDrive area so you can install from there.

Feel free to leave any comments or problems with it 🙂

SL

Whilst writing this, I was listening to Def LeppardPromises

Advertisements

4 Comments

Writing Plugins For Windows Live Writer – Logging Errors

Sometimes your plugin will require some kind of logging, especially when it comes to logging errors that have occurred. So rather than reinvent the wheel for this, the Live Writer API has a class for doing just this, and logs it into the Windows Live Writer log file. So if you have implemented this in your plugin and you get an email come in with it giving errors or not working, you can request the log file and check what has been written. In the following example I’ll show you the code samples needed for logging to the WLW Log file.

This is a very simple thing to demonstrate, so I’ve created a simple plugin with a form and two buttons, one will call an error message box that looks like a normal Windows Live Writer error window as well as log it to the Windows Live Writer logfile. The second button will be used to try and open a file that doesn’t exist and so would normally throw an exception.

So the form looks like:

And when we click the first button we get:

When you then look in your logfile, you will see an entry at the end that says:

WindowsLiveWriter,1.11700,None,00017,05-Aug-2008 20:08:14.842,"DisplayableException occurred: WindowsLive.Writer.CoreServices.DisplayableException: Oh no, an error! – This is an error logged and displayed by the Plugin Diagnostics Plugin",""

Which as you can see is what is in that error window.

For the second button we get:

and again in the logfile:

WindowsLiveWriter,1.11200,Fail,00016,05-Aug-2008 22:55:49.828,"Unexpected Error Occurred
Exception Details:
An unexpected error has occurred within the application.
System.IO.FileNotFoundException: Could not find file ‘c:\scottisafool.scott’.
File name: ‘c:\scottisafool.scott’
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
   at System.IO.File.Open(String path, FileMode mode)
   at PluginDiagosticsExample.frmMain.button2_Click(Object sender, EventArgs e)",""

With the second button, you’ll see that we aren’t presented with the standard Windows Live Writer error window, but a standard Windows error, the reason for this is because it’s the only way for the Writer team to get information about the error. What they then do is contact the plugin author and give them the details.

Now, to add this functionality to your plugin is dead simple:

        private void button1_Click(object sender, EventArgs e)
        {
            // Log a general Error Message it to the user
            string message = "This is an error logged and displayed by the Plugin Diagnostics Plugin";
            PluginDiagnostics.LogError(message);

            // This one will show the error to the user as well as log it
            PluginDiagnostics.DisplayError("Oh no, an error!", message);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            // Log an exception by opening a non-existent file
            try
            {
                File.Open(@"c:\scottisafool.scott", FileMode.Open);
            }
            catch (Exception ex)
            {
                PluginDiagnostics.LogException(ex, "From Plugin Diagostics Plugin");
                // This will display an error in the same way that Windows displays its own errors.
                PluginDiagnostics.DisplayUnexpectedException(ex);
            } 
        }

It’s as easy as that! With the first button, it’s up to you whether you display the error message or not (you might not need to). If you use the DisplayError() method, this gets written to the log file automatically, so although I show both methods in that example, it’s not necessary. This goes for the LogException() and DisplayUnexpectedException() methods too.

As always, you can download the source for this little sample from my skydrive area: PluginDiagosticsExample.zip

Windows Live Tags: , , , ,

SL

Whilst writing this, I was listening to Linkin ParkOne Step Closer

6 Comments

The New Live Writer SDK

In my LiveSide post, I mentioned that the Live Writer SDK had been updated as well as Live Writer itself. In this post I will show you how to build a couple of quick plugins that use the new APIs, but first, what’s changed?

The big thing to note is that all the API calls in the previous version of the SDK are unchanged; the changes have been additions to the SDK. So the main two new additions are two new plugin classes: PublishNotificationHook and HeaderFooterSource. This gives us four types of plugins: ContentSource, SmartContentSource, PublishNotificationHook and HeaderFooterSource. There are also a couple of other new smaller additions, like the TaskServices class that will let you perform a task in the background whilst still keeping the Writer UI in a responsive state.

But this post is going to concentrate on those two new Plugin base classes, which you can see after the jump.

PublishNotificationHook

This type of plugin can be used to access the post either before or after it’s published. The reason you might want to do this is to check the post for something, this can be the title, the contents or even the keywords (blog engine permitting). You would check the post for whatever you’re looking for and if it passes your check, you allow the post to be published, or else you tell Writer to stop publishing and the post remains unpublished.

Let’s look at some code. The plugin starts off the same way as a ContentSource or SmartContentSource plugin in that you have to declare some WriterPlugin attributes:

    [WriterPlugin("07b95fc3-887e-4558-b53a-0e2a5a47f431", 
"PublishNotification Example", PublisherUrl = "http://www.liveside.net", Description = " ", ImagePath = "writer.png", HasEditableOptions = false)]

So now we create the plugin class and mark it as a PublishNotificationHook class:

    public class PublishNotificationExample : PublishNotificationHook
    {

Like ContentSource or SmartContentSource plugins, you can override the Initialize() method (if your plugin requires settings), this is also true for HeaderFooter plugins too.

With PublishNotificationHook plugins, I mentioned that you can access the post before (or after) it’s published, and we do this by overriding the OnPrePublish and OnPostPublish methods. In this very quick example, I’m going to check whether my post’s contents (ie, the body of the blog entry) contains the word “liveside”:

        public override bool OnPrePublish(IWin32Window dialogOwner, 
            IProperties properties, IPublishingContext publishingContext, 
            bool publish)
        {
            // Check the post contents to see if liveside appears, if it does, 
// return true (publish),
// if it doesn't, return false (cancel publish) return publishingContext.PostInfo.Contents.ToLower().Contains("liveside"); }

Now, the publishingContext.PostInfo is where all the cool stuff is. In this property (which is an IPostInfo object), you have access to the Contents, Keywords, Title, Categories, and even tells you whether it’s a page or not (for WordPress users). Now with this quick check, if my post doesn’t contain the word liveside, then the OnPrePublish method will return false which will stop the post from publishing, if it does contain it, then it will return true and continue to publish.

The OnPostPublish method is slightly different, this method would allow you to do something once the post has been published, for example, update your Twitter status with the blog title and permalink:

        public override void OnPostPublish(IWin32Window dialogOwner, 
            IProperties properties, IPublishingContext publishingContext, 
            bool publish)
        {
            // If this post is a draft (false), don't do anything
            // if it's an actual publish, then publish = true;
            if (!publish)
                return;

            string updateTwitter = string.Format("{0} - {1}",
                publishingContext.PostInfo.Title,
                publishingContext.PostInfo.Permalink);

            // Code to update Twitter
        }

You’ll notice the variable publish that gets passed in both OnPostPublish and OnPrePublish, this will tell your plugin whether it’s being saved as a draft or as an actual published entry. This is the same for HeaderFooterSource plugins, too.

And there you have it, a quick plugin that uses the PublishNotificationHook base class.

HeaderFooterSource

This type of plugin can be used to automatically add some html code to a blog post as either a header, or a footer. Quick examples of this could be a Digg button (header), or Social Bookmarking widget (footer). Now the cool thing about this type of plugin is you can actually specify the permalink for the post to be used, even if the post has yet to be published (I’ll cover this when I start going through the code). If you want to see what your post will look like when using this type of plugin, you just go to the Preview tab and the plugin will get loaded (there are separate methods for the Preview HTML and the Published HTML, but again, I’ll go through that in the code).

Start off by creating the class and declaring it as a HeaderFooterSource plugin:

    public class HeaderFooterSourceExample : HeaderFooterSource
    {

Now, as I mentioned, the cool thing about this base class is you can tell the plugin to use the post’s permalink (even though it hasn’t been published yet), but what we need to do is tell Writer that the plugin will require a [currently] non-existent permalink, we do this by overriding the RequiresPermalink boolean (whose default is false):

        public override bool RequiresPermalink
        {
            get
            {
                return true;
            }
        }

The HeaderFooterSource base class will create two methods for us: GeneratePreviewHtml() and GeneratePublishHtml(). Now these both work in a similar way to GeneratePublishHtml() and GenerateEditorHtml() in SmartContentSource plugins. The GeneratePreviewHtml() is what shows when you switch to the Preview tab, and the GeneratePublishHtml() is what gets published.

So first off the GeneratePreviewHtml():

        public override string GeneratePreviewHtml(ISmartContent smartContent,
            IPublishingContext publishingContext, 
            out HeaderFooterSource.Position position)
        {
            // This tells the plugin where to put your code
            position = Position.Header;
            return "Nothing to see here yet!";
        }

And then the GeneratePublishHtml():

        public override string GeneratePublishHtml(IWin32Window dialogOwner, 
            ISmartContent smartContent, IPublishingContext publishingContext, 
            bool publish, out HeaderFooterSource.Position position)
        {
            position = Position.Header;
            string yeehaaaa = string.Format("This blog entry's link is: <br />" + 
                "<a href=\"{0}\">{0}</a>.", publishingContext.PostInfo.Permalink);

            return yeehaaaa;
        }

So if you now click on the Preview tab, your post would look like this:

Notes about these plugins

After you have have first added any of these plugins to Live Writer, when you click on the Publish button (or Preview for HeaderFooterSource), Writer will ask you if you want to use these plugins for the blog you’re currently using:

For these new types of plugins, you can enable or disable each plugin on a per blog basis, which you can do from the Accounts options window:

And that’s about all you need to know for now. I have made some plugins of my own using these new APIs, but I will cover those in another post.

As always, the source code for this can be found in my skydrive area:

http://cid-fabdddc5cad93494.skydrive.live.com/self.aspx/LiveSide%20-%20Public/SourceCode/NewAPIPlugin.zip

SL

Whilst writing this, I was listening to The Lightning SeedsChange

6 Comments

Writing An Application That Opens Windows Live Writer

Everyone knows that you can easily make a plugin for Windows Live Writer, but one of the APIs that’s not as well known or spoken about is the Windows Live Writer Application API. This set of API calls will allow you to open Windows Live Writer in a particular way. What do I mean by that? Well, you can open Live Writer at the Open Post window, or the options window, as just a couple of examples. The real power with this API is the BlogThis set of calls.

Some of you might be familiar with the Blog This addins for Internet Explorer (no longer available) and Firefox, which would allow you to click on the Blog This button in your browser, and it would open up Live Writer with either the page details loaded in Writer, or the highlighted text from the webpage you were viewing. Also anyone who uses my Live Writer sidebar gadget in Vista, this uses the same principle. In this article I will show you how to write a simple Windows application that uses some of the BlogThis calls.

To start off, make sure you have the latest version of Windows Live Writer installed by going to http://writer.live.com/. Now, create a new project in Visual Studio and add a reference in that project to the Windows Live Writer COM assembly (C:\Program Files\Windows Live\Writer\WindowsLiveWriter.Application.dll) and then for using it we put:

using WindowsLiveWriterApplicationLib;

Now we have to create an instance of the WindowsLiveWriterApplicationLibClass:

        WindowsLiveWriterApplicationClass wlwapp;
        public Form1()
        {
            InitializeComponent();
            wlwapp = new WindowsLiveWriterApplicationClass();
            cbOptions.SelectedIndex = 5;
        }

Now, for this example I have just created a basic WinForms application with a series of buttons for showing the different functions, it looks like this:

This App will show a few examples, but not all, after a certain point, they’re all one and the same really, just for a different use.

We’ll start off with the basic Open Writer button. The call that we make for this one is NewPost(), as that is effectively opening Writer as if running the program from a shortcut. So the code for this is:

        private void btnOpenWriter_Click(object sender, EventArgs e)
        {
            wlwapp.NewPost();
        }

For the Open Post button, we use OpenPost():

        private void btnOpenPost_Click(object sender, EventArgs e)
        {
            wlwapp.OpenPost();
        }

Now for the Open Options button, we use the ShowOptions() call. This call can be made with no parameters, and it will default to the preferences tab in the options window. However, you can put in a string parameter to open a different tab from the options window, and you can choose from the following: "preferences", “accounts”, "blogthis", “spelling”, “glossary”, "plugins", "webproxy", and "pings". And you can see from my App that I have put this in a drop down:

Which for the code looks like:

        private void btnOpenOptions_Click(object sender, EventArgs e)
        {
            string option = cbOptions.SelectedItem.ToString();
            wlwapp.ShowOptions(option);
        }

Now, the cool thing about this API is when it comes to putting images into a blog post and there are a couple of methods you can use for Images, one is for a single image, and one is for an image-set, so for multiple images. I’ll start with the single image method first which uses the BlogThisImageFile() call:

        private void btnOpenWithImage_Click(object sender, EventArgs e)
        {
            DialogResult result = openFileDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                string title = string.Empty;
                if (!string.IsNullOrEmpty(txbxBlogTitle.Text))
                {
                    title = txbxBlogTitle.Text;
                }
                else
                {
                    title = "My New Blog Post";
                }

                string imagefile = openFileDialog1.FileName;
                
                // Open a new post using the imagefile we just selected

                wlwapp.BlogThisImageFile(title, imagefile, txbxComment.Text);
            }
        }

And for multiple images, we use the BlogThisImageFileList() call:

        private void btnOpenWithFiles_Click(object sender, EventArgs e)
        {
            DialogResult result = openFileDialog2.ShowDialog();
            if (result == DialogResult.OK)
            {
                string title = string.Empty;
                if (!string.IsNullOrEmpty(txbxBlogTitle.Text))
                {
                    title = txbxBlogTitle.Text;
                }
                else
                {
                    title = "My New Blog Post";
                }

                string[] imagefiles = openFileDialog2.FileNames;

                // Open a new post with the files we selected

                wlwapp.BlogThisImageFileList(title, imagefiles, txbxComment.Text);
            }
        }

The BlogThis set of calls also has one for URLs, BlogThisLink(), which will most likely be what the Blog This add-ins for IE and FF use. The code for this is:

        private void btnOpenUrl_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txbxUrl.Text) &&
                txbxUrl.Text.StartsWith("http://"))
            {
                label3.ForeColor = Color.Black;
                string title = string.Empty;
                if (!string.IsNullOrEmpty(txbxBlogTitle.Text))
                {
                    title = txbxBlogTitle.Text;
                }
                else
                {
                    title = "My New Blog Post";
                }
                wlwapp.BlogThisLink(title, txbxUrl.Text, txbxComment.Text);
            }
            else
            {
                label3.ForeColor = Color.Red;
            }            
        }

As I mentioned, I’m not going to go into detail about the others, but I will give a quick description of them:

  • BlogThisFeedItem() – This would be used in an RSS Feed Reader program, in the way that FeedDemon uses it.
  • BlogThisHTML() – This would be used to start Writer with some preconfigured HTML in the blog entry (self explanatory really)
  • BlogThisImageUrl() – Much like the BlogThisLink() call, this deals with links again, but image links, similar to if you inserted a picture and choosing a picture from the web.
  • BlogThisSnippet() – This is another one I suspect the Blog This add-ins use. In those examples this would be where you highlighted some text on a webpage to blog about it.

There are some good examples of where these API calls have been used, and I have tried to cover the main ones in this post, although one I haven’t mentioned is one I used quite frequently, which is the Live Writer System Tray App, which works in a similar way to my sidebar gadget.

If you wish to download the source code for my example app, you can do so from my SkyDrive area.

SL

9 Comments

My Live Writer Article for CoDe Magazine

Last year at the back end of November, I got asked by CoDe Magazine if I would like to write an article for a special edition of the magazine dedicated to Windows Live that would be getting published for Mix08. Sure, I said. So I wrote my article on developing plugins for Windows Live Writer.

Well, Mix was last week, and on the Wednesday, the magazine was published, complete with my article . And now, a week on, the online version of the magazine is up, including the online version of my article. All rather cool really

CoDe Magazine – 2008 – Vol. 5 – Issue 2 – Windows Live

Developing Plugins for Windows Live Writer

SL

Whilst writing this I was listening to GarbagePush it

4 Comments

Writing Plugins For Windows Live Writer – Using PluginHttpRequest Instead of HttpWebRequest

In a few of my plugins, I often find myself using System.Net.HttpWebRequest to get some data from a website, whether from a service or to access a specific part of a website. This is all very well and good, but what happens if you’re trying to use Windows Live Writer behind a proxy? Well with Writer itself, that’s not a problem, you just use the proxy settings to bypass it:

The only trouble is, although Writer is using those proxy settings, your plugin isn’t. Unless you do more work to set the proxy in the WebRequest, but that means hard coding the details into your plugin, which won’t really work, or creating a seperate set of settings for it, which again is a but cumbersome. Fortunately though, the Writer team have given us an answer for this. Embedded deep in the Writer APIs is a little class called PluginHttpRequest. What this class does is use the settings that are already configured in Writer. How cool is that!

Now, one important thing to note about this class: it is not exactly the same as HttpWebRequest, more like a very good substitute. If you have built a plugin that uses HttpWebRequest, you will still have to modify some of the code. To demonstrate this, I created a test plugin that will show the HttpWebRequest method, and the PluginHttpRequest method.

I created the basics of a quick plugin, and used the following UI:

The code behind the Test 1 button looks like this:

        private void button1_Click(object sender, EventArgs e)
        {
            string s = "";
            try
            {
                // Create the HttpWebRequest
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                WebResponse resp = req.GetResponse();
                Stream st = resp.GetResponseStream();
                StreamReader sr = new StreamReader(st);
                s = sr.ReadToEnd();
            }
            catch (Exception ex)
            {
                s = "Failed to get information: \n" + ex.Message;
            }
            textBox1.Text = s;
        }

The code behind the Test 2 button looks like this:

        private void button2_Click(object sender, EventArgs e)
        {
            string p = "";
            try
            {
                PluginHttpRequest prequest = new PluginHttpRequest(url);
                Stream presp = prequest.GetResponse();
                StreamReader sr = new StreamReader(presp);
                p = sr.ReadToEnd();
            }
            catch (Exception ex)
            {
                p = "Failed to get information: \n" + ex.Message;
            }
            textBox2.Text = p;
        }

As you can see, there is one step that is missed out when using the PluginHttpRequest, and that’s getting the WebResponse and getting the stream from that. This is where the PluginHttpRequest differs, in that the GetResponse() returns a Stream, not a WebResponse.

The results of these tests are as follows:

This is for me at home, not behind a proxy, see how they both work, now if I was behind a proxy, Test 1 will give a failure message in the textbox, but Test 2 (assuming you have Writer configured for your proxy), will show the same as it does above, the source code for www.microsoft.com.

Now, this is only a basic example of how to use the PluginHttpRequest, and there are other properties to this class that can be levied. But if your plugin uses the methods described in Test 1, I would recommend migrating over to Writer’s native class, as it means your plugins will not only work for Joe Public, but also for those who are behind a corporate proxy, for example.

Test project source code: http://cid-fabdddc5cad93494.skydrive.live.com/self.aspx/LiveSide%20-%20Public/SourceCode/HttpRequestTest.zip

SL

PS, Expect a post soon with a list of my plugins that use the original HttpWebRequest class as they will have been updated and re-released.

7 Comments

Writing Plugins For Windows Live Writer – Using Settings In Your Plugin

So far I’ve shown you how to create basic plugins for Windows Live Writer, in this next guide I’m going to show you how you can use settings in your plugin to make things easier for your end user, you can create default options (that they can customise if you allow them). I’m going to show you how to do exactly that, have the user be able to change the default settings that are applied everytime the plugin is called. I will be carrying this on from my last guide so if you haven’t got that already, download the source now.

First thing’s first, what options does your plugin need? This is still going to be a simple plugin, so anything you put in can’t be changed once inserted, so the options and settings need to be something that the user would want. The simple plugin we have been using so far in this series has been to insert some simple text into the blog entry, so the option I’m going to use is to make it default to use a bold style for the text.

For the settings, we need to create a new Class that will contain all the settings’ properties. In this example, I have called it PluginSettings.cs. Before we call the constructor, we need to just declare an instance of the IProperties Interface: 

        private IProperties m_properties;
        private const string DEFAULTBOLD = "DEFAULTBOLD";

At this point, I also like to declare constants for the setting properties, these will be used in a bit, I will note that you don’t need to put these in, this is more a personal preference for me.

The settings class needs to be passed an IProperties instance so that it has a point of reference, then you need to set the IProperties instance you just declared to be the one that gets passed to the class. So your constructor should look like this: 

        public PluginSettings(IProperties properties)
        {
            m_properties = properties;
        }

Next we write the properties for the settings class, you will need one of these for each of the settings you use in your plugin and they can be one of five different types: int, string, boolean, decimal or float. For this plugin, I’m going to use a boolean type as I want it to either be yes (true) or no (false) for whether the text should be bold or not. This plugin only requires one property, and mine looks like this:  

        public bool DefaultBoldOption
        {
            get { return m_properties.GetBoolean(DEFAULTBOLD, true); }
            set { m_properties.SetBoolean(DEFAULTBOLD, value); }
        }

You’ll see that this is where we used the constant value I mentioned earlier, this is the property name that tells the plugin which setting to get, and you’ll see that there are two sections, a get section, and a set section. The get section must return a value of whatever type you’re using, in this case, a boolean value, so we use the IProperties’ GetBoolean method and put in the property name that we want. The set section is where we assign what the property’s value is going to be. This will all become clearer a bit further on. And that’s the settings class done with.

Now we move back to the plugin’s main class. To start off with, declare a PluginSettings object (I’ve called it m_defaultoptions), this will be set next. To do this, we need to override the Initialize method so that we can get the IProperties object for that plugin. Declaring the settings originally outside of this method means that the default options are available to the rest of the plugin. It should look like this: 

        public override void Initialize(IProperties pluginOptions)
        {
            base.Initialize(pluginOptions);
            m_defaultsettings = new PluginSettings(pluginOptions);
        }

Notice how we pass the PluginSettings class the IProperties object so that it knows where it’s reading/writing from.

You might remember in the previous parts to this guide, in the WriterPlugin section we had HasEditbleOptions set to false, well now we’re going to set it to true, this will enable the Options button in the plugins part of the preferences. Before we tell the plugin about the options window, let’s create the form first. So add a new Windows form to the project (I called mine frmOptions.cs) and make your form look something like this:

Now, hit F7 and go into the code for the form and you will need to add the using WindowsLive.Writer.Api; namespace again. At the top, declare a new instance of the PluginSettings class, and in the constructor we need to then set that to be the PluginSettings that is being passed to the form, then apply the default settings. So your code should look like this:

        public frmOptions(PluginSettings settings)
        {
            InitializeComponent();
            m_settings = settings;
            // This sets the checkbox to be whatever the default option was
            chBoldOption.Checked = m_settings.DefaultBoldOption;
        }

Now these settings are only basic, so when we press the save button, there’s only one setting that needs to be saved, which we do with the following line:

        private void btnSave_Click(object sender, EventArgs e)
        {
            // This actually sets the option to be whatever the checkbox is currently at
            m_settings.DefaultBoldOption = chBoldOption.Checked;
            this.Close();
        }

Right, back to the main plugin class. Now that we have our options form, we need to tell the plugin what to do when the options button is pressed; so we need to override the EditOptions method. In this method, we are literally just going to create a new instance of the PluginSettings and use the stored options for that plugin, then pass that to the form, as follows:

        public override void EditOptions(IWin32Window dialogOwner)
        {
            PluginSettings options = new PluginSettings(this.Options);
            frmOptions op = new frmOptions(options);
            op.ShowDialog();
        }

Now, the final thing to do is actually apply these settings to the text that is put into the blog entry. For this plugin, this is simple as there is only one setting. So in the CreateContent method, we had the if statement to say that if (result == DialogResult.OK) then we make newContent = form.getText. All we will do for this plugin is add an extra if statement after that which checks whether the setting is to be applied or not, and as we have made this setting a boolean value, it makes it even easier to check. So the if statement we want is basically this:

                    if (m_defaultsettings.DefaultBoldOption)
                        newContent = string.Format("<b>{0}</b>", newContent);

And that’s it, you should be done

As always, the source code that I have used can be downloaded here.

Any problems, please leave a comment.

SL

10 Comments