Esempio n. 1
0
        private static void Main()
        {
            Log.Message(LogType.INIT, "                AIO SANDBOX                ");
            Log.Message(LogType.INIT, "             REALM/PROXY/WORLD             ");
            Log.Message();
            Log.Message(LogType.NORMAL, "Starting AIO Sandbox WorldServer...");
            Log.Message();

            // Load Plugins
            PluginHandler pluginHandler = new PluginHandler();

            Sandbox = pluginHandler.SandboxSelector();

            RealmManager.RealmSession = new RealmSocket();
            WorldManager.WorldSession = new WorldSocket();

            if (WorldManager.WorldSession.Start() && RealmManager.RealmSession.Start())
            {
                Authenticator.LoadConfig();

                RealmManager.RealmSession.StartRealmThread();
                RealmManager.RealmSession.StartProxyThread();
                WorldManager.WorldSession.StartConnectionThread();

                Log.Message();
                Log.Message(LogType.NORMAL, "Loading {0}", Sandbox.RealmName);
                Log.Message(LogType.NORMAL, "RealmProxy listening on {0} port(s) {1}.", "127.0.0.1", Sandbox.RealmPort);
                Log.Message(LogType.NORMAL, "RedirectServer listening on {0} port {1}.", "127.0.0.1", Sandbox.RedirectPort);
                Log.Message(LogType.NORMAL, "WorldServer listening on {0} port {1}.", "127.0.0.1", Sandbox.WorldPort);
                Log.Message(LogType.NORMAL, "Started {0}", Sandbox.RealmName);
                Log.Message();
                Log.Message(LogType.NORMAL, "Default client password set to \"{0}\"", Authenticator.Password);
                Log.Message();

                HandlerDefinitions.InitializePacketHandler();
                AreaTriggers.Initialize(Sandbox);
                Worldports.Initialize(Sandbox);
            }
            else
            {
                if (!WorldManager.WorldSession.Started)
                {
                    Log.Message(LogType.ERROR, "WorldServer couldn't be started.");
                }
                if (!RealmManager.RealmSession.Started)
                {
                    Log.Message(LogType.ERROR, "RealmServer couldn't be started.");
                }

                Log.Message();
            }

            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
        /// <summary>
        /// 安装/升级插件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="handler"></param>
        /// <returns></returns>
        public static bool InstallPlugin(string url, PluginHandler <PluginPackAttribute> handler)
        {
            var    installResult = false;
            string appDirectory  = AppDomain.CurrentDomain.BaseDirectory;
            var    pluginPath    = String.Concat(
                appDirectory,
                PluginConfig.PLUGIN_DIRECTORY);

            var tempDir  = String.Concat(appDirectory, PluginConfig.PLUGIN_TMP_DIRECTORY, "plugin/");
            var fileName = tempDir + "dl_pack_" + String.Empty.RandomLetters(16) + ".zip";

            if (Directory.Exists(tempDir))
            {
                Directory.Delete(tempDir, true);
            }
            Directory.CreateDirectory(tempDir).Create();

            var dir = new DirectoryInfo(tempDir);

            var data = WebClient.DownloadFile(url, null);

            using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
            {
                fs.Write(data, 0, data.Length);
                fs.Flush();
                fs.Dispose();
            }

            IList <PluginPackAttribute> pluginAttrs = new List <PluginPackAttribute>(GetPluginPackInfo(fileName));

            if (pluginAttrs.Count != 0)
            {
                ZipUtility.UncompressFile(pluginPath, fileName, false);
                foreach (FileInfo file in dir.GetFiles("*.dll"))
                {
                    File.Delete(pluginPath + file.Name);
                    file.MoveTo(pluginPath + file.Name);
                }

                if (handler != null)
                {
                    var result = false;
                    foreach (PluginPackAttribute attr in pluginAttrs)
                    {
                        handler(attr, ref result);
                    }
                }

                installResult = true;
            }

            Directory.Delete(tempDir, true);

            return(installResult);
        }
Esempio n. 3
0
 public static void HandlePlugn(ChannelGroup group)
 {
     if (group.Async)
     {
         PluginHandler.Async(group);
     }
     else
     {
         _ = PluginHandler.Sync(group);
     }
 }
Esempio n. 4
0
 public void AddHandler(PluginHandler plugin)
 {
     if (plugin == null)
     {
         _plugin = plugin;
     }
     else
     {
         _plugin += plugin;
     }
 }
Esempio n. 5
0
        static void Main()
        {
            Log.Message(LogType.INIT, "                AIO SANDBOX                ");
            Log.Message(LogType.INIT, "             REALM/PROXY/WORLD             ");
            Log.Message();
            Log.Message(LogType.NORMAL, "Starting AIO Sandbox WorldServer...");
            Log.Message();

            //Load Plugins
            PluginHandler.GetPlugins();
            Sandbox = PluginHandler.SelectPlugin();

            RealmManager.RealmSession = new RealmSocket();
            WorldManager.WorldSession = new WorldSocket();

            if (WorldManager.WorldSession.Start() && RealmManager.RealmSession.Start())
            {
                RealmManager.RealmSession.StartRealmThread();
                RealmManager.RealmSession.StartProxyThread();
                WorldManager.WorldSession.StartConnectionThread();

                Log.Message();
                Log.Message(LogType.NORMAL, "RealmProxy listening on {0} port(s) {1}.", "127.0.0.1", Sandbox.RealmPort);
                Log.Message(LogType.NORMAL, "RedirectServer listening on {0} port {1}.", "127.0.0.1", Sandbox.RedirectPort);
                Log.Message(LogType.NORMAL, "WorldServer listening on {0} port {1}.", "127.0.0.1", Sandbox.WorldPort);
                Log.Message(LogType.NORMAL, "Started {0}", Sandbox.RealmName);
                Log.Message();

                ClientAuth.Password = ConfigurationManager.AppSettings["Password"];
                if (!string.IsNullOrEmpty(ClientAuth.Password))
                {
                    Log.Message(LogType.NORMAL, "Default client password set to \"{0}\"", ClientAuth.Password);
                    Log.Message();
                }

                HandlerDefinitions.InitializePacketHandler();
            }
            else
            {
                if (!WorldManager.WorldSession.Started)
                {
                    Log.Message(LogType.ERROR, "WorldServer couldn't be started.");
                }
                if (!RealmManager.RealmSession.Started)
                {
                    Log.Message(LogType.ERROR, "RealmServer couldn't be started.");
                }

                Log.Message();
            }

            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
Esempio n. 6
0
 /// <summary>
 /// Add handler for register plugins.
 /// </summary>
 public static void RegisterPluginHandler(string pluginType, PluginHandler handler, PluginRemover remover)
 {
     if (!Handlers.ContainsKey(pluginType))
     {
         Handlers.Add(pluginType, handler);
     }
     if (!Removers.ContainsKey(pluginType))
     {
         Removers.Add(pluginType, remover);
     }
 }
Esempio n. 7
0
        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            ShortcutsInfo.Text = InternalResources.ShortcutInfoEnterFullScreen;

            _clientFactory = new ClientFactory();
            _pluginHandler = new PluginHandler();

            ConnectAndRender();

            _dispatcherTimer.Tick    += DispatcherTimer_Tick;
            _dispatcherTimer.Interval = new TimeSpan(0, 0, Settings.Default.RefreshInterval);
            _dispatcherTimer.Start();
        }
Esempio n. 8
0
        /// <summary>
        /// Add a WoW Folder to the core.
        /// </summary>
        /// <param name="client"></param>
        /// <param name="locale"></param>
        /// <param name="fileLocation"></param>
        public void AddWoWFolder(String client, String locale, String fileLocation)
        {
            if (Config.ValidateClient(client) && Config.ValidateLocale(locale) && fileLocation != "")
            {
                Vector3 <String> vector = new Vector3 <String>();
                vector.Create(client, locale, fileLocation);
                Config.wowDirectories.Add(vector);

                String        name    = client.Replace('.', '-');
                PluginHandler handler = new PluginHandler(_masterForm);
                handler.WriteNewPlugin(name, PluginType.WoWFolder, vector);
            }
        }
Esempio n. 9
0
 /// <summary>
 /// Deregisters an API plugin handler instance via handler reference
 /// </summary>
 /// <param name="handler">The plugin handler for the plugin</param>
 private void Deregister(PluginHandler handler)
 {
     PluginLogger.print("Removing registered plugin " + handler.instance.ToString());
     // Remove the handler caches
     lock (_dataLock)
     {
         foreach (var api in handler.known_handlers)
         {
             handlers.Remove(api);
         }
         registeredPlugins.Remove(handler);
     }
 }
Esempio n. 10
0
        static void Main(string[] args)
        {
            _computer = new Computer();
            _pluginHandler = new PluginHandler(_computer);

            AdvConsole.Log("Opening SettingsForm");
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            SettingsForm settingsForm = new SettingsForm(_pluginHandler);
            settingsForm.setupComplete += setupComplete;
            Application.Run(settingsForm);
            AdvConsole.ReadLine();
        }
Esempio n. 11
0
        /// <summary>
        /// 注册处理事件
        /// </summary>
        /// <param name="plugin"></param>
        /// <param name="reqHandler"></param>
        /// <param name="postReqHandler"></param>
        /// <returns></returns>
        public bool Register(IPlugin plugin, PluginHandler <TContext> getHandler, PluginHandler <TContext> postHandler)
        {
            Type type = plugin.GetType();
            PluginPackAttribute attr = PluginUtil.GetAttribute(plugin);
            string indent            = attr.WorkIndent;

            if (postHandler == null || postHandlers.Keys.Contains(indent))
            {
                return(false);
            }
            postHandlers.Add(indent, postHandler);

            return(base.Register(plugin, getHandler));
        }
Esempio n. 12
0
        /// <summary>
        /// Called when the application is loaded
        /// </summary>
        /// <param name="sender">Not used.</param>
        /// <param name="e">Not used.</param>
        private void Master_Load(object sender, EventArgs e)
        {
            ConfigController controller = new ConfigController(this);

            controller.LoadAllValues();

            PluginHandler scanner = new PluginHandler(this);

            scanner.ScanPlugins();
            scanner.ScanDirectories();

            controller.ValidateWoWLocation();
            UpdateRealmSelectionToDefault();
        }
Esempio n. 13
0
        private static void Main(string[] args)
        {
            //fixes wrong screensize for screen share
            if (Environment.OSVersion.Version.Major >= 6)
            {
                SetProcessDPIAware();
            }

            if (!Directory.Exists(AppEnvironment.DataPath))
            {
                Directory.CreateDirectory(AppEnvironment.DataPath);
            }

            if (!Debugger.IsAttached)
            {
                ExceptionHandler.AddGlobalHandlers();
            }


            Console.WriteLine("Exception Handlers attached");


            Settings.Initialize("Config.json");

            Console.Title = Resources.Program_Title;
            Tools.ConfigureServer();
            var useTerminal  = Convert.ToBoolean(Settings.Get("Terminal").AllowTerminal);
            var usePlugins   = Convert.ToBoolean(Settings.Get("Plugins").LoadPlugins);
            var useWebServer = Convert.ToBoolean(Settings.Get("WebServer").UseWebServer);

            WebCamManager.LoadWebcams();
            if (usePlugins)
            {
                PluginHandler.LoadPlugins();
            }
            if (useWebServer)
            {
                HttpServer.Setup();
            }
            var systemUtilities = new SystemUtilities();

            systemUtilities.Start();
            //Keep down here if you actually want a functional program
            TaskManagerServer.Start();
            if (useTerminal)
            {
                TerminalManagerServer.Start();
            }
            Console.ReadLine();
        }
Esempio n. 14
0
        public void StartPlugin()
        {
            if (PluginHandler.GetTotalPlugins() <= 0)
            {
                var pluginError = new
                {
                    noPluginsLoaded = true
                };
                _builder.WriteMessage(pluginError);
                return;
            }
            //GUID should always be the first argument
            var guid = _packet.Args?.First().ToString();

            if (guid == null)
            {
                var pluginError = new
                {
                    missingGuid = true
                };
                _builder.WriteMessage(pluginError);
                return;
            }
            object returnData    = null;
            var    pluginStarted = false;

            //lets check if we have any other arguments to clean the list
            if (_packet.Args.Count > 1)
            {
                var cleanedArgs = _packet.Args;
                //remove guid from the arguments.
                cleanedArgs.RemoveAt(0);
                returnData    = PluginHandler.StartPlugin(_client.Client, guid, cleanedArgs);
                pluginStarted = true;
            }
            else
            {
                returnData    = PluginHandler.StartPlugin(_client.Client, guid);
                pluginStarted = true;
            }
            var pluginResponse = new
            {
                guid,
                pluginData = returnData,
                pluginStarted
            };

            _builder.WriteMessage(pluginResponse);
        }
Esempio n. 15
0
        public void ListBadPlugins()
        {
            var badPlugins = (from plugin in PluginHandler.GetBadPluginsList()
                              select plugin.Split('|')
                              into pluginInfo
                              let pluginName = pluginInfo[0]
                                               let pluginError = pluginInfo[1]
                                                                 select new
            {
                pluginName,
                pluginError
            }).Cast <object>().ToList();

            _serializator.Serialize(_client, _packet.Endpoint, _packet.SyncKey, badPlugins);
        }
Esempio n. 16
0
        static void Main(string[] args)
        {
            PluginHandler<MyPluginTemplate> handler = new PluginHandler<MyPluginTemplate>(new MyPluginBridge());

            string path = Path.Combine(
                Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                @"..\..\..\PluginExample_Plugin\bin\Debug\PluginExample_Plugin.dll");

            handler.AddPlugin(Assembly.LoadFile(path));

            for (int i = 0; i <= 100; i++)
                handler.Invoke("OnNumber", i);

            Console.ReadKey();
        }
Esempio n. 17
0
        /// <summary>
        /// Registers a plugin API with Telemachus
        /// </summary>
        /// <param name="toRegister">An instance of a Plugin object, that conforms to the TelemachusPlugin interface.
        /// NOTE: Does NOT have to be a physical instance of the interface.</param>
        /// <returns>An Action, calling of which Deregisters the plugin. This is disposeable.</returns>
        public void Register(object toRegister)
        {
            var pluginType = toRegister.GetType();

            // Must conform at least to the minimal interface
            if (!typeof(IMinimalTelemachusPlugin).IsAssignableFrom(pluginType) && !pluginType.DoesMatchInterfaceOf(typeof(IMinimalTelemachusPlugin)))
            {
                throw new ArgumentException("Object " + toRegister.GetType().ToString() + " does not conform to the minimal interface");
            }

            var handler = new PluginHandler()
            {
                instance = toRegister
            };
            // Get a list of commands that this instance handles
            var commands = ReadCommandList(toRegister);
            // Get the plugin handler function
            var apiMethod = toRegister.GetType().GetMethod("GetAPIHandler", new Type[] { typeof(string) });

            handler.apiHandler = (APIHandler)Delegate.CreateDelegate(typeof(APIHandler), toRegister, apiMethod);

            // Does it match the Deregistration? If so, pass it the deregistration method
            if (toRegister is IDeregisterableTelemachusPlugin || pluginType.DoesMatchInterfaceOf(typeof(IDeregisterableTelemachusPlugin)))
            {
                Action deregistration = () => Deregister(handler);
                pluginType.GetProperty("Deregister").SetValue(toRegister, deregistration, null);
                handler.is_deregisterable = true;
            }

            var optional_interfaces = new List <string>();

            if (handler.is_deregisterable)
            {
                optional_interfaces.Add("Deregister");
            }
            PluginLogger.print("Got plugin registration call for " + toRegister.GetType() + ".\n  Optional interfaces enabled: " + (optional_interfaces.Count == 0 ? "None" : string.Join(", ", optional_interfaces.ToArray())));

            // Make a simple hashset of basic commands
            handler.commands = new HashSet <string>(commands.Where(x => !x.Contains("*")));
            // Now, deal with any wildcard plugin strings by building a regex
            handler.regexCommands = commands
                                    .Where(x => x.Contains("*"))
                                    .Select(x => new Regex("^" + x.Replace(".", "\\.").Replace("*", ".*") + "$")).ToList();

            lock (_dataLock)
                registeredPlugins.Add(handler);
        }
Esempio n. 18
0
        private static PluginHandler[] DiscoverPlugins(DirectoryInfo[] probingDirectories)
        {
            // Initialize a list that will contain all plugin types discovered
            List <PluginHandler> pluginHandlers = new List <PluginHandler>();

            if (probingDirectories != null)
            {
                // Iterate over the probing directories and look for plugins
                foreach (DirectoryInfo directory in probingDirectories)
                {
                    if (directory.Exists)
                    {
                        // Try to load plugins from each dll
                        foreach (FileInfo file in directory.GetFiles("*.dll"))
                        {
                            try
                            {
                                // Load the dll into an assembly
                                Assembly assembly = Assembly.Load(file.FullName);

                                // Iterate over all types contained in the assembly
                                foreach (Type type in assembly.GetTypes())
                                {
                                    // Only consider public, concrete types that implement IPlugin
                                    if (type.IsPublic && !type.IsAbstract && typeof(IPlugin).IsAssignableFrom(type))
                                    {
                                        PluginHandler pluginHandler = PluginHandler.FromType(type);
                                        if (pluginHandler != null)
                                        {
                                            pluginHandlers.Add(pluginHandler);
                                        }
                                    }
                                }
                            }
                            catch (Exception exception)
                            {
                                // TODO: Properly report error
                                //Utilities.DefaultTraceSource.TraceEvent(TraceEventType.Error, 0, "A failure occurred while trying to load the {0} Plugin: {1}{2}", file.FullName, Environment.NewLine, exception.ToString());
                            }
                        }
                    }
                }
            }

            // Return the list of plugin types discovered
            return(pluginHandlers.ToArray());
        }
Esempio n. 19
0
        static void Main(string[] args)
        {
            PluginHandler <MyPluginTemplate> handler = new PluginHandler <MyPluginTemplate>(new MyPluginBridge());

            string path = Path.Combine(
                Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                @"..\..\..\PluginExample_Plugin\bin\Debug\PluginExample_Plugin.dll");

            handler.AddPlugin(Assembly.LoadFile(path));

            for (int i = 0; i <= 100; i++)
            {
                handler.Invoke("OnNumber", i);
            }

            Console.ReadKey();
        }
Esempio n. 20
0
        /// <summary>
        /// Defines script type members - helpers and constructors.
        /// </summary>
        private MethodBuilder /*!*/ DefineMainHelper(TypeBuilder /*!*/ builder)
        {
            // public static object <Main>(ScriptContext context,IDictionary variables, DObject self, DTypeDesc includer, bool request);
            MethodBuilder result = builder.DefineMethod(
                MainHelperName,
                MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.SpecialName,
                typeof(object),
                MainHelperArgTypes);

            // gives arguments names (for comfortable debugging):
            result.DefineParameter(1, ParameterAttributes.None, PluginHandler.ConvertParameterName(PhpRoutine.ContextParamName));
            result.DefineParameter(2, ParameterAttributes.None, PluginHandler.ConvertParameterName(PhpRoutine.LocalVariablesTableName));
            result.DefineParameter(3, ParameterAttributes.None, PluginHandler.ConvertParameterName("<self>"));
            result.DefineParameter(4, ParameterAttributes.None, PluginHandler.ConvertParameterName("<includer>"));
            result.DefineParameter(5, ParameterAttributes.None, PluginHandler.ConvertParameterName("<request>"));

            return(result);
        }
Esempio n. 21
0
        /// <summary>
        /// 注册扩展处理程序
        /// </summary>
        /// <param name="extendName">扩展名称,而且也是访问地址的名称。如扩展名称为:ext,那么可使用/ext.sh访问该扩展插件</param>
        /// <param name="getReqHandler">委托PluginHandler<CmsContext,string>的实例</param>
        /// <param name="postReqHandler">委托PluginHandler<CmsContext,string>的实例</param>
        /// <returns></returns>
        public bool Register(IPlugin plugin,
                             PluginHandler <T> reqHandler)
        {
            Type type = plugin.GetType();
            PluginPackAttribute attr = PluginUtil.GetAttribute(plugin);
            string indent            = attr.WorkIndent;

            if (reqHandler == null || reqHandlers.Keys.Contains(indent))
            {
                return(false);
            }

            if (reqHandler != null)
            {
                reqHandlers.Add(indent, reqHandler);
            }

            return(true);
        }
Esempio n. 22
0
        /// <summary>This class is internal only to make tests work.
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        internal static int Main(string[] args)
        {
            if (args == null || args.Length == 0)
            {
                return((int)ReturnValues.NoInput);
            }

            var options = ParseArgs(args);

            var impl = new ProgramImpl(
                PluginHandler.Create(),
                new System.IO.Abstractions.FileSystem(),
                new AssemblyFactory(),
                Outputter.Create());;

            var res = impl.Execute(options);

            return((int)res);
        }
Esempio n. 23
0
        /// <summary>
        /// Define new instance of CallSite&lt;<paramref name="delegateType"/>&gt; and initialize it with specified binder.
        /// </summary>
        /// <param name="bodyEmitter"><see cref="ILEmitter"/> of the body that is using this call site. This method may emit initialization of the call site into this <paramref name="bodyEmitter"/>.</param>
        /// <param name="userFriendlyName">User friendly name used as name for the CallSite field.</param>
        /// <param name="delegateType">CallSite type argument.</param>
        /// <param name="binderInstanceEmitter">Function used to emit initialization of the binder from within the call sites container .cctor.</param>
        /// <returns>The <see cref="FieldInfo"/> containing the instance of the created CallSite.</returns>
        public FieldInfo /*!*/ DefineCallSite(ILEmitter /*!*/ bodyEmitter, string /*!*/ userFriendlyName, Type /*!*/ delegateType, Action <ILEmitter> /*!*/ binderInstanceEmitter)
        {
            Debug.Assert(userFriendlyName != null && delegateType != null && binderInstanceEmitter != null);

            userFriendlyName += ("'" + (callSitesCount++));

            // call sites container
            var type = EnsureContainer();

            // call site type
            var callSiteType = Types.CallSiteGeneric[0].MakeGenericType(delegateType);

            // define the field:
            // public static readonly CallSite<delegateType> <userFriendlyName>
            var attrs = FieldAttributes.Static | FieldAttributes.InitOnly | ((staticCtorEmitter == null) ? FieldAttributes.Private : FieldAttributes.Public);
            var field = type.DefineField(PluginHandler.ConvertCallSiteName(userFriendlyName), callSiteType, attrs);

            if (staticCtorEmitter == null) // => this.classContext != null
            {
                // emit initialization of the call site just in the body of current method (as it is in C#, we need current generic arguments):
                Debug.Assert(this.classContext != null);

                // check if the call site if not null, otherwise initialize it first:

                // if (<field> == null) <InitializeCallSite>;
                Label ifend = bodyEmitter.DefineLabel();
                bodyEmitter.Emit(OpCodes.Ldsfld, field);
                bodyEmitter.Emit(OpCodes.Brtrue, ifend);

                // init the field:
                InitializeCallSite(bodyEmitter, callSiteType, field, binderInstanceEmitter);

                bodyEmitter.MarkLabel(ifend);
            }
            else
            {
                // init the field in .cctor:
                InitializeCallSite(staticCtorEmitter, callSiteType, field, binderInstanceEmitter);
            }

            //
            return(field);
        }
Esempio n. 24
0
        public void ShouldLoadAndExecute()
        {
            var sourceCode = @"
using LehmanLaidun.Plugin;
using System.Xml.Linq;

namespace MyPlugin
{
    public class Command : ICommand
    {
        public string Name => ""My plugin"";

        public string Description => ""A plugin for testing"";

        public ParseResult Parse(string pathfile)
        {
            return ParseResult.Create(
                Name,
                XDocument.Parse($""<data plugin=\""{Name}\"">{pathfile}</data>"")
            );
        }
    }
}
";
            var assembly   = CreateAssembly(sourceCode);
            var sut        = PluginHandler.Create();

            //  Act.
            sut.Load(new[] { assembly });
            var res = sut.Execute("x");

            //  Assert.
            res
            .Select(pr => new { pr.Name, Result = pr.Result.ToString() })
            .Should()
            .BeEquivalentTo(
                new[] {
                new { Name = "My plugin", Result = "<data plugin=\"My plugin\">x</data>" },
            }
                );
        }
Esempio n. 25
0
        public void AddToRealmOptions(String name, String realmlist, String clientversion)
        {
            Vector3 <String> info = new Vector3 <string>();

            info.Create(name, realmlist, clientversion);

            Config.realmOptions.Add(info);

            ListViewItem item = new ListViewItem(name);

            item.Name = name;
            chosenRealm.Items.Add(item);
            chosenRealm.Items[name].Selected = true;

            PluginHandler handler = new PluginHandler(this);

            if (!handler.WriteNewPlugin(name, PluginType.Plugin, info))
            {
                throw new NotImplementedException();
            }
        }
        private void frmMain_Load(object sender, EventArgs e)
        {
            PluginHandler.LoadPlugins();

            ToolHandler.LoadTools();

            //put this after loadplugins to avoid "where's reflector" dialog
            HostHandler.SetupAssemblyResolver();

            #region About & Update
            try
            {
                ShowAbout(false);
                CheckUpdate();
            }
            catch (Exception ex)
            {
                SimpleMessage.ShowException(ex);
            }
            #endregion About & Update
        }
Esempio n. 27
0
        /// <summary>
        /// Ensure the call sites container is created and return the <see cref="TypeBuilder"/>.
        /// </summary>
        /// <returns></returns>
        private TypeBuilder /*!*/ EnsureContainer()
        {
            if (containerClass == null)
            {
                if (this.classContext != null && this.classContext.IsGeneric)
                {
                    // we will emit single call sites in the class context. It is easier than to build generic sites container.
                    Debug.Assert(this.classContext.RealTypeBuilder != null);
                    return(this.classContext.RealTypeBuilder);
                }

                Debug.Assert(staticCtorEmitter == null);

                var containerClassName = string.Format("<{0}>o_Sitescontainer'{1}", this.userFriendlyName.Replace('.', '_'), System.Threading.Interlocked.Increment(ref nextContainerId));
                containerClass = moduleBuilder.DefineType(PluginHandler.ConvertCallSiteName(containerClassName), TypeAttributes.Sealed | TypeAttributes.Class | TypeAttributes.NotPublic | TypeAttributes.Abstract);

                staticCtorEmitter = new ILEmitter(containerClass.DefineTypeInitializer());
            }

            return(containerClass);
        }
Esempio n. 28
0
        public void CanReturnFileInRoot()
        {
            var rootName = Logic.ElementNameRoot;
            var files    = new[]
            {
                new { pathfile = Path.Combine(Root, "whatever.jpg"), length = 4, lastAccessTime = DateTime.Parse("2010-01-05 11:22:33Z") }
            };

            var mockedFileSystem = new MockFileSystem(
                files.ToDictionary(pf => pf.pathfile, pf => CreateMockFileData(pf.length, pf.lastAccessTime)),
                Root
                );

            var pluginHandler = PluginHandler.Create();

            var sut = LogicFactory.CreateForPath(mockedFileSystem, Root, pluginHandler);

            //  #   Act.
            var res = sut.AsXDocument();

            //  #   Assert.
            res.Should().BeEquivalentTo(
                XDocument.Parse(@$ "
<root path='{Root}'>
Esempio n. 29
0
        public void CanLoadAndExecute()
        {
            var assemblyFactory = new AssemblyFactory();
            var plugins         = new[] {
                new { Name = "PluginOne", Framework = "netstandard2.0" },
                new{ Name = "PluginTwo", Framework = "net6.0" },
            };
            var pluginPathFiles = plugins.Select(plugin =>
                                                 pathWrapper.Combine(
                                                     PathToPlugins(),
                                                     plugin.Name,
                                                     "bin",
                                                     "Debug",
                                                     plugin.Framework,
                                                     plugin.Name + ".dll")
                                                 );

            var assemblies = pluginPathFiles.Select(pluginPathFile => assemblyFactory.LoadFile(pluginPathFile));

            var sut = PluginHandler.Create();

            //  Act.
            sut.Load(assemblies);
            var res = sut.Execute("a");

            //  Assert.
            res
            .Select(pr => new { pr.Name, Result = pr.Result.ToString() })
            .Should()
            .BeEquivalentTo(
                new[] {
                new { Name = "Plugin one", Result = "<data plugin=\"Plugin one\">a</data>" },
                new { Name = "Plugin two", Result = "<data plugin=\"Plugin two\">a</data>" },
            }
                );
        }
Esempio n. 30
0
    public static void Launch()
    {
        FilePaths.Setup();
        Console.WriteLine(FilePaths.ConfigFile);
        var cfg         = new Config <ConfigFile>(FilePaths.ConfigFile);
        var Filecontent = cfg.Read();

        if (Filecontent == null)
        {
            return;
        }

        foreach (var group in Filecontent.ChannelGroups)
        {
            if (group.Async)
            {
                PluginHandler.Async(group); // Starts thread for all group channels
            }
            else
            {
                _ = PluginHandler.Sync(group); // Creates 1 thread for all group channels
            }
        }
    }
        /// <summary>
        /// Registers a plugin API with Telemachus
        /// </summary>
        /// <param name="toRegister">An instance of a Plugin object, that conforms to the TelemachusPlugin interface. 
        /// NOTE: Does NOT have to be a physical instance of the interface.</param>
        /// <returns>An Action, calling of which Deregisters the plugin. This is disposeable.</returns>
        public void Register(object toRegister)
        {
            var pluginType = toRegister.GetType();
            // Must conform at least to the minimal interface
            if (!typeof(IMinimalTelemachusPlugin).IsAssignableFrom(pluginType) && !pluginType.DoesMatchInterfaceOf(typeof(IMinimalTelemachusPlugin)))
            {
                throw new ArgumentException("Object " + toRegister.GetType().ToString() + " does not conform to the minimal interface");
            }

            var handler = new PluginHandler() { instance = toRegister };
            // Get a list of commands that this instance handles
            var commands = ReadCommandList(toRegister);
            // Get the plugin handler function
            var apiMethod = toRegister.GetType().GetMethod("GetAPIHandler", new Type[] { typeof(string) });
            handler.apiHandler = (APIHandler)Delegate.CreateDelegate(typeof(APIHandler), toRegister, apiMethod);

            // Does it match the Deregistration? If so, pass it the deregistration method
            if (toRegister is IDeregisterableTelemachusPlugin || pluginType.DoesMatchInterfaceOf(typeof(IDeregisterableTelemachusPlugin)))
            {
                Action deregistration = () => Deregister(handler);
                pluginType.GetProperty("Deregister").SetValue(toRegister, deregistration, null);
                handler.is_deregisterable = true;
            }

            var optional_interfaces = new List<string>();
            if (handler.is_deregisterable) optional_interfaces.Add("Deregister");
            PluginLogger.print("Got plugin registration call for " + toRegister.GetType() + ".\n  Optional interfaces enabled: " + (optional_interfaces.Count == 0 ? "None" : string.Join(", ", optional_interfaces.ToArray())));

            // Make a simple hashset of basic commands
            handler.commands = new HashSet<string>(commands.Where(x => !x.Contains("*")));
            // Now, deal with any wildcard plugin strings by building a regex
            handler.regexCommands = commands
                .Where(x => x.Contains("*"))
                .Select(x => new Regex("^" + x.Replace(".", "\\.").Replace("*", ".*") + "$")).ToList();

            lock(_dataLock)
                registeredPlugins.Add(handler);
        }
Esempio n. 32
0
 /// <summary>
 /// 迭代插件
 /// </summary>
 /// <param name="handler"></param>
 public static void Iterate(PluginHandler handler)
 {
     foreach (IPlugin p in BasePluginHost.plugins.Keys)
     {
         handler(p, BasePluginHost.plugins[p]);
     }
 }
Esempio n. 33
0
        /// <summary>
        /// 安装/升级插件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="handler"></param>
        /// <returns></returns>
        public static bool InstallPlugin(string url, PluginHandler<PluginPackAttribute> handler)
        {
            var installResult = false;
            string appDirectory = AppDomain.CurrentDomain.BaseDirectory;
            var pluginPath = String.Concat(
                appDirectory,
                PluginConfig.PLUGIN_DIRECTORY);

            var tempDir = String.Concat(appDirectory, PluginConfig.PLUGIN_TMP_DIRECTORY, "plugin/");
            var fileName = tempDir + "dl_pack_" + String.Empty.RandomLetters(16) + ".zip";

            if (Directory.Exists(tempDir))
            {
                Directory.Delete(tempDir, true);
            }
            Directory.CreateDirectory(tempDir).Create();

            var dir = new DirectoryInfo(tempDir);

            var data = HttpClient.DownloadFile(url, null);
            using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
            {
                fs.Write(data, 0, data.Length);
                fs.Flush();
                fs.Dispose();
            }

            IList<PluginPackAttribute> pluginAttrs = new List<PluginPackAttribute>(GetPluginPackInfo(fileName));

            if (pluginAttrs.Count != 0)
            {
                ZipUtility.UncompressFile(pluginPath, fileName, false);

                string[] multExt = PluginConfig.GetFilePartterns();
                foreach (String ext in multExt)
                {
                    foreach (FileInfo file in dir.GetFiles(ext))
                    {
                        File.Delete(pluginPath + file.Name);
                        file.MoveTo(pluginPath + file.Name);
                    }
                }

                if (handler != null)
                {
                    var result = false;
                    foreach (PluginPackAttribute attr in pluginAttrs)
                    {
                        handler(attr, ref result);
                    }
                }

                installResult = true;
            }

            Directory.Delete(tempDir, true);

            return installResult;
        }
 /// <summary>
 /// Deregisters an API plugin handler instance via handler reference
 /// </summary>
 /// <param name="handler">The plugin handler for the plugin</param>
 private void Deregister(PluginHandler handler)
 {
     PluginLogger.print("Removing registered plugin " + handler.instance.ToString());
     // Remove the handler caches
     lock(_dataLock)
     {
         foreach (var api in handler.known_handlers)
         {
             handlers.Remove(api);
         }
         registeredPlugins.Remove(handler);
     }
 }
Esempio n. 35
0
 public AlienInnocents(PluginHandler plugin)
 {
     this.plugin = plugin;
 }
Esempio n. 36
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SettingsForm"/> class
 /// </summary>
 /// <param name="pluginHandler">The plugin handler</param>
 public SettingsForm(PluginHandler pluginHandler)
 {
     this.pluginHandler = pluginHandler;
     InitializeComponent();
 }
 /// <summary>
 /// 迭代插件
 /// </summary>
 /// <param name="handler"></param>
 public void Iterate(PluginHandler handler)
 {
     foreach (IPlugin p in plugins.Keys)
     {
         if (CanAdapter(p))
         {
             handler(p, plugins[p]);
         }
     }
 }
Esempio n. 38
0
        public MainWindow()
        {
            using (LoadBotForm lbf = new LoadBotForm())
            {
                if (lbf.ShowDialog() != DialogResult.OK)
                {
                    Environment.Exit(0);
                    return;
                }
                bot = new IRCBot(lbf.BotLogin);
            }
            InitializeComponent();

            DirectoryInfo PluginDirectory;

            try
            {
                PluginDirectory = new DirectoryInfo("Plugins");
                if (!PluginDirectory.Exists)
                {
                    PluginDirectory.Create();
                }
            }
            catch
            {
                MessageBox.Show("No access to \"Plugin\" Directory.");
                return;
            }
            foreach (FileInfo pluginFile in PluginDirectory.GetFiles("*.dll"))
            {
                try
                {
                    LoadedPlugin plugin = PluginHandler.LoadPlugin(pluginFile.FullName);
                    plugin.OnException += Plugin_OnException;
                    if (!PluginIDList.Add(plugin.PluginID))
                    {
                        throw new Exception("Duplicate id");
                    }

                    HandlerBundle handlers = new HandlerBundle();

                    handlers.Bot               = new BotHandler(plugin);
                    handlers.Bot.OnException  += OnException;
                    handlers.Bot.OnSayMessage += Bot_OnSayMessage;

                    handlers.UI           = new BotUIHandler(plugin);
                    handlers.UI.OnTabAdd += UI_OnTabAdd;

                    plugin.Initilze(handlers);


                    foreach (var command in plugin.Details.LoadedCommands)
                    {
                        var handler = new CommandHandler(plugin, command);
                        if (!HandlerList.ContainsKey(handler.ID))
                        {
                            HandlerList.Add(handler.ID, handler);
                        }
                    }


                    PluginDisplayControl display = new PluginDisplayControl(plugin);
                    display.Parent   = PluginDisplayPanel;
                    display.Width    = PluginDisplayPanel.Width;
                    display.Anchor   = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
                    display.Location = new Point(0, PluginList.Count * display.Height);
                    PluginDisplayPanel.Controls.Add(display);

                    PluginList.Add(plugin);
                }
                catch
                {
                    Debug.WriteLine("Error on file {0}", pluginFile.Name);
                }

                LoadSettings();
            }
        }