Adding Simple Plug-In Structure To Your Programs

by Bar Zohan 21. January 2010 01:40

Briefing:

In this article I'm going to implement a simple plug in structured calculator. Calculator will take two numeric inputs from the user and user will select which calculator plug in to use. After that user will hit calculate button and our little program will ask the plug in to calculate those two numeric values and mbox the result that plug in sends as. Here's what I'm going to do step by step.

  • First open a windows forms project and add two textboxes which will take input from the user as integers or doubles etc. Add a calculate button. Add one listview for listing loaded plugins. Add some labels explaining our form :).
  • Add a class library project to our solution which is going to include our Plug-In Interface. We'll put this interface to a seperate class library project because we don't want to give away full source code of our software to plug in writers ;). This interface will hold simply one Calculate method and a string property field called Operation for identifying our plug in.
  • We'll add another class library project which is going to be actualy our plug-in. This project should give a reference to the project we've just added that contains our interface. And we'll implement our interface in a little class.
  • Compile our project. Put the plug-in's dll file inside a directory such as 'PlugIns' right beside our executable file.
  • When our executable file runs it first searches that directory for plug in files. Once it finds them it'll add these plugins to a list for later use in our calculate button click event.

This is it for now. Let's start writing.

Form Look:

I know it looks dummy :) 

ICalculator Interface

 public interface ICalculator
    {
        double Calculate(double a, double b);
        string Operation { get; }
      
    }

The Multiplier Plug In


    class Multiplier:ICalculator
    {
        #region ICalculator Members

        public double Calculate(double a, double b)
        {
            return a * b;
        }

        public string Operation
        {
            get
            {
                return "x";
            }
        }


        #endregion
    }

Windows Form

  private void LoadPlugins()
        {
            string[] files = Directory.GetFiles(Application.StartupPath + "/PlugIns");
            foreach (string file in files)
            {
                Assembly asm = Assembly.LoadFile(file);
                foreach (Type t in asm.GetTypes())
                {
                    if (t.GetInterface("ICalculator") == typeof(ICalculator))
                    {
                         ICalculator calculatorPlugIn =(ICalculator) Activator.CreateInstance(t);
                         ListViewItem lvi = new ListViewItem();
                         lvi.Text = calculatorPlugIn.Operation;
                         lvi.Tag = calculatorPlugIn;
                         lvPlugIns.Items.Add(lvi);
                    }
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            LoadPlugins();
        }

        private void btnCalc_Click(object sender, EventArgs e)
        {
            try
            {
                if (lvPlugIns.SelectedItems.Count > 0)
                {
                    ICalculator calculator = (ICalculator)lvPlugIns.SelectedItems[0].Tag;
                    double a = Convert.ToDouble(txt1.Text);
                    double b = Convert.ToDouble(txt2.Text);
                    double result = calculator.Calculate(a, b);
                    MessageBox.Show("Result Is: " + result.ToString());
                }
                else
                {
                    MessageBox.Show("Please select 1 plug in");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception...");
            }
          
        }


Note: A plug in writer can use several types inside a dll file. So we need to find out which of those types are derived from our ICalculator interface. if (t.GetInterface("ICalculator") == typeof(ICalculator)) part is spesifically used for that.

Note 2: After compiling your project you should put the plug-in's dll file into folder that LoadPlugins method searches in. By default it's Directory.GetFiles(Application.StartupPath + "/PlugIns");

 

Sample Source Code:

PlugInsSample.rar (68,95 kb)

kick it on DotNetKicks.com

Tags: , ,

.Net Framework | C#

Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen