MarcEdit Plugin Development: Using late binding to reference functions

In MarcEdit, plugins provide a way to extend the application’s functionality.  However, there are a couple of best practices that developers working with MarcEdit should generally follow if working with C#/.NET.

  1. Only create a Reference to the MacroInterfaces.dll.  I rarely change this file.  This is important.  I strongly name and sign all libraries, so any library that is referenced — if changed — will require you to recompile your code as well.  Don’t do that.
  2. If you want to use functionality in MarcEdit’s libraries (like the MARCEngine7.dll — use late binding.

Late binding in C# use to be considerably harder — but that was before the introduction of dynamic variables.  Now, you can avoid using Invoke statements, and simply define a new type and then allow the compiler to determine the variable time at runtime. 

So what might an example look like?  Well, here’s how you would late bind to the MARCEngine7.MARC21 object, and then make a call to the MARCMaker function.

     private void Button1_Click(object sender, EventArgs e)
        {
            //Late Bind
            //MARCEngine5.MARC21 compiler = new MARCEngine5.MARC21();
            //compiler.MMaker(temp_name, fileFullName);

            
            try
            {
                Type MarcEngine;
                object[] parameters = new object[2];
                //Get the MarcEngine object 
                MarcEngine = Type.GetTypeFromProgID("MARCEngine7.MARC21");
                //MarcEngine5 works with MarcEdit 6 and 7, MARCEngine7 attaches to 
                //the MarcEdit 7 object.
                //objMarc = Type.GetTypeFromProgID("MarcEngine5.MARC21");
                //Create instance of MarcEngine 
                dynamic objMarc = Activator.CreateInstance(MarcEngine);
                //Set the arguments to the method I'll invoke
                string sSource = textBox1.Text;
                string sDest = textBox2.Text;
                dynamic dret = objMarc.MMaker(sSource, sDest);
                
                MessageBox.Show("Return Val: " + dret.ToString());
            }
            catch (Exception oError)
            {
                System.Windows.Forms.MessageBox.Show(oError.ToString());
            }
        }

This is it.   The most important parts of this happen in the statement:
Type MarcEngine
This establishes a new type.  And then the CreateInstance — which is how the compiler dynamically sets the object type. 

If you follow this process, you will not need to update your plugins when MarcEdit is updated because your program will bind to objects at runtime rather than forcing bindings to specific versions. 

Questions, let me know.

–tr


Posted

in

,

by

Tags: