Esempio n. 1
0
 public void DisposePlugin()
 {
     try
     {
         if (_instanceFromOtherAssembly != null)
         {
             if (Products.Products.IsStarted && _instanceFromOtherAssembly is State)
             {
                 return;
             }
             _instanceFromOtherAssembly.Dispose();
         }
         if (_worker != null)
         {
             if (_worker.IsAlive)
             {
                 _worker.Abort();
             }
         }
         Thread.Sleep(1000);
     }
     catch (Exception exception)
     {
         Logging.WriteError("DisposePlugin(): " + exception);
     }
     finally
     {
         if (!Products.Products.IsStarted || !(_instanceFromOtherAssembly is State))
         {
             _instanceFromOtherAssembly = null;
             _assembly = null;
             _obj      = null;
         }
     }
 }
Esempio n. 2
0
        /// <summary>
        /// 插件任务执行完成相关操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="result"></param>
        private void OnPluginTaskCompleted(IPlugins sender, ExecuteResult result)
        {
            if (sender == null)
            {
                logger.Error(new Exception("ExecuteCompletedHandler 事件未指定正确的sender参数"));  //记录错误日志
                return;
            }
            ScheduleJobsInfo job = jobsService.FindOne(sender.JobID);

            OnPluginTaskCompleted(null, job, result.Successed, result.Message);
        }
Esempio n. 3
0
        public static IEnumerable <MetricAnalyzer> Load()
        {
            System.Reflection.AssemblyName an = new System.Reflection.AssemblyName("Plugins, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");

            foreach (Type t in System.Reflection.Assembly.Load(an).ExportedTypes)
            {
                Type     pluginType = t.GetTypeInfo().ImplementedInterfaces.SingleOrDefault(k => k == typeof(IPlugins));
                IPlugins result     = (IPlugins)Activator.CreateInstance(t);
                return(result.GetAnalyzers());
            }
            return(null);
        }
Esempio n. 4
0
        public void Execute(IJobExecutionContext context)
        {
            Guid             jobID = (Guid)context.JobDetail.JobDataMap["JOBS"];
            ScheduleJobsInfo job   = jobsService.FindOne(jobID);

            if (job == null)
            {
                return;
            }
            logger.Info("Execute:" + job.ScheduleId.ToString());
            SchedulePluginsInfo schedule = pluginService.FindOne(job.ScheduleId);
            string assembly = schedule == null ? "" : schedule.AssemblyInfo;

            if (string.IsNullOrEmpty(assembly))
            {
                return;
            }
            IPlugins plugin = LoadPlugins.Instance.CreateInstance(assembly);

            if (plugin == null)
            {
                logger.Warn("实例化插件:" + assembly + "失败");
                //如果插件不存在,//标记未读取,以便下一次插件加载后可以读取任务
                jobsService.UpdateStatus(jobID, JobStatus.WaitToRun);
                RemoveQuartzJob(context);
                return;
            }
            jobsService.UpdateStatus(jobID, JobStatus.Running);//标记任务正在执行

            try
            {
                if (job.Mode == JobMode.OnTimeEveryTime)
                {
                    plugin.Execute(job.Id, schedule.NotifyUrl, job.Mode, null, OnPluginTaskCompleted);//执行任务
                }
                else
                {
                    TaskExecuteState state = new TaskExecuteState();
                    plugin.Execute(job.Id, schedule.NotifyUrl, job.Mode, state, null);//执行任务
                    state.Wait();
                    OnPluginTaskCompleted(context, job, plugin.State.Successed, plugin.State.OperationException != null ? plugin.State.OperationException.Message : "");
                }
            }
            catch (Exception ex)
            {
                jobsService.UpdateStatus(jobID, JobStatus.Failed);
                logger.Error(ex);
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Starts the plugin.
        /// </summary>
        /// <param name="plugin">The plugin.</param>
        /// <returns>A Task.</returns>
        private async Task <bool> StartPlugin(IPlugins plugin)
        {
            //处理插件
            var result = false;

            try
            {
                result = await plugin.StartingAsync();
            }
            catch (Exception e)
            {
                Log.Error($"{plugin.Name}插件加载失败", e);
                await plugin.ExitAsync();

                result = false;
            }
            return(result);
        }
Esempio n. 6
0
 /// <summary>
 /// Removes the.
 /// </summary>
 /// <param name="plugin">The plugin.</param>
 /// <returns>A Task.</returns>
 public ValueTask Remove(IPlugins plugin)
 {
     pluginDic.TryRemove(plugin.Key, out var _);
     return(ValueTask.CompletedTask);
 }
Esempio n. 7
0
 /// <summary>
 /// Regists the.
 /// </summary>
 /// <param name="plugin">The plugin.</param>
 public void Regist(IPlugins plugin)
 {
     pluginDic.TryAdd(plugin.Key, plugin);
 }
Esempio n. 8
0
        public void LoadPlugin(bool settingOnly = false, bool resetSettings = false, bool onlyCheckVersion = false)
        {
            try
            {
                DisposePlugin();
                _instanceFromOtherAssembly = null;
                _assembly = null;
                _obj      = null;

                if (!IsDll)
                {
                    CodeDomProvider      cc         = new CSharpCodeProvider();
                    var                  cp         = new CompilerParameters();
                    IEnumerable <string> assemblies =
                        AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic && !a.CodeBase.Contains((Process.GetCurrentProcess().ProcessName + ".exe"))).Select(a => a.Location);
                    cp.ReferencedAssemblies.AddRange(assemblies.ToArray());
                    StreamReader    sr        = File.OpenText(PathToPluginFile);
                    string          toCompile = sr.ReadToEnd();
                    CompilerResults cr        = cc.CompileAssemblyFromSource(cp, toCompile);
                    if (cr.Errors.HasErrors)
                    {
                        String text = cr.Errors.Cast <CompilerError>().Aggregate("Compilator Error :\n",
                                                                                 (current, err) => current + (err + "\n"));
                        Logging.WriteError(text);
                        MessageBox.Show(text);
                        return;
                    }
                    _assembly = cr.CompiledAssembly;
                    _obj      = _assembly.CreateInstance("Main", true);
                    if (!(_obj is IPlugins) && !(_obj is State))
                    {
                        Logging.WriteError("The plugin doesn't implement neither IPlugins nor State or have a different namespace than \"Main\". Path: " + PathToPluginFile);
                        return;
                    }
                }
                else
                {
                    _assembly = Assembly.LoadFrom(PathToPluginFile);
                    _obj      = _assembly.CreateInstance("Main", false);
                    if (!(_obj is IPlugins) && !(_obj is State))
                    {
                        Logging.WriteError("The plugin doesn't implement neither IPlugins nor State or have a different namespace than \"Main\". Path: " + PathToPluginFile);
                        return;
                    }
                }
                if (_assembly == null)
                {
                    return;
                }
                if (_obj is IPlugins)
                {
                    _instanceFromOtherAssembly = _obj as IPlugins;
                    foreach (Plugin plugin in Plugins.ListLoadedPlugins)
                    {
                        if (plugin.Name == _instanceFromOtherAssembly.Name)
                        {
                            Logging.WriteError("A plugin with the same name is already started.");
                            return;
                        }
                    }
                    _threadName = "Plugin " + _instanceFromOtherAssembly.Name;
                    if (settingOnly && resetSettings)
                    {
                        _instanceFromOtherAssembly.ResetConfiguration();
                        return;
                    }
                    if (settingOnly)
                    {
                        _instanceFromOtherAssembly.ShowConfiguration();
                        return;
                    }
                    if (onlyCheckVersion && !(_instanceFromOtherAssembly is State))
                    {
                        _worker = new Thread(_instanceFromOtherAssembly.CheckFields)
                        {
                            IsBackground = true, Name = _threadName
                        };
                        _worker.Start();
                    }
                    if (onlyCheckVersion)
                    {
                        return;
                    }
                    if (_instanceFromOtherAssembly is State)
                    {
                        if (Products.Products.IsStarted)
                        {
                            return;
                        }
                        State _statePlugin = _instanceFromOtherAssembly as State;
                        if (_statePlugin.Priority <= 0 || _statePlugin.Priority > 199)
                        {
                            Logging.WriteError("The State plugin doesn't uses a valid priority, must be within 1 and 199. Path: " + PathToPluginFile);
                            return;
                        }
                        Plugins.ListLoadedStatePlugins.Add(_instanceFromOtherAssembly as State);
                    }
                    else
                    {
                        _worker = new Thread(_instanceFromOtherAssembly.Initialize)
                        {
                            IsBackground = true, Name = _threadName
                        };
                        _worker.Start();
                    }
                }
            }
            catch (Exception exception)
            {
                Logging.WriteError("LoadPlugin(bool settingOnly = false, bool resetSettings = false, bool onlyCheckVersion = false): " + exception);
            }
        }
Esempio n. 9
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PluginOption"/> class.
 /// </summary>
 /// <param name="plugins">The plugins.</param>
 /// <param name="configuration"></param>
 public PluginOption(IPlugins plugins, IConfiguration configuration)
 {
     this._plugin  = plugins;
     Configuration = configuration;
 }
Esempio n. 10
0
 public PluginElement([NotNull] XmlElement xmlElement, [NotNull] IPlugins parent,
                      [NotNull] IIdentifierValidator identifierValidator) : base(xmlElement, parent)
 {
     _plugins             = parent;
     _identifierValidator = identifierValidator;
 }
Esempio n. 11
0
        public ShellViewModel(CompositionContainer container)
        {
            // load visuals
            this.container = container;
            plugins = container.GetExportedValue<IPlugins>();
            popups = container.GetExportedValue<IPopups>();
            floating = container.GetExportedValueOrDefault<IFloating>();
            AppState.Container = this.container;
            AppState.FullScreenFloatingElementChanged += (e, s) => NotifyOfPropertyChange(() => FullScreen);
            
            // load module
            AppState.State = AppStates.Starting;

            //Load configuration
            AppState.Config.LoadOfflineConfig();
            AppState.Config.LoadLocalConfig();
            AppState.Config.UpdateValues();
            BackgroundWorker barInvoker = new BackgroundWorker();
            barInvoker.DoWork += delegate
            {
                Thread.Sleep(TimeSpan.FromSeconds(10));
                AppState.ViewDef.CheckOnlineBaseLayerProviders();
            };
            barInvoker.RunWorkerAsync();
            
            
            
            var b = container.GetExportedValues<IModule>();
            module = b.FirstOrDefault();
            if (module == null) return;

            AppState.Config.ApplicationName = module.Name;

            AppState.State = AppStates.AppInitializing;
            AppState.ViewDef.RememberLastPosition = AppState.Config.GetBool("Map.RememberLastPosition", true);

            AppState.MapStarted += (e, f) =>
            {
                AppState.StartFramework(true, true, true, true);

                AppState.ShareContracts.Add(new EmailShareContract());
                AppState.ShareContracts.Add(new QrShareContract());

                var g = AppState.AddDownload("Init", "StartPoint");

                // start framework
                AppState.State = AppStates.FrameworkStarting;
                AddMainMenuItems();

                // set map
                if (AppState.ViewDef.RememberLastPosition)
                {
                    var extent = (AppState.Config.Get("Map.Extent", "-186.09257071294,-101.374056570352,196.09257071294,204.374056570352"));
                    if (!string.IsNullOrEmpty(extent))
                        AppState.ViewDef.MapControl.Extent = (Envelope)new EnvelopeConverter().ConvertFromString(extent);
                }

                // start app
                AppState.State = AppStates.AppStarting;

                // init plugins


                module.StartApp();

                // app ready
                AppState.State = AppStates.AppStarted;
                AppState.Imb.UpdateStatus();
                AppState.FinishDownload(g);

                // Show timeline player (EV: I've tried to turn it on earlier during the startup process, but that didn't work 
                // (most likely, because something wasn't loaded or initialized correctly).
                AppState.TimelineManager.PlayerVisible = AppState.Config.GetBool("Timeline.PlayerVisible", false);
            };
            
            module.InitializeApp();

        }
Esempio n. 12
0
 public static void Load(IPlugins plugins)
 {
     plugins.Add(new BundleFileImporter());
 }
 public GetPlugInsResult(IPlugins plugins)
 {
     PlugIns = plugins?.Required.ToYesNoString();
     AdditionalInformation = plugins?.AdditionalInformation;
 }
Esempio n. 14
0
        // ##########################################################################################################################################
        public void CheckPlugin()
        {
            // Navigate to Path (DLL-Files from Plugins)
            string path = Environment.CurrentDirectory + "\\Plugins\\";


            // For each DLL-File
            foreach (string plugin in System.IO.Directory.GetFiles(path, "*.dll"))
            {
                System.Reflection.Assembly myDllAssembly = System.Reflection.Assembly.LoadFile(plugin);

                //filter FILENAME without Extension
                string filename = Path.GetFileNameWithoutExtension(plugin);
                //Console.WriteLine(result);

                // Server.Temperatur
                // Server.Static
                Type type = myDllAssembly.GetType("Server." + filename);

                // Create Instance
                IPlugins staticInstance = null;
                try
                {
                    staticInstance = Activator.CreateInstance(type) as IPlugins;
                }
                catch (ArgumentNullException e)
                {
                    // Tritt auf, wenn eine dll-Datei kopiert wurde und unter einem anderen Namen abgespeichert ist
                    // Pluginname und Dateiname passen nicht zusammen
                    //Console.WriteLine("PluginManager: Es ist ein Fehler im folgenden Plugin aufgetreten: " + filename);
                    _logFile = new LogFile(e.ToString());
                }

                if (staticInstance == null)
                {
                    continue;
                }


                // Startseite anzeigen
                if (_name == "")
                {
                    _pluginExists = true;
                }
                else
                {
                    filename += ".html";

                    // If filename is the same as pluginName in URL --> Set true
                    if (filename == _name)
                    {
                        _pluginExists = true;

                        staticInstance.IsPlugin = true;
                        staticInstance.Writer   = _sw;

                        try
                        {
                            object[] param = { _parameter };

                            staticInstance.Init(_parameter);
                            staticInstance.Run();
                        }

                        catch (WrongParameterException e)
                        {
                            Console.WriteLine("Falscher Parameter: 404 Error");

                            // 404 ErrorPage
                            _response.ContentType = "text/html";
                            _response.Status      = false;
                            _response.SendMessage(_sw, "Bitte &uuml;berpr&uuml;fen Sie Ihre Paramter.");

                            /*
                             * if (e.InnerException != null)
                             * {
                             *  Console.WriteLine(e.InnerException.StackTrace);
                             * }
                             */

                            _logFile = new LogFile(e.ToString());
                        }

                        catch (WrongFilenameException e)
                        {
                            Console.WriteLine("Falscher Parameter: 404 Error");

                            // 404 ErrorPage
                            _response.ContentType = "text/html";
                            _response.Status      = false;
                            _response.SendMessage(_sw, "Bitte &uuml;berpr&uuml;fen Sie die URL von diesem Feed.");

                            /*
                             * if (e.InnerException != null)
                             * {
                             *  Console.WriteLine(e.InnerException.StackTrace);
                             * }
                             */

                            _logFile = new LogFile(e.ToString());
                        }

                        catch (Exception e)
                        {
                            //Console.WriteLine("ERROR: " + e);
                            _response.ContentType = "text/html";
                            _response.Status      = false;
                            _response.SendMessage(_sw, "Error PluginManager - " + e);

                            _logFile = new LogFile(e.ToString());
                        }
                    }
                }

                // Write true or false
                //Console.ForegroundColor = ConsoleColor.Yellow;
                //Console.WriteLine((bool)isPlugin.GetValue(StaticInstance, null));
                //Console.ForegroundColor = ConsoleColor.Green;
            }

            if ((_firstAccess == false) && (_pluginExists == false))
            {
                _response.ContentType = "text/html";
                _response.SendMessage(_sw, "Error PluginManager - Ihr ausgew&auml;hltes Plugin ist derzeit nicht verf&uuml;gbar. Bitte probieren Sie es sp&auml;ter erneut");
            }
        }
Esempio n. 15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ResolveProcess"/> class.
 /// </summary>
 /// <param name="plugin">The plugin.</param>
 /// <param name="pluginAssemblyCache">The plugin assembly cache.</param>
 public ResolveProcess(IPlugins plugin, PluginSerivceTypeCache pluginAssemblyCache)
 {
     this.plugins             = plugin;
     this.pluginAssemblyCache = pluginAssemblyCache;
 }
Esempio n. 16
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="plugin">The reference to the plugin</param>
 /// <param name="pluginPath">The path to the plugin</param>
 public LocalPlugins(IPlugins plugin, string pluginPath)
 {
     PluginPath = pluginPath;
     Plugin     = plugin;
     Hash       = Hashes.HashFromFile(PluginPath, Hashes.HashAlgorithm.Md5);
 }
Esempio n. 17
0
 /// <summary>
 /// Initialises a new instance of the <see cref="PluginOrExtensionsSectionAnswers"/> class.
 /// </summary>
 public PluginOrExtensionsSectionAnswers(IPlugins clientApplicationPlugins)
 {
     Required = clientApplicationPlugins?.Required.ToYesNoString();
     AdditionalInformation = clientApplicationPlugins?.AdditionalInformation;
 }
Esempio n. 18
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="plugin">The reference to the plugin</param>
 /// <param name="pluginPath">The path to the plugin</param>
 public LocalPlugins(IPlugins plugin, string pluginPath)
 {
     PluginPath = pluginPath;
     Plugin = plugin;
     Hash = Hashes.HashFromFile(PluginPath, Hashes.HashAlgorithm.Md5);
 }