private async Task Set(ServerMessagedEventArgs e) { if (e.Message.SplitArgs.Count < 2 || !e.Message.SplitArgs[1].Equals("set")) { return; } Status = PluginStatus.Processing; CommandEventArgs message = new CommandEventArgs(Commands.PRIVMSG, e.Message.Origin, string.Empty); if (e.Message.SplitArgs.Count < 5) { message.Contents = "Insufficient parameters. Type 'eve help lookup' to view correct usage."; await DoCallback(this, new ActionEventArgs(PluginActionType.SendMessage, message)); return; } if (e.Caller.GetUser(e.Message.Nickname) ?.Access > 0) { message.Contents = "Insufficient permissions."; } //e.Root.GetUser() Status = PluginStatus.Stopped; }
public override PluginStatus GetStatus() { var status = new PluginStatus { Status = StatusCode.OK, Color = System.Drawing.Color.ForestGreen, ShortMessage = "Ready", LongMessage = LogAndMessage.GetMessages() }; if (string.IsNullOrEmpty(status.LongMessage)) { status.LongMessage = status.ShortMessage; lastLongMessage = status.ShortMessage; } if (lastLongMessage != status.LongMessage) { lastLongMessage = status.LongMessage; lastLongMessageTime = (int)DateTime.Now.TimeOfDay.TotalMilliseconds; } status.Status = (StatusCode)((int)status.Status + lastLongMessageTime); return(status); }
public Plugin(FileInfo file, MainBot parent, int id) { mainBot = parent; this.file = file; Id = id; status = PluginStatus.Off; }
/// <summary> /// 创建插件对象。 /// </summary> /// <param name="pluginTree">依附的插件树对象。</param> /// <param name="name">插件名称,该名称必须在同级插件中唯一。</param> /// <param name="filePath">插件文件路径(完整路径)。</param> /// <param name="parent">所属的父插件。</param> /// <remarks>创建的插件对象,并没有被加入到<paramref name="parent"/>参数指定的父插件的子集中(<seealso cref="Zongsoft.Plugins.Plugin.Children"/>)。</remarks> internal Plugin(PluginTree pluginTree, string name, string filePath, Plugin parent) { if (pluginTree == null) { throw new ArgumentNullException("pluginTree"); } if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentNullException("name"); } if (string.IsNullOrWhiteSpace(filePath)) { throw new ArgumentNullException("filePath"); } _pluginTree = pluginTree; _name = name.Trim(); _filePath = filePath; _parent = parent; _status = PluginStatus.None; _manifest = new PluginManifest(this); _children = new PluginCollection(this); _builtins = new List <Builtin>(); _modules = new FixedElementCollection <IApplicationModule>(); _parsers = new FixedElementCollection <IParser>(); _builders = new BuilderElementCollection(); }
public void Unload() { try { if (status == PluginStatus.Active) { mainBot.CommandManager.UnregisterPlugin(this); } if (proxy != null) { proxy.Stop(); } if (domain != null) { AppDomain.Unload(domain); } } finally { proxy = null; domain = null; status = PluginStatus.Off; } }
public Plugin(PluginManager manager, Assembly assembly, Type type) { _manager = manager; _assembly = assembly; _pluginType = type; _status = PluginStatus.Declared; }
protected override void Initialize() { //Load the state of Settings saved to INI if there are any. LoadSettingsFromIni(); if (LogDebug) { Console.WriteLine("Registering feature pages"); } //Initialize feature pages HomeSeerSystem.RegisterFeaturePage(Id, "sample-guided-process.html", "Sample Guided Process"); HomeSeerSystem.RegisterFeaturePage(Id, "sample-blank.html", "Sample Blank Page"); HomeSeerSystem.RegisterFeaturePage(Id, "sample-trigger-feature.html", "Trigger Feature Page"); HomeSeerSystem.RegisterDeviceIncPage(Id, "add-sample-device.html", "Add Sample Device"); // If a speaker client is needed that handles sending speech to an audio device, initialize that here. // If you are supporting multiple speak devices such as multiple speakers, you would make this call // in your reoutine that initializes each speaker device. Create a new instance of the speaker client // for each speaker. We simply initalize one here as a sample implementation _speakerClient = new SpeakerClient(Name); // if the HS system has the setting "No password required for local subnet" enabled, the user/pass passed to Connect are ignored // if the connection is from the local subnet, else the user/pass passed here are must exist as a user in the system // You will need to allow the user to supply a user/pass in your plugin settings // This functions connects your speaker client to the system. Your client will then appear as a speaker client in the system // and can be selected as a target for speech and audio in event actions. // When the system speaks to your client, your SpeakText function is called in SpeakerClient class _speakerClient.Connect("default", "default"); Console.WriteLine("Initialized"); Status = PluginStatus.Ok(); }
public GenericResult TryToLoad() { string typename = _pluginType.FullName; if (!typeof(IPlugin).IsAssignableFrom(_pluginType)) { _manager.Tracer.Trace("PluginManager.Messages.IPluginIsNotImplemented", typename); return(GenericResult.Failed); } object[] attrs = _pluginType.GetCustomAttributes(typeof(PluginInfoAttribute), false); if (attrs.Length != 1) { _manager.Tracer.Trace("PluginManager.Messages.PluginInfoAttributeNotFound", typename); return(GenericResult.Failed); } _attribute = (PluginInfoAttribute)attrs[0]; string id = _attribute.ID; if (id == null || id.Length == 0) { _manager.Tracer.Trace("PluginManager.Messages.IDNotFound", typename); return(GenericResult.Failed); } _status = PluginStatus.Loaded; return(GenericResult.Succeeded); }
private PluginResponse PrepareSource() { var provider = CodeDomProvider.CreateProvider("CSharp"); var cp = GenerateCompilerParameter(); var result = provider.CompileAssemblyFromFile(cp, File.FullName); if (result.Errors.Count > 0) { bool containsErrors = false; var strb = new StringBuilder(); strb.AppendFormat("Plugin_{0} compiler notifications:\n", Id); foreach (CompilerError error in result.Errors) { containsErrors |= !error.IsWarning; strb.AppendFormat("{0} L{1}/C{2}: {3}\n", error.IsWarning ? "Warning" : "Error", error.Line, error.Column, error.ErrorText); } strb.Length -= 1; // remove last linebreak Log.Warn(strb.ToString()); if (containsErrors) { status = PluginStatus.Error; return(PluginResponse.CompileError); } } return(InitlializeAssembly(result.CompiledAssembly)); }
/// <summary> /// 创建插件对象。 /// </summary> /// <param name="pluginTree">依附的插件树对象。</param> /// <param name="name">插件名称,该名称必须在同级插件中唯一。</param> /// <param name="filePath">插件文件路径(完整路径)。</param> /// <param name="parent">所属的父插件。</param> /// <remarks>创建的插件对象,并没有被加入到<paramref name="parent"/>参数指定的父插件的子集中(<seealso cref="Zongsoft.Plugins.Plugin.Children"/>)。</remarks> internal Plugin(PluginTree pluginTree, string name, string filePath, Plugin parent) { if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentNullException("name"); } if (string.IsNullOrWhiteSpace(filePath)) { throw new ArgumentNullException("filePath"); } _pluginTree = pluginTree ?? throw new ArgumentNullException(nameof(pluginTree)); _name = name.Trim(); _filePath = filePath; _parent = parent; _isHidden = string.Equals(Path.GetFileName(filePath), ".plugin", StringComparison.OrdinalIgnoreCase); _status = PluginStatus.None; _manifest = new PluginManifest(this); _children = new PluginCollection(this); _builtins = new List <Builtin>(); _parsers = new FixedElementCollection <IParser>(); _builders = new BuilderElementCollection(); }
public PluginStatusInfo(int id, string name, PluginStatus status, PluginType type) { Id = id; Name = name; Status = status; Type = type; }
/// <summary> /// Stops the plugin and removes all its functionality available in the bot. /// Changes the status from <see cref="PluginStatus.Active"/> to <see cref="PluginStatus.Ready"/> when successful or <see cref="PluginStatus.Error"/> otherwise. /// </summary> /// <param name="bot">The bot instance where this plugin should be stopped. Can be null when not required.</param> public PluginResponse Stop(Bot bot) { switch (Type) { case PluginType.None: break; case PluginType.BotPlugin: if (bot is null) { foreach (var pluginObjs in botPluginList.Values) { DestroyPluginObjects(pluginObjs); } botPluginList.Clear(); } else { if (botPluginList.TryGetValue(bot, out var pluginObjs)) { botPluginList.Remove(bot); DestroyPluginObjects(pluginObjs); } } break; case PluginType.CorePlugin: if (corePlugin != null) { BotManager.IterateAll(b => { if (b.Injector.TryGet <CommandManager>(out var commandManager)) { commandManager.UnregisterCollection(corePlugin.Bag); } }); DestroyPluginObjects(corePlugin); corePlugin = null; } break; case PluginType.Factory: ResourceResolver.RemoveResolver(factoryObject); break; case PluginType.Commands: if (corePlugin != null) { DestroyPluginObjects(corePlugin); } break; default: throw Tools.UnhandledDefault(Type); } status = PluginStatus.Ready; return(PluginResponse.Ok); }
public static void UpdatePluginStatus(this PluginSettings pluginSettings, string systemName, bool installed, bool active) { var pluginStatus = pluginSettings.GetSitePlugins(); var ps = pluginStatus.FirstOrDefault(x => x.PluginSystemName == systemName); if (ps == null) { ps = new PluginStatus() { PluginSystemName = systemName }; pluginStatus.Add(ps); } ps.Installed = installed; var storeId = ApplicationEngine.CurrentStore.Id; ps.ActiveStoreIds = ps.ActiveStoreIds ?? new List <int>(); if (active) { if (!ps.ActiveStoreIds.Contains(storeId)) { ps.ActiveStoreIds.Add(storeId); } } else { ps.ActiveStoreIds.Remove(storeId); } pluginSettings.SetSitePlugins(pluginStatus, true); }
private async Task Eval(ServerMessagedEventArgs e) { Status = PluginStatus.Processing; CommandEventArgs message = new CommandEventArgs(Commands.PRIVMSG, e.Message.Origin, string.Empty); if (e.Message.SplitArgs.Count < 3) { message.Contents = "Not enough parameters."; } Status = PluginStatus.Running; if (string.IsNullOrEmpty(message.Contents)) { Status = PluginStatus.Running; string evalArgs = e.Message.SplitArgs.Count > 3 ? e.Message.SplitArgs[2] + e.Message.SplitArgs[3] : e.Message.SplitArgs[2]; try { message.Contents = calculator.Evaluate(evalArgs) .ToString(CultureInfo.CurrentCulture); } catch (Exception ex) { message.Contents = ex.Message; } } await DoCallback(this, new ActionEventArgs(PluginActionType.SendMessage, message)); Status = PluginStatus.Stopped; }
public PluginResponse Load() { try { if (PluginManager.IsIgnored(File)) { return(PluginResponse.Disabled); } var locStatus = CheckStatus(null); if (locStatus != PluginStatus.Off && Md5EqualsCache()) { return(locStatus == PluginStatus.Ready || locStatus == PluginStatus.Active ? PluginResponse.Ok : PluginResponse.UnknownError); } Unload(); PluginResponse result; switch (File.Extension) { case ".cs": #if NET46 result = PrepareSource(); #else result = PluginResponse.NotSupported; #endif break; case ".dll": case ".exe": result = PrepareBinary(); break; default: throw new InvalidProgramException(); } status = result == PluginResponse.Ok ? PluginStatus.Ready : PluginStatus.Error; return(result); } catch (BadImageFormatException bifex) { Log.Warn("Plugin \"{0}\" has an invalid format: {1} (Add a \"{0}.ignore\" file to ignore this file)", File.Name, bifex.InnerException?.Message ?? bifex.Message); status = PluginStatus.Error; return(PluginResponse.InvalidBinary); } catch (Exception ex) { Log.Warn("Plugin \"{0}\" failed to prepare: {1}", File.Name, ex.Message); status = PluginStatus.Error; return(PluginResponse.Crash); } }
private async Task Channels(ServerMessagedEventArgs e) { Status = PluginStatus.Running; await DoCallback(this, new ActionEventArgs(PluginActionType.SendMessage, new CommandEventArgs(Commands.PRIVMSG, e.Message.Origin, string.Join(", ", e.Caller.Server.Channels.Where(channel => channel.Name.StartsWith("#")) .Select(channel => channel.Name))))); Status = PluginStatus.Stopped; }
public Plugin(FileInfo file, int id) { corePlugin = null; File = file; Id = id; status = PluginStatus.Off; Type = PluginType.None; }
public void Call_Die() { _Status = PluginStatus.Stopped; DoCallback(new PluginEventArgs(PluginEventMessageType.Message, "Calling die, stopping process, sending UNLOAD... from: " + _pluginName)); PluginEventAction actionCommand = new PluginEventAction(); actionCommand.ActionToTake = PluginActionType.Unload; DoCallback(new PluginEventArgs(PluginEventMessageType.Action, null, actionCommand)); // make a generic "reboot / update service" event handler ?! }
private async Task Users(ServerMessagedEventArgs e) { Status = PluginStatus.Running; await DoCallback(this, new ActionEventArgs(PluginActionType.SendMessage, new CommandEventArgs(Commands.PRIVMSG, e.Message.Origin, string.Join(", ", e.Caller.GetAllUsers())))); Status = PluginStatus.Stopped; }
public void Call_Die() { _Status = PluginStatus.Stopped; DoCallback(new PluginEventArgs(PluginEventMessageType.Message, "Calling die, stopping process, sending UNLOAD... from: " + _pluginName)); PluginEventAction actionCommand = new PluginEventAction(); actionCommand.ActionToTake = PluginActionType.Unload; DoCallback(new PluginEventArgs(PluginEventMessageType.Action, null, actionCommand)); // telling controller it can no unload me.... }
/// <summary> /// Stops the plugin and removes all its functionality available in the bot. /// Changes the status from <see cref="PluginStatus.Active"/> to <see cref="PluginStatus.Ready"/> when successful or <see cref="PluginStatus.Error"/> otherwise. /// </summary> /// <param name="bot">The bot instance where this plugin should be stopped. Can be null when not required.</param> public PluginResponse Stop(Bot bot) { if (writeStatus) { PersistentEnabled = false; } switch (Type) { case PluginType.None: break; case PluginType.BotPlugin: if (bot is null) { foreach (var plugin in pluginObjectList.Values) { plugin.Dispose(); } pluginObjectList.Clear(); } else { if (pluginObjectList.TryGetValue(bot, out var plugin)) { SaveDisposePlugin(plugin); pluginObjectList.Remove(bot); } } if (pluginObjectList.Count == 0) { UnregisterCommands(); } break; case PluginType.CorePlugin: SaveDisposePlugin(pluginObject); UnregisterCommands(); pluginObject = null; break; case PluginType.Factory: FactoryManager.RemoveFactory(factoryObject); break; case PluginType.Commands: UnregisterCommands(); break; default: throw Util.UnhandledDefault(Type); } status = PluginStatus.Ready; return(PluginResponse.Ok); }
public Plugin(FileInfo file, int id, bool writeStatus) { pluginObject = null; this.writeStatus = writeStatus; File = file; Id = id; status = PluginStatus.Off; Type = PluginType.None; }
private bool ChangePluginState(LocalPlugin plugin, PluginStatus state) { if (plugin.Manifest.Status == state || string.IsNullOrEmpty(plugin.Path)) { // No need to save as the state hasn't changed. return(true); } plugin.Manifest.Status = state; return(SaveManifest(plugin.Manifest, plugin.Path)); }
public void Unload() { Stop(null); pluginType = null; if (CheckStatus(null) == PluginStatus.Ready) { status = PluginStatus.Off; } }
public Plugin(CoreInjector coreInjector, ResourceResolver resourceResolver, BotManager botManager, FileInfo file, int id) { this.coreInjector = coreInjector; this.resourceResolver = resourceResolver; this.botManager = botManager; corePlugin = null; File = file; Id = id; status = PluginStatus.Off; Type = PluginType.None; }
public void ProcessEnded() { _Status = PluginStatus.Running; if (_terminateRequestReceived) // plugin has been asked to notify on process so it can be terminated, therefore send "unload" message { if (counter != null) { counter.Stop(); } PluginEventAction actionCommand = new PluginEventAction(); actionCommand.ActionToTake = PluginActionType.Unload; } }
public PluginResponse Prepare() { try { if (file.Extension != ".cs" && file.Extension != ".dll" && file.Extension != ".exe") { return(PluginResponse.UnsupportedFile); } //todo test shadowcopying domain = AppDomain.CreateDomain( "Plugin_" + file.Name, AppDomain.CurrentDomain.Evidence, new AppDomainSetup { ApplicationBase = ts3File.Directory.FullName, PrivateBinPath = "Plugin/..;Plugin", PrivateBinPathProbe = "" }); domain.UnhandledException += (s, e) => Unload(); proxy = (PluginProxy)domain.CreateInstanceAndUnwrap( proxType.Assembly.FullName, proxType.FullName); PluginResponse result; if (file.Extension == ".cs") { result = PrepareSource(); } else if (file.Extension == ".dll" || file.Extension == ".exe") { result = proxy.LoadAssembly(domain, file); } else { throw new InvalidProgramException(); } if (result == PluginResponse.Ok) { status = PluginStatus.Ready; } return(result); } catch (Exception ex) { Log.Write(Log.Level.Warning, "Possible plugin failed to load: ", ex); return(PluginResponse.Crash); } }
private async Task Lookup(ServerMessagedEventArgs e) { Status = PluginStatus.Processing; if (e.Message.SplitArgs.Count < 2 || !e.Message.SplitArgs[1].Equals("lookup")) { return; } CommandEventArgs message = new CommandEventArgs(Commands.PRIVMSG, e.Message.Origin, string.Empty); if (e.Message.SplitArgs.Count < 3) { message.Contents = "Insufficient parameters. Type 'eve help lookup' to view correct usage."; await DoCallback(this, new ActionEventArgs(PluginActionType.SendMessage, message)); return; } Status = PluginStatus.Running; string query = string.Join(" ", e.Message.SplitArgs.Skip(1)); string response = await $"https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles={query}".HttpGet(); JToken pages = JObject.Parse(response)["query"]["pages"].Values() .First(); if (string.IsNullOrEmpty((string)pages["extract"])) { message.Contents = "Query failed to return results. Perhaps try a different term?"; await DoCallback(this, new ActionEventArgs(PluginActionType.SendMessage, message)); return; } string fullReplyStr = $"\x02{(string)pages["title"]}\x0F — {Regex.Replace((string)pages["extract"], @"\n\n?|\n", " ")}"; message.Target = e.Message.Nickname; foreach (string splitMessage in fullReplyStr.SplitByLength(400)) { message.Contents = splitMessage; await DoCallback(this, new ActionEventArgs(PluginActionType.SendMessage, message)); } Status = PluginStatus.Stopped; }
// OnTimer event, process start raised, sleep to simulate doing some work, then process end raised public void OnCounterElapsed(Object sender, EventArgs e) { _Status = PluginStatus.Processing; DoCallback(new PluginEventArgs(PluginEventMessageType.Message, "Counter elapsed from: " + _pluginName)); if (_terminateRequestReceived) { counter.Stop(); DoCallback(new PluginEventArgs(PluginEventMessageType.Message, "Acting on terminate signal: " + _pluginName)); _Status = PluginStatus.Stopped; Call_Die(); } else { _Status = PluginStatus.Running; // nb: in normal plugin, this gets set after all processes complete - may be after scrapes etc. } }
private async Task Part(ServerMessagedEventArgs e) { Status = PluginStatus.Processing; CommandEventArgs message = new CommandEventArgs(Commands.PRIVMSG, e.Message.Origin, string.Empty); if (e.Caller.GetUser(e.Message.Realname) ?.Access > 1) { message.Contents = "Insufficient permissions."; } else if (e.Message.SplitArgs.Count < 3) { message.Contents = "Insufficient parameters. Type 'eve help part' to view command's help index."; } else if (e.Message.SplitArgs.Count < 2 || !e.Message.SplitArgs[2].StartsWith("#")) { message.Contents = "Channel parameter must be a proper name (starts with '#')."; } else if (e.Message.SplitArgs.Count < 2 || e.Caller.Server.GetChannel(e.Message.SplitArgs[2]) == null) { message.Contents = "I'm not in that channel."; } Status = PluginStatus.Running; if (!string.IsNullOrEmpty(message.Contents)) { await DoCallback(this, new ActionEventArgs(PluginActionType.SendMessage, message)); return; } string channel = e.Message.SplitArgs[2].ToLower(); e.Caller.Server.RemoveChannel(channel); message.Contents = $"Successfully parted channel: {channel}"; await DoCallback(this, new ActionEventArgs(PluginActionType.SendMessage, message)); await DoCallback(this, new ActionEventArgs(PluginActionType.SendMessage, new CommandEventArgs(Commands.PART, string.Empty, $"{channel} Channel part invoked by: {e.Message.Nickname}"))); Status = PluginStatus.Stopped; }
// OnTimer event, process start raised, sleep to simulate doing some work, then process end raised public void OnCounterElapsed(Object sender, EventArgs e) { _Status = PluginStatus.Processing; DoCallback(new PluginEventArgs(PluginEventMessageType.Message, "Counter elapsed from: " + _pluginName)); if (_terminateRequestReceived) { DoCallback(new PluginEventArgs(PluginEventMessageType.Message, "Counter elapsed, terminate received, stopping process... from: " + _pluginName)); } // TEST FOR DIE... DoCallback(new PluginEventArgs(PluginEventMessageType.Message, "*** Sending UPDATE SERVICE WITH INSTALLER COMMAND ***")); PluginEventAction actionCommand = new PluginEventAction(); actionCommand.ActionToTake = PluginActionType.TerminateAndUnloadPlugins; // TEST !!!! ... this should ONLY be used to signal the HOST/CONTROLLER to flag a DIE.... DoCallback(new PluginEventArgs(PluginEventMessageType.Action, null, actionCommand)); DoCallback(new PluginEventArgs(PluginEventMessageType.Message, "*** Sending UPDATE SERVICE WITH INSTALLER COMMAND - COMPLETE ***")); Call_Die(); // end test }
public PluginStatusChangedEventArgs(Plugin plugin, PluginStatus status) { _plugin = plugin; _status = status; }
public void OnChannelMessage(object source, ChannelMessageEventArgs e) { Status = PluginStatus.Processing; Console.WriteLine(Program.Bot.Users.GetAll().First().Realname); PluginEventArgs responseEvent = new PluginEventArgs { MessageType = PluginEventMessageType.Message }; PluginReturnMessage response = new PluginReturnMessage(Protocols.PRIVMSG, e.Recipient, string.Empty); switch (e.SplitArgs[1]) { case "eval": if (e.SplitArgs.Count < 3) { response.Message = "Not enough parameters."; responseEvent.Result = response; DoCallback(responseEvent); Status = PluginStatus.Stopped; break; } Status = PluginStatus.Running; string evalArgs = e.SplitArgs.Count > 3 ? e.SplitArgs[2] + e.SplitArgs[3] : e.SplitArgs[2]; try { response.Message = new Calculator().Evaluate(evalArgs).ToString(CultureInfo.CurrentCulture); responseEvent.Result = response; DoCallback(responseEvent); } catch (Exception ex) { response.Message = ex.Message; responseEvent.Result = response; DoCallback(responseEvent); } break; case "join": if (Program.Bot.Users.LastSeen.Access > 1) response.Message = "Insufficient permissions."; else if (e.SplitArgs.Count < 3) response.Message = "Insufficient parameters. Type 'eve help join' to view command's help index."; else if (!e.SplitArgs[2].StartsWith("#")) response.Message = "Channel name must start with '#'."; else if (Program.Bot.Channels.Get(e.SplitArgs[2].ToLower()) != null) response.Message = "I'm already in that channel."; if (!string.IsNullOrEmpty(response.Message)) { responseEvent.Result = response; DoCallback(responseEvent); return; } response.Target = string.Empty; response.Message = e.SplitArgs[2]; response.Protocol = Protocols.JOIN; responseEvent.Result = response; DoCallback(responseEvent); break; } Status = PluginStatus.Stopped; }
public void Call_Die() { Status = PluginStatus.Stopped; DoCallback(new PluginEventArgs(PluginEventMessageType.Message, $"Calling die, stopping process, sending unload —— from: {Name}")); DoCallback(new PluginEventArgs(PluginEventMessageType.Action, null, new PluginEventAction { ActionToTake = PluginActionType.Unload })); }
public InvalidStatusToSetToPendingException(PluginStatus status) : base("Current status (" + status + ") does not allow a change to a pending status") { }
public void Unload() { try { if (status == PluginStatus.Active) mainBot.CommandManager.UnregisterPlugin(this); if (proxy != null) proxy.Stop(); if (domain != null) AppDomain.Unload(domain); } finally { proxy = null; domain = null; status = PluginStatus.Off; } }
public PluginResponse Prepare() { try { if (file.Extension != ".cs" && file.Extension != ".dll" && file.Extension != ".exe") return PluginResponse.UnsupportedFile; //todo test shadowcopying domain = AppDomain.CreateDomain( "Plugin_" + file.Name, AppDomain.CurrentDomain.Evidence, new AppDomainSetup { ApplicationBase = ts3File.Directory.FullName, PrivateBinPath = "Plugin/..;Plugin", PrivateBinPathProbe = "" }); domain.UnhandledException += (s, e) => Unload(); proxy = (PluginProxy)domain.CreateInstanceAndUnwrap( proxType.Assembly.FullName, proxType.FullName); PluginResponse result; if (file.Extension == ".cs") result = PrepareSource(); else if (file.Extension == ".dll" || file.Extension == ".exe") result = proxy.LoadAssembly(domain, file); else throw new InvalidProgramException(); if (result == PluginResponse.Ok) status = PluginStatus.Ready; return result; } catch (Exception ex) { Log.Write(Log.Level.Warning, "Possible plugin failed to load: ", ex); return PluginResponse.Crash; } }
public GenericResult Instantiate() { _instance = (IPlugin)_assembly.CreateInstance(_pluginType.FullName); _status = PluginStatus.Activated; return GenericResult.Succeeded; }
public GenericResult TryToLoad() { string typename = _pluginType.FullName; if (!typeof(IPlugin).IsAssignableFrom(_pluginType)) { _manager.Tracer.Trace("PluginManager.Messages.IPluginIsNotImplemented", typename); return GenericResult.Failed; } object[] attrs = _pluginType.GetCustomAttributes(typeof(PluginInfoAttribute), false); if (attrs.Length != 1) { _manager.Tracer.Trace("PluginManager.Messages.PluginInfoAttributeNotFound", typename); return GenericResult.Failed; } _attribute = (PluginInfoAttribute)attrs[0]; string id = _attribute.ID; if (id == null || id.Length == 0) { _manager.Tracer.Trace("PluginManager.Messages.IDNotFound", typename); return GenericResult.Failed; } _status = PluginStatus.Loaded; return GenericResult.Succeeded; }
public void Disable() { _status = PluginStatus.Disabled; }
public string RunProcess() { _Status = PluginStatus.Running; if (counter == null) { counter = new System.Timers.Timer(_timerInterval); } else { counter.Stop(); counter.Enabled = false; counter.Interval = _timerInterval; } counter.Elapsed += OnCounterElapsed; counter.Start(); return ""; }
private static bool Contains(PluginStatus inStatus, params PluginStatus[] statusFilter) { foreach (PluginStatus status in statusFilter) { if (inStatus == status) return true; } return false; }
public SOKOBAN_PLUGIN_RESULT SolveEx(uint mazeWidth, uint mazeHeight, string inputBoard) { SOKOBAN_PLUGIN_RESULT spr = SOKOBAN_PLUGIN_RESULT.FAILURE; // just default value; will be overwritten string methodName = "SolveEx"; if (this.libraryLoaded == true) { IntPtr pAddressOfFunctionToCall = NativeMethods.GetProcAddress(pDll, methodName); if (pAddressOfFunctionToCall != IntPtr.Zero) { // PLUGIN CONFIGURATION SolveExDel solveEx = (SolveExDel)Marshal.GetDelegateForFunctionPointer(pAddressOfFunctionToCall, typeof(SolveExDel)); alertStatusMessage(StatusPriority.Debug, "SolveEx started"); alertStatusMessage(StatusPriority.FunctionStatusChange, "Solver is being initialized."); StringBuilder board = new StringBuilder(inputBoard); solution = new StringBuilder(solutionBufferSize); psStatus = new PluginStatus(); this.pluginCallback = new PluginCallbackDel(this.PluginCallback); isSolverRunning = true; unsafe { int result = solveEx(mazeWidth, mazeHeight, board, solution, (uint)solutionBufferSize, ref psStatus, Marshal.GetFunctionPointerForDelegate(this.pluginCallback)); spr = (SOKOBAN_PLUGIN_RESULT)result; } isSolverRunning = false; if (spr == SOKOBAN_PLUGIN_RESULT.OK) { alertStatusMessage(StatusPriority.Debug, "Solution is: " + solution.ToString()); if (psStatus.uiPluginTimeMS > 0) { alertStatusMessage(StatusPriority.FunctionStatusChange, "Finished in: " + psStatus.uiPluginTimeMS.ToString()); } lastSolution = solution.ToString(); } else { alertStatusMessage(StatusPriority.Debug, "SolveEx ended with status: " + spr.ToString()); alertStatusMessage(StatusPriority.FunctionStatusChange, "Solver ended with status: " + spr.ToString()); } } else { alertStatusMessage(StatusPriority.Debug, "Resolving function '" + methodName + "' error: " + Marshal.GetLastWin32Error().ToString()); alertStatusMessage(StatusPriority.Debug, "Trying deprecated function 'Solve'"); alertStatusMessage(StatusPriority.FunctionStatusChange, "Solver uses old API. Progress of the plugin can't be tracked."); return Solve(mazeWidth, mazeHeight, inputBoard); } } else { throw new Exception(methodName + ": Solver library is not loaded."); } return spr; }