C# code for Plugin System (1 Viewer)

egonspengleruk

Retired Team Member
  • Premium Supporter
  • June 30, 2005
    250
    0
    Hi all,

    Can anyone point me in the direction of a good example plugin system for C#? Ive got a project at work which requires this and even though I have the MP source code, its not easy to just find the plugin related bits of it.

    Cheers

    Mat
     

    and-81

    Retired Team Member
  • Premium Supporter
  • March 7, 2005
    2,257
    183
    Melbourne
    Home Country
    Australia Australia
    Here's a slightly modified piece of code from my IR Server program.

    Basically it just goes through all the dll files in the plugin folder to find ones that contain plugins in them (plugins must inherit the IRServerPluginBase class).

    Code:
        List<IRServerPluginBase> AvailablePlugins()
        {
          try
          {
            List<IRServerPluginBase> plugins = new List<IRServerPluginBase>();
    
            string installFolder = SystemRegistry.GetInstallFolder();
            if (String.IsNullOrEmpty(installFolder))
              return null;
    
            string[] files = Directory.GetFiles(installFolder + "\\IR Server Plugins\\", "*.dll", SearchOption.TopDirectoryOnly);
    
            foreach (string file in files)
            {
              try
              {
                Assembly assembly = Assembly.LoadFrom(file);
                Type[] types = assembly.GetExportedTypes();
    
                foreach (Type type in types)
                {
                  if (type.IsClass && !type.IsAbstract && type.IsSubclassOf(typeof(IRServerPluginBase)))
                  {
                    IRServerPluginBase plugin = (IRServerPluginBase)assembly.CreateInstance(type.FullName);
    
                    if (plugin != null)
                      plugins.Add(plugin);
                  }
                }
              }
              catch (BadImageFormatException)
              {
                // Ignore Bad Image Format Exceptions, just keep checking for IR Server Plugins
              }
              catch (TypeLoadException)
              {
                // Ignore Type Load Exceptions, just keep checking for IR Server Plugins
              }
              catch (Exception ex)
              {
                MessageBox.Show(ex.ToString(), "IR Server Plugin Error");
              }
            }
    
            return plugins;
          }
          catch
          {
            return null;
          }
        }

    Hope that helps,
     

    Users who are viewing this thread

    Top Bottom