Monthly Archives: August 2014

Using the Managed Extensibility Framework (MEF) to implement a third-party plugin solution. Part 3 – Developing the plugins

Now that my application supports plugins, I’m ready to publish my plugin SDK out for other developers to make use of.  If I take a look in my .\bin\Debug folder for the MyPluginApp project (yes, I’m staying in Debug mode for the purposes of this example) I see the following.

Debug Folder Contents

MyPluginApp.exe of course is my Windows Forms Application executable, but in addition to that there is a file called MyPluginApp.Plugins.dll.  This .dll is the compiled version of the Class Library that I added to my solution in Part 2 named MyPluginApp.Plugins.  This is the .dll that I will need to make available to 3rd party developers (henceforth I will refer to this as my “SDK”).  Along, of course, with some thorough documentation outlining what exactly I am expecting them to implement and what metadata I am expecting.

Now I am going to create a new solution from the perspective of a 3rd party developer who wants to develop a plugin for my application.  I start by creating a new “Class Library” project, because I want my code to compile to a .dll that I can place in the Plugins directory for my application.  I’m going to call my new solution MyPluginApp_StarterPlugins.

Once my new solution and project have been created, I take the MyPluginApp.Plugins.dll file that I downloaded as part of the application developer’s SDK *wink wink* and place it in my project directory.  I then add the file to my project, making sure to set the Build Action to ‘None’ and Copy to Output Directory to ‘Do Not Copy.’  The step of explicitly adding the .dll file to my solution is not required, however I think it adds some clarity to what the purpose of my project is.  Now that I’ve physically gotten the SDK into the appropriate place, I need to add a reference to it within the project.  I do this by adding a reference to the actual .dll file that I just moved into my project’s directory.  Also, just to keep Visual Studio from copying the .dll to my bin\{Debug}{Release} folders, I will set “Copy Local” property of the reference to false.  I also need to add a reference to System.Windows.Forms because my intention is to use MessageBox when my plugins perform their tasks.  Finally, I need to add a reference to System.ComponentModel.Composition in order to gain access to the necessary MEF namespaces.

Project Directory

Project Directory Contents

Solution Explorer Containing File

Solution Explorer View

Reference

Solution Explorer References

I’m going to develop two simple plugins within this project.  The first will be called AdditionPlugin, and will add the two numbers together.  The second will be called MultiplicationPlugin, and will multiply the two numbers together.  These plugins will both impliment the IPlugin interface which we defined in the MyPluginApp.Plugins projects and is available to me as a 3rd party developer within the .dll that I have added to my project.

Now I’m ready to define my first plugin.  First I will create the AdditionPlugin.  I rename the Class1.cs default file to AdditionPlugin.cs and replace its contents with the following:

using System;

using System.ComponentModel.Composition; //MEF namespace for Exporting
using System.Windows.Forms; 

namespace MyPluginApp.Plugins
{
    [Export(typeof(IPlugin))] //**1
    [ExportMetadata("Name", "Addition Plugin")] //**2
    public class AdditionPlugin : IPlugin
    {
        public void HandleNumbers(decimal num1, decimal num2)
        {
            MessageBox.Show(string.Format("{0} + {1} = {2}", num1, num2, num1 + num2), "Addition Plugin");
        }
    }


    
    //**1 - This will allow the CompositionContainer in MyPluginApp know that this class is of type IPlugin, which will be loaded 
    //  when we call .GetExports<IPlugin, IPluginMetaData() in the LoadPlugins() method.

    //**2 - This is how MetaData is exported by the Plugin.  The exported metadata needs to match with the metadata interface we defined in MyPluginApp.
    //  In this case we have only 1 defined field in IPluginMetaData called "Name", so that is the only peice of metadata that we want to export.
}

Now if this plugin is enabled (remember the Checked List Box in MyPluginApp?), its HandleNumbers method will be added to the MyButtonClicked event, which gets Invoked every time the button on my form gets clicked.

Similarly to the AdditionPlugin, I add a new .cs file to the project and name it MultiplicationPlugin.cs.  Here are the contents of that file:

using System;
using System.ComponentModel.Composition; //MEF namespace for Exporting
using System.Windows.Forms;

namespace MyPluginApp.Plugins
{
    [Export(typeof(IPlugin))]
    [ExportMetadata("Name", "Multiplication Plugin")]
    public class MultiplicationPlugin : IPlugin
    {
        public void HandleNumbers(decimal num1, decimal num2)
        {
            MessageBox.Show(string.Format("{0} * {1} = {2}", num1, num2, num1 * num2), "Multiplication Plugin");
        }
    }
}

Now I can build my solution.  After the build is complete, I find the following in MyPluginApp_StarterPlugins bin\Debug folder:

image

MyPluginApp_StarterPlugins.dll needs only to be placed in the \Plugins directory of MyPluginApp prior to MyPluginApp being started up.  Here is what MyPluginApp looks like after I do just that.

MyPluginApp with loaded plugins

Clicking on MyButton at this point still yields the familiar output from before Plugin support was added.

MyPluginApp Output no plugins enabled

Clicking OK on the MessageBox dialog returns me to the application.  Now I change Number 1 to “8,” check both boxes, and then click MyButton.

MyPluginApp Enabled Plugins

MyPluginApp - App Output

MyPluginApp - Addition Plugin Output

MyPluginApp - Multiplication Plugin Output

Unchecking the box next to a plugin prior to clicking MyButton again causes that plugin to become unsubscribed from the event, so its MessageBox no longer pops up.

I’ve certainly only begun to scratch the surface of MEF in this series of posts.  But I hope that this simple tutorial showing a method of developing plugin .dll files completely independently of your original application’s code/solution will be of some value to someone.

I have posted a .zip file containing both complete solutions Here.

Using the Managed Extensibility Framework (MEF) to implement a third-party plugin solution. Part 2–Plugin Support in the Application

Now that I have a feature-complete application from my perspective, I am ready to add plugin support so that other developers can extend the functionality of my application.  I don’t want to make my application open source, so I want to just expose enough information about my application to them that they are able to create plugins.

In order to give my application access to MEF, I need to add a reference to the appropriate namespace within my windows forms application.  The namespace I need to reference is System.ComponentModel.Composition.  Once I’ve done that, I need to add a new project to my solution of type “Class Library.”  This project will be my “Plugin API” and will compile to a .dll file that I can distribute to developers as a part of my SDK so that they can create plugins that adhere to my standard.  After creating my new project, I need add a reference to that project from within my Windows Forms project.

At this point, my application solution looks like this:

Solution Explorer

Here are the contents of IPlugin.cs in the MyPluginApp.Plugins project:

using System;

namespace MyPluginApp.Plugins
{
    //This interface defines what we expect a plugin developer to impliment in order for our application to make use of their plugin
    public interface IPlugin
    {
        //This method's signature matches the MyButtonClickedEventHandler in our application
        void HandleNumbers(decimal num1, decimal num2);
    }

    //MEF allows for metadata to be exported along with the object itself, we need a separate interface to receive any metatdata that we expect
    // plugin developers to include as well.
    public interface IPluginMetaData
    {
        string Name { get;}
    }
}

Next I need to update my UI so that it is able to display the list of available plugins and allow the user enable/disable them at will.  I’ve opted to use a checked list box to achieve that goal.  The plugins will load initially disabled, and the user simply needs to check the box next to the plugin in order to enable it, similarly unchecking the box will cause the plugin to be disabled.

Here is my New UI

MyPluginApp

And now the code for the form, including the code to enable plugin support.  New lines of code are highlighted for your convenience.

using System;
using System.Windows.Forms;

using System.Collections.Generic;
using MyPluginApp.Plugins;  //Our plugin namespace
using System.ComponentModel.Composition.Hosting; //MEF namespace

namespace MyPluginApp
{
    public partial class Form1 : Form
    {
        private delegate void MyButtonClickedEventHandler(decimal num1, decimal num2);
        private event MyButtonClickedEventHandler MyButtuttonClicked;

        private readonly Dictionary<string, IPlugin> _plugins = new Dictionary<string, IPlugin>();

        public Form1()
        {
            InitializeComponent();

            this.LoadPlugins();
        }

        //the Leave event handler for both text boxes
        private void textNum_Leave(object sender, EventArgs e)
        {
            decimal d;
            var textNum = (TextBox) sender;

            if (!decimal.TryParse(textNum.Text, out d))
            {
                textNum.Text = "5";
            }
        }

        //The KeyDown event handler for both text boxes
        private void txtNum_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter || e.KeyData == Keys.Return)
            {
                btnMyButton.Focus(); //fires the Leave event for the active text box
                btnMyButton.PerformClick();
            }
        }

        //OnClick event handler for the button
        private void btnMyButton_Click(object sender, EventArgs e)
        {
            decimal num1;
            decimal num2;

            MessageBox.Show(string.Format("You entered {0} and {1}", txtNum1.Text, txtNum2.Text));

            if (decimal.TryParse(txtNum1.Text, out num1) && decimal.TryParse(txtNum2.Text, out num2))
            {
                //If our new event has any subscribers, invoke the event.
                if(this.MyButtuttonClicked != null)
                    this.MyButtuttonClicked.Invoke(num1, num2);
            }
        }

        private void LoadPlugins()
        {
            var pluginDir = System.IO.Path.GetDirectoryName(Application.ExecutablePath) + @"\Plugins\";

            //Create plugin directory if it doesn't exist
            System.IO.Directory.CreateDirectory(pluginDir);

            //DirectoryCatalog gets a list of all .dll files in our plugin directory
            var catalog = new DirectoryCatalog(pluginDir, "*.dll");

            //CompositionContainer parses all of the dlls in the catalog and identifies their exports
            var container = new CompositionContainer(catalog);

            //Iterate through each export that matches our IPlugin interface and add it to our plugin collection
            foreach (var plugin in container.GetExports<IPlugin, IPluginMetaData>())
            {
                this._plugins.Add(plugin.Metadata.Name, plugin.Value);
                this.clbPlugins.Items.Add(plugin.Metadata.Name, false);
            }

            //Best practice per MS is to dispose the CompositionContainer as soon as we are finished with it.
            container.Dispose();
            catalog.Dispose();
        }

        //ItemCheck event for clbPlugins (checked list box)
        private void clbPlugins_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            var item = clbPlugins.Items[e.Index].ToString();


            if (e.NewValue == CheckState.Checked)
            {
                //If the user checked the box for the plugin, subscribe the plugin's handler to the event
                this.MyButtuttonClicked += this._plugins[item].HandleNumbers;
            }
            else
            {
                //If the user unchecked the box for the plugin, unsubscribe the plugin's handler to the event
                this.MyButtuttonClicked -= this._plugins[item].HandleNumbers;
            }
        }
    }
}

This concludes post #2.  In Post #3 I will create a few example plugins in their own solution without access to any of the code contained in Form1.cs, just as I would expect a 3rd party developer to be able to do.

Using the Managed Extensibility Framework (MEF) to implement a third-party plugin solution. Part 1–Introduction

I recently started working on a project that would benefit greatly from the ability to support plugins that were developed by someone other than myself or anyone else who necessarily had access to our source code. Having never really done anything like this myself I set off and tried to research it. I found a lot of information about loading compiled .dll files, using reflection and Activator.CreateInstance and so on. Then in the comments of those posts I’d see someone say “Why don’t you use MEF?” and that’s it; no other information.

In a quick nutshell, here’s what Wikipedia has to say about MEF as of August 2014:

Managed Extensibility Framework (MEF) is a component of .NET Framework 4.0 aiming to create lightweight, extensible applications. It allows application developers to discover and use extensions with no configuration required. It also lets extension developers easily encapsulate code and avoid fragile hard dependencies. MEF also allows extensions to be reused across applications. MEF was introduced as a part of .NET 4.0 and Silverlight 4.

Additionally, here is the MSDN page for your reference.

In my research, I found a lot of great examples of using MEF to quickly load external dll files and instantiate the types that they had defined within them. The problem was, all of the examples I found had all of the projects (application and plugins) contained within a single solution. I wanted to know how to enable someone else to take my plugin specification and implement it, without me having to distribute my entire solution to them. I never did find a true tutorial on that aspect of MEF, but I did figure out a way that works and that is the way I am going to present in this series. If anyone happens upon this series and has a better method, I’d be happy to learn from you!

In this series of posts I am going to go through the process of creating a .NET 4.0 Windows Forms application that implements a simple plugin system.  The plugins system will load any available plugins on startup and allow the user to enable/disable them.  I will then create an entirely separate solution that creates some example plugins that can be loaded an used by my original program.  This should simulate the workflow that I would expect a third-party developer to go through to develop plugins for my application.

The series will consist of 3 posts.  The first post, which you are now reading, will serve as the introduction and cover the initial application (without plugin support).  In the second post, I will add plugin handling capabilities to the application, and in the third post I will create a couple sample plugins within their own solution.

I’m going to use Visual Studio 2010 for this project.  I will include zipped archives for both solutions at the end of the series.

To start out, I have created a simple application that allows the user to enter two numbers, then reports back to them what they entered.

Application

The Application

Result of pressing the button

Result of Button Press

And the code for my application

using System;
using System.Windows.Forms;

namespace MyPluginApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //the Leave event handler for both text boxes
        private void textNum_Leave(object sender, EventArgs e)
        {
            decimal d;
            var textNum = (TextBox) sender;

            if (!decimal.TryParse(textNum.Text, out d))
            {
                textNum.Text = "5";
            }
        }

        //The KeyDown event handler for both text boxes
        private void txtNum_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter || e.KeyData == Keys.Return)
            {
                btnMyButton.Focus(); //fires the Leave event for the active text box
                btnMyButton.PerformClick();
            }
        }

        //OnClick event handler for the button
        private void btnMyButton_Click(object sender, EventArgs e)
        {
            MessageBox.Show(string.Format("You entered {0} and {1}", txtNum1.Text, txtNum2.Text));
        }
    }
}

This concludes the first post of the series.  In the next post I will add the capability for my application to load and utilize plugins.

Renaming poorly named constraints in MS SQL

I recently found myself in a situation where I was working on tuning SQL Server performance in a SQL Server 2008 R2 environment. What made this environment different than other environments that I had worked on in the past, was that the environment had ~400 databases that were all (essentially) identical in structure. The company sells a remote-hosted solution, so whenever a new client comes on board they simply spin each client off their own appropriately structured database that they can then begin filling with their own data.

In the process of tuning the SQL performance, there were many instances where I needed to make changes to Primary and Foreign keys, unfortunately many of the keys did not have the same name in each database; because when the tables were originally created the constraints were not explicitly named; and were instead named by SQL Server itself.

Consider these simple examples.

--Implicit
CREATE TABLE dbo.Users
(
	id_Users int IDENTITY(1,1) NOT NULL PRIMARY KEY
	, UserName nvarchar(20) NOT NULL
	, UserPassword nvarchar(20) NOT NULL
);

CREATE TABLE dbo.UserLoginHistory
(
	id_Users int NOT NULL FOREIGN KEY REFERENCES dbo.Users (id_Users)
	, LoginTime datetime2 NOT NULL
);
CREATE CLUSTERED INDEX cidx_dbo_UserLoginHistory ON dbo.UserLoginHistory (id_Users);

select name, 'pk' AS [type] FROM sys.key_constraints WHERE parent_object_id = OBJECT_ID('dbo.Users')
union all
select name, 'fk' AS [type] FROM sys.foreign_keys WHERE parent_object_id = OBJECT_ID('dbo.UserLoginHistory');

And here is an example of explicitly defined primary and foreign keys:

--Explicit
CREATE TABLE dbo.Users
(
	id_Users int IDENTITY(1,1) NOT NULL
	, UserName nvarchar(20) NOT NULL
	, UserPassword nvarchar(20) NOT NULL
	, CONSTRAINT pk_dbo_Users PRIMARY KEY CLUSTERED (id_Users)
);

CREATE TABLE dbo.UserLoginHistory
(
	id_Users int NOT NULL
	, LoginTime datetime2 NOT NULL
	, CONSTRAINT fk_dbo_UserLoginHistory_dbo_Users FOREIGN KEY (id_Users) REFERENCES dbo.Users (id_Users)
);
CREATE CLUSTERED INDEX cidx_dbo_UserLoginHistory ON dbo.UserLoginHistory (id_Users);

select name, 'pk' AS [type] FROM sys.key_constraints WHERE parent_object_id = OBJECT_ID('dbo.Users')
union all
select name, 'fk' AS [type] FROM sys.foreign_keys WHERE parent_object_id = OBJECT_ID('dbo.UserLoginHistory');

And the results from each:

