Click here to Skip to main content
15,897,704 members
Articles / General Programming / Threads

Plugged.NET - An event based plug-in library for enterprise application integration and extensibility

Rate me:
Please Sign up or sign in to vote.
4.89/5 (19 votes)
25 Jul 2013CPOL6 min read 34.1K   1.4K   92  
An event based plug-in library for enterprise application integration, extensibility and cross business application management.
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Reflection;
using System.Security.Principal;
using System.Windows;
using System.Windows.Controls;
using Microsoft.VisualBasic.ApplicationServices;
using Microsoft.Win32;
using Common.Plugin.Platform.Common;
using Common.Plugin.Platform.Events;
using System.Collections.Generic;
using Common.Plugin.Platform;

namespace Common.Plugin.SampleHost
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private ApplicationHost host;

        public MainWindow()
        {
            InitializeComponent();
            host = new ApplicationHost(GetExtensionMessage);
        }

        public void Add(string text)
        {
            var message = string.Format("\r\n{0}:{1}", Directory.Exists(text) ? "Folder" : "File", text);
            textBox1.AppendText(message);

            this.Dispatcher.Invoke((Action)(() => host.FileSystemEvent(new FileSystemInfoEventArg(text))));
        }

        public void GetExtensionMessage(string message)
        {
            this.Dispatcher.Invoke((Action)(() => textBox1.Text += "\r\n" + message));
            OnShowNotifyMessage(this, new NotifyIconMessageArgs() { Message = "Response received from one of the loaded plugins" });
        }

        private void RegisterExtensions()
        {
            if (!host.PluginsInitialized)
            {
                host.ReloadPlugins(GetPluginsFromConfiguration());
            }
        }

        private void UnLoadExtensions()
        {
            if (host.PluginsInitialized)
            {
                host.RemovePlugins(GetPluginsFromConfiguration());
            }
        }

        private IEnumerable<PluginInfo> GetPluginsFromConfiguration()
        {
            var plugins = new List<PluginInfo>();

            plugins.Add(new PluginInfo() { DisplayName = "KickStart", Name = "KickStartPlugin", Version = "0.0.0.1" });
            plugins.Add(new PluginInfo() { DisplayName = "TimeEvent", Name = "TimeEventPlugin", Version = "0.0.0.1" });

            return plugins;
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            UnLoadExtensions();
            RemovePluginsFromMenu();
        }
        private void button2_Click(object sender, RoutedEventArgs e)
        {
            RegisterExtensions();
            AddPluginsToMenu();
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            this.Hide();
            e.Cancel = true;
        }
    }

    public class SingleInstanceApplication : Application
    {
        protected override void OnStartup(System.Windows.StartupEventArgs e)
        {
            AddRegistry("*", "Directory");
            base.OnStartup(e);

            MainWindow window = new MainWindow();
            window.Show();
        }

        public void Activate()
        {
            MainWindow.Activate();
        }

        protected override void OnExit(ExitEventArgs e)
        {
            base.OnExit(e);
            DeleteRegistry("*", "Directory");
        }

        private void AddRegistry(params string[] extensions)
        {
            var filename = Assembly.GetExecutingAssembly().Location;

            foreach (var ext in extensions)
            {
                var regmenu = Registry.CurrentUser.CreateSubKey("Software\\Classes\\" + ext + "\\shell\\Plugin.Platform");
                if (regmenu != null)
                {
                    regmenu.SetValue("", "Send to Plugin");
                    regmenu.SetValue("icon", filename + ",0");
                    regmenu.SetValue("EditFlags", new byte[] { 0x01, 0x00, 0x00, 0x00 }, RegistryValueKind.Binary);
                }

                var regcmd = Registry.CurrentUser.CreateSubKey("Software\\Classes\\" + ext + "\\shell\\Plugin.Platform\\command");
                if (regcmd != null)
                    regcmd.SetValue("", filename + " %1");
            }
        }

        private void DeleteRegistry(params string[] extensions)
        {
            var filename = Assembly.GetExecutingAssembly().Location;

            foreach (var ext in extensions)
            {
                Registry.CurrentUser.DeleteSubKeyTree("Software\\Classes\\" + ext + "\\shell\\Plugin.Platform");
            }
        }

        private bool IsUserAdministrator
        {
            get
            {
                bool isAdmin = false;
                try
                {
                    var principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
                    isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
                }
                catch (UnauthorizedAccessException)
                {

                }
                catch (Exception)
                {

                }
                return isAdmin;
            }
        }
    }

    public class SingleInstanceManager : WindowsFormsApplicationBase
    {
        private SingleInstanceApplication _application;
        private ReadOnlyCollection<string> _commandLine;

        public SingleInstanceManager()
        {
            IsSingleInstance = true;
        }

        protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs eventArgs)
        {
            // First time _application is launched
            _commandLine = eventArgs.CommandLine;
            _application = new SingleInstanceApplication();
            _application.Run();
            return false;
        }

        protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
        {
            // Subsequent launches
            base.OnStartupNextInstance(eventArgs);
            _commandLine = eventArgs.CommandLine;
            (_application.MainWindow as MainWindow).Add(string.Join(" ", eventArgs.CommandLine));
            _application.Activate();
        }
    }

    public class EntryPoint
    {
        [STAThread]
        public static void Main(string[] args)
        {
            SingleInstanceManager manager = new SingleInstanceManager();
            manager.Run(args);
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
is a poor software developer and thinker. Presently working on a theory of "complementary perception". It's a work in progress.

Comments and Discussions