Implicit
type	name
pk	PK__Users__B3F21DFE5BED93EA
fk	FK__UserLogin__id_Us__5ECA0095

Explicit
type	name
pk	pk_dbo_Users
fk	fk_dbo_UserLoginHistory_dbo_Users

When you allow SQL Server to name your constraints for you, it will generate a name that is partially based on the object name, then append a set of random hex characters to the end. So in the case of the system I was working in, this resulted in 400 different names for the same constraints. So any maintenance I wanted to perform against those constraints would first have to dynamically identify the name of the constraint before the logic could proceed. Further, any future maintenance would require the same level of effort. I opted to create these two simple scripts which would name all Primary and Foreign keys based on a defined naming convention, thus bringing all of the databases into sync and making future maintenance much easier, so long as future development does not use implicit constraint creation techniques.

-------------------------------------------
--Rename all system generated primary keys using the following format
-- pk_schema_tablename
-------------------------------------------
DECLARE @oldname nvarchar(776)
        , @newname sysname;

DECLARE key_curse CURSOR FAST_FORWARD FOR (SELECT
                                                '[' + SCHEMA_NAME(kc.schema_id) + '].[' + kc.name + ']' AS [oldname]
                                                , 'pk_' + SCHEMA_NAME(kc.schema_id) + '_' + OBJECT_NAME(kc.parent_object_id) AS [newname]
                                                FROM sys.key_constraints kc
                                                WHERE
                                                    kc.type = 'PK'
                                                    AND kc.name <> 'pk_' + SCHEMA_NAME(kc.schema_id) + '_' + OBJECT_NAME(kc.parent_object_id));

OPEN key_curse

    FETCH NEXT FROM key_curse INTO @oldname, @newname;

    WHILE(@@FETCH_STATUS = 0)
    BEGIN

        print substring(@oldname, charindex('.', @oldname) + 1, len(@oldname)) + '     ' + @newname;
        EXEC sp_rename @objname = @oldname, @newname = @newname, @objtype = 'OBJECT';

        FETCH NEXT FROM key_curse INTO @oldname, @newname;
    END

CLOSE key_curse;
DEALLOCATE key_curse;
GO

-------------------------------------------
--Rename all system generated foreign keys using the following format
-- fk_schema1_tablename1_schema2_tablename2
-- where schema/table 1 = the ReferencING table
-- and schema/table 2 = the ReferencED table
-------------------------------------------
DECLARE @oldname nvarchar(776)
		, @newname sysname;

DECLARE key_curse CURSOR FAST_FORWARD FOR (select
											'[' + SCHEMA_NAME(o_ing.schema_id) + '].[' + fk.name + ']' AS [oldname]
											, 'fk_' + SCHEMA_NAME(o_ing.schema_id) + '_' + o_ing.name + '_' + SCHEMA_NAME(o_ed.schema_id) + '_' + o_ed.name AS [newname]
											FROM sys.foreign_keys fk
											JOIN sys.objects o_ing ON o_ing.object_id = fk.parent_object_id
											JOIN sys.objects o_ed ON o_ed.object_id = fk.referenced_object_id
											WHERE
												fk.name <> 'fk_' + SCHEMA_NAME(o_ing.schema_id) + '_' + o_ing.name + '_' + SCHEMA_NAME(o_ed.schema_id) + '_' + o_ed.name); --The format of our standard key

OPEN key_curse

	FETCH NEXT FROM key_curse INTO @oldname, @newname;

	WHILE(@@FETCH_STATUS = 0)
	BEGIN

		print SUBSTRING(@oldname, charindex('.', @oldname) + 1, len(@oldname)) + '     ' + @newname;
		EXEC sp_rename @objname = @oldname, @newname = @newname, @objtype = 'OBJECT';

		FETCH NEXT FROM key_curse INTO @oldname, @newname;
	END

CLOSE key_curse;
DEALLOCATE key_curse;
GO

There was already a system in place to apply a SQL script to every client database, so there was no need to employ sp_MSForeachdb (Just Kidding!) Aaron Bertrand’s sp_foreachdb.

I haven’t tested this script against any other versions of MSSQL, but I think it should work fine on anything >= SQL Server 2005.

In closing, to all you developers out there, please take the time to explicitly name your constraints!