public override bool CheckFileCollisions(string buildTargetName)
 {
     bool flag = false;
     Dictionary<string, List<PluginInfo>> dictionary = new Dictionary<string, List<PluginInfo>>();
     foreach (PluginImporter importer in PluginImporter.GetImporters(BuildTarget.Android))
     {
         List<PluginInfo> list;
         PluginInfo item = new PluginInfo(buildTargetName, importer);
         if (dictionary.TryGetValue(item.assetName, out list))
         {
             foreach (PluginInfo info2 in list)
             {
                 if (item.ConflictsWith(info2))
                 {
                     Debug.LogError(string.Format("Found plugins with same names and architectures, {0} ({1}) and {2} ({3}). Assign different architectures or delete the duplicate.", new object[] { item.assetPath, item.cpuType, info2.assetPath, info2.cpuType }));
                     flag = true;
                 }
             }
         }
         else
         {
             dictionary[item.assetName] = list = new List<PluginInfo>();
         }
         list.Add(item);
     }
     return flag;
 }
        public void AddPlugin(string id, string name, Version version,
            Icon icon, string description, string disabledReason)
        {
            if (icon == null)
                icon = Resources.DefaultPluginIcon;

            Image smallIcon = new Icon(icon, new Size(16, 16)).ToBitmap();
            Image bigIcon = new Icon(icon, new Size(32, 32)).ToBitmap();

            var pluginInfo = new PluginInfo()
            {
                Id = id,
                Name = name,
                Version = version != null ? version.ToString() : "",
                SmallIcon = smallIcon,
                BigIcon = bigIcon,
                Description = description ?? name,
                DisabledReason = disabledReason
            };

            int rowIndex = pluginGrid.Rows.Add(pluginInfo.SmallIcon, pluginInfo.Name, pluginInfo.Version);
            DataGridViewRow row = pluginGrid.Rows[rowIndex];
            row.Tag = pluginInfo;

            if (disabledReason != null)
                row.DefaultCellStyle.ForeColor = Color.LightGray;
        }
Example #3
0
 public R4Toolkit()
 {
     pluginInfo = new PluginInfo();
     pluginInfo.Name = "L2Script Toolkit";
     pluginInfo.ShortName = "R4Toolkit";
     pluginInfo.Description = "A large selection of tools and extensions for L2Script.";
     pluginInfo.Author = "Peter Corcoran (R4000)";
 }
Example #4
0
 public RunnerDataHolder( PluginAssemblyInfo[] allAssemblies,
                         PluginInfo[] oldPlugins,
                         ServiceInfo[] notFoundServices )
 {
     _allAssemblies = allAssemblies;
     _oldPlugins = oldPlugins;
     _notFoundServices = notFoundServices;
 }
Example #5
0
 public Twitter()
 {
     info = new PluginInfo("Twitter",
         "Twitter",
         Assembly.GetExecutingAssembly().GetName().Version,
         true);
     configuration = new PluginConfiguration(0);
 }
Example #6
0
 /// <summary>
 /// Downloads plugin update info
 /// </summary>
 public static PluginUpdateInfo DownloadPluginUpdateInfo(PluginInfo plugin)
 {
     if (plugin != null)
     {
         PluginUpdateInfo info = (PluginUpdateInfo)Updaters.DownloadUpdateInfo(typeof(PluginUpdateInfo), plugin.UpdateInfoUrl);
         return info;
     }
     return null;
 }
        public void Uninstall(PluginInfo pluginInfo)
        {
            if (!pluginInfo.Installed)
                return;

            var pluginType = pluginInfo.LoadPluginInstance<IPlugin>();
            if (pluginType != null)
                pluginType.Uninstall();
        }
Example #8
0
 public Logger()
 {
     info = new PluginInfo(
         name: "Logger",
         displayName: "ログ出力",
         version: Assembly.GetExecutingAssembly().GetName().Version,
         hasSettingsDialog: true);
     configuration = new PluginConfiguration(10);
 }
        public PluginInfo AddPlugin(IPackage plugin)
        {
            if (plugin == null)
            {
                throw new ArgumentNullException("plugin");
            }

            try
            {
                var pluginInfo = new PluginInfo(plugin.Id, plugin.Version);

                string targetPath = GetTargetPath(pluginInfo);
                if (Directory.Exists(targetPath))
                {
                    UIServices.Value.Show(
                        "Adding plugin failed. There is already an existing plugin with the same Id and Version.",
                        MessageLevel.Error);
                }
                else
                {
                    Directory.CreateDirectory(targetPath);
                    if (Directory.Exists(targetPath))
                    {
                        // make sure there is no .delete file lurking around for this plugin
                        string deleteMePath = targetPath + DeleteMeExtension;
                        File.Delete(deleteMePath);

                        // copy assemblies
                        int numberOfFilesCopied = 
                            FrameworkFolderForAssemblies.Sum(folder => plugin.UnpackPackage(folder, targetPath));

                        if (numberOfFilesCopied == 0)
                        {
                            Directory.Delete(targetPath);
                            UIServices.Value.Show(
                                "Adding plugin failed. The selected package does not have any assembly inside the 'lib\\net40' folder.",
                                MessageLevel.Error);
                        }
                        else
                        {
                            bool succeeded = AddPluginToCatalog(pluginInfo, targetPath, quietMode: false);
                            if (!succeeded)
                            {
                                DeletePlugin(pluginInfo);
                            }
                            return succeeded ? pluginInfo : null;
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                UIServices.Value.Show(exception.Message, MessageLevel.Error);
            }

            return null;
        }
Example #10
0
		public override PluginInfo GetPluginInfo()
		{
			PluginInfo pluginInfo = new PluginInfo();
			pluginInfo.AuthorEmail = "*****@*****.**";
			pluginInfo.AuthorName = "Fernando Rozenblit";
            pluginInfo.Description = "Exports the Gump into a POL script. Based on Sphere Exporter by Francesco Furiani & Mark Chandler.";
			pluginInfo.PluginName = "POLGumpExporter";
			pluginInfo.Version = "1.1";
			return pluginInfo;
		}
Example #11
0
 public static void GetPluginInfo(ref PluginInfo pluginInfo)
 {
     pluginInfo.Name = "AmiBroker\x00ae data Plug-in";
     pluginInfo.Vendor = "KriaSoft LLC";
     pluginInfo.Type = PluginType.Data;
     pluginInfo.Version = 10000; // v1.0.0
     pluginInfo.IDCode = new PluginID("TEST");
     pluginInfo.Certificate = 0;
     pluginInfo.MinAmiVersion = 5600000; // v5.60
     pluginInfo.StructSize = Marshal.SizeOf((PluginInfo)pluginInfo);
 }
Example #12
0
        public void addPlugin(string name, Plugin plugin)
        {
            lock(this)
            {
                if(_communicator == null)
                {
                    throw new CommunicatorDestroyedException();
                }

                if(findPlugin(name) != null)
                {
                    AlreadyRegisteredException ex = new AlreadyRegisteredException();
                    ex.id = name;
                    ex.kindOfObject = _kindOfObject;
                    throw ex;
                }

                PluginInfo info = new PluginInfo();
                info.name = name;
                info.plugin = plugin;
                _plugins.Add(info);
            }
        }
Example #13
0
 public ViewResultBase Details()
 {
     if (!string.IsNullOrEmpty(Request["isTooltip"]))
     {
         Guid id;
         if (Guid.TryParse(Request["id"], out id))
         {
             var data = new PluginInfo(AcDomain, base.EntityType.GetData(id));
             return new PartialViewResult { ViewName = "Partials/Details", ViewData = new ViewDataDictionary(data) };
         }
         else
         {
             throw new ValidationException("非法的Guid标识" + Request["id"]);
         }
     }
     else if (!string.IsNullOrEmpty(Request["isInner"]))
     {
         return new PartialViewResult { ViewName = "Partials/Details" };
     }
     else
     {
         return this.View();
     }
 }
Example #14
0
        static void loadFile(string fileName) {
            // Attempts to load the file. On failure, it will call unload.
            // Loading part does not take out a lock. 
            // Lock is only done after loading is finished and dictionaries need updating.

            // We might get a load for a file that's no longer there. Just unload the old one.
            if (!File.Exists(fileName)) {
                unloadFile(fileName);
                return;
            }

            Type pmType;
            switch (Path.GetExtension(fileName).ToLowerInvariant()) {
                case ".dll":
                    pmType = typeof(AsmPluginManager);
                    break;
                case ".exe": // TODO these need to come from config
                case ".fsx":
                case ".vbx":
                case ".csx":
                case ".jsx":
                    pmType = typeof(ScriptPluginManager);
                    break;
                default:
                    pmType = null;
                    break;
            }
            if (pmType == null) return;

            // App domain setup
            var setup = new AppDomainSetup();
            if (File.Exists(fileName + ".config")) {
                setup.ConfigurationFile = fileName + ".config";
            }
            setup.ApplicationBase = Native.freeswitch.SWITCH_GLOBAL_dirs.mod_dir;
            setup.ShadowCopyDirectories = managedDir + ";";
            setup.LoaderOptimization = LoaderOptimization.MultiDomainHost; // TODO: would MultiDomain work better since FreeSWITCH.Managed isn't gac'd?
            setup.CachePath = shadowDir;
            setup.ShadowCopyFiles = "true";
            setup.PrivateBinPath = "managed";

            // Create domain and load PM inside
            System.Threading.Interlocked.Increment(ref appDomainCount);
            setup.ApplicationName = Path.GetFileName(fileName) + "_" + appDomainCount;
            var domain = AppDomain.CreateDomain(setup.ApplicationName, null, setup);
                
            PluginManager pm;
            try {
                pm = (PluginManager)domain.CreateInstanceAndUnwrap(pmType.Assembly.FullName, pmType.FullName, null);
                if (!pm.Load(fileName)) {
                    AppDomain.Unload(domain);
                    unloadFile(fileName);
                    return;
                }
            } catch (Exception ex) {
                // On an exception, we will unload the current file so an old copy doesnt stay active
                Log.WriteLine(LogLevel.Alert, "Exception loading {0}: {1}", fileName, ex.ToString());
                AppDomain.Unload(domain);
                unloadFile(fileName);
                return;
            }

            // Update dictionaries atomically
            lock (loaderLock) {
                unloadFile(fileName);

                var pi = new PluginInfo { FileName = fileName, Domain = domain, Manager = pm };
                pluginInfos.Add(pi);
                var newAppExecs = new Dictionary<string, AppPluginExecutor>(appExecs, StringComparer.OrdinalIgnoreCase);
                var newApiExecs = new Dictionary<string, ApiPluginExecutor>(apiExecs, StringComparer.OrdinalIgnoreCase);
                pm.AppExecutors.ForEach(x => x.Aliases.ForEach(y => newAppExecs[y] = x));
                pm.ApiExecutors.ForEach(x => x.Aliases.ForEach(y => newApiExecs[y] = x));
                appExecs = newAppExecs;
                apiExecs = newApiExecs;
                Action<PluginExecutor, string> printLoaded = (pe, type) => {
                    var aliases = pe.Aliases.Aggregate((acc, x) => acc += ", " + x);
                    Log.WriteLine(LogLevel.Notice, "Loaded {3} {0}, aliases '{1}', into domain {2}.", pe.Name, aliases, pi.Domain.FriendlyName, type);
                };
                pm.AppExecutors.ForEach(x => printLoaded(x, "App"));
                pm.ApiExecutors.ForEach(x => printLoaded(x, "Api"));
                Log.WriteLine(LogLevel.Info, "Finished loading {0} into domain {1}.", pi.FileName, pi.Domain.FriendlyName);
            }
        }
 internal PluginViewExtensionsNode(PluginInfo plugin)
 {
     _plugin = plugin;
 }
 /// <summary>
 /// 插件卸载信息
 /// </summary>
 /// <param name="info">插件信息</param>
 public ServerPluginUnloadArg(PluginInfo info)
 {
     this.Info = info;
 }
Example #17
0
 public static bool UnloadPlugin(PluginInfo pluginInfo)
 {
     // TODO Shoud load plugins in separate APPDomain, this let us unload the domain and all plugins
     throw new NotImplementedException();
 }
Example #18
0
 private void UpdatePluginActiveStatus(PluginInfo pluginInfo, bool active)
 {
     _pluginSettings.UpdatePluginStatus(pluginInfo.SystemName, true, active);
 }
 private void RemovePluginFromCatalog(PluginInfo pluginInfo)
 {
     DirectoryCatalog catalog;
     if (_pluginToCatalog.TryGetValue(pluginInfo, out catalog))
     {
         _pluginCatalog.Catalogs.Remove(catalog);
     }
 }
        private bool AddPluginToCatalog(PluginInfo pluginInfo, string targetPath, bool quietMode)
        {
            try
            {
                var directoryCatalog = new DirectoryCatalog(targetPath);
                if (directoryCatalog.Parts.Any())
                {
                    _pluginCatalog.Catalogs.Add(directoryCatalog);
                    _pluginToCatalog[pluginInfo] = directoryCatalog;
                }
                return true;
            }
            catch (ReflectionTypeLoadException exception)
            {
                _pluginToCatalog.Remove(pluginInfo);

                string errorMessage = BuildErrorMessage(exception);
                if (quietMode)
                {
                    Trace.WriteLine(errorMessage, "Plugins Loader");
                }
                else
                {
                    UIServices.Value.Show(errorMessage, MessageLevel.Error);
                }

                return false;
            }
        }
        public bool DeletePlugin(PluginInfo plugin)
        {
            if (plugin == null)
            {
                throw new ArgumentNullException("plugin");
            }

            string targetPath = GetTargetPath(plugin);
            if (Directory.Exists(targetPath))
            {
                RemovePluginFromCatalog(plugin);

                try
                {
                    CreateDeleteMeFile(targetPath);
                    return true;
                }
                catch (IOException ex)
                {
                    UIServices.Value.Show(ex.Message, MessageLevel.Error);
                    return false;
                }
            }

            return false;
        }
        /// <summary>
        /// Attempts to load a plugin from the assembly located at <paramref name="path"/>.
        /// </summary>
        /// <param name="path">The path at which plugin assembly is to be found.</param>
        public void LoadPlugin(string path)
        {
            string canonicalPath = GetCanonicalPath(path);
            string name;
            if (!attemptedFilenames.Contains(canonicalPath)) {
                try {
                    // Add this plugin to the list of loaded paths.
                    attemptedFilenames.Add(canonicalPath);

                    // Load an assembly.
                    Assembly assembly = Assembly.LoadFrom(canonicalPath);

                    // Find initializer class.
                    List<Type> types = new List<Type>(assembly.GetTypes());
                    Type interfaceType = typeof(IPluginInitializer);
                    Type initializerType = types.Find(t => interfaceType.IsAssignableFrom(t));
                    if (initializerType == null || initializerType.Equals(interfaceType)) {
                        Logger.Info("Assembly in file " + path +
                                    " doesn't contain any class implementing IPluginInitializer.");
                        return;
                    }

                    // Construct basic plugin info.
                    PluginInfo info = new PluginInfo();
                    info.Path = canonicalPath;
                    info.Initializer = (IPluginInitializer)Activator.CreateInstance(initializerType);

                    // Check if plugin with the same name was already loaded.
                    name = info.Initializer.Name;
                    info.Name = name;
                    if (loadedPlugins.ContainsKey(name)) {
                        Logger.Warn("Cannot load plugin from " + path + ". Plugin with the same name '" + name +
                                    "' was already loaded from " + loadedPlugins[name].Path + ".");
                        return;
                    }

                    // Check if plugin has all required dependencies.
                    info.RemainingPluginDeps =
                        info.Initializer.PluginDependencies.FindAll(plugin => !loadedPlugins.ContainsKey(plugin));
                    info.RemainingComponentDeps = info.Initializer.ComponentDependencies.FindAll(
                        component => ComponentRegistry.Instance.FindComponentDefinition(component) == null);

                    if (info.RemainingPluginDeps.Count > 0 || info.RemainingComponentDeps.Count > 0) {
                        deferredPlugins.Add(name, info);
                        return;
                    }

                    try {
                        // Initialize plugin.
                        info.Initializer.Initialize();
                    } catch (Exception e) {
                        Logger.WarnException("Exception occured during initialization of " + name + " plugin.", e);
                        return;
                    }
                    loadedPlugins.Add(name, info);
                } catch (BadImageFormatException e) {
                    Logger.InfoException(path + " is not a valid assembly and thus cannot be loaded as a plugin.", e);
                    return;
                } catch (Exception e) {
                    Logger.WarnException("Failed to load file " + path + " as a plugin", e);
                    return;
                }

                if (OnAnyPluginInitialized != null)
                    OnAnyPluginInitialized(this, new PluginInitializedEventArgs(name));
            }
        }
Example #23
0
 public PluginErrorEventArgs( Exception exception, PluginInfo pluginAssemblyInfo )
     : base(exception)
 {
     PluginAssemblyInfo = pluginAssemblyInfo;
 }
Example #24
0
        /// <summary>
        /// Reads a plugin's information from the configuration file.
        /// </summary>
        /// <param name="p_xndPlugin">The configuration file node corresponding to the plugin to read.</param>
        /// <returns>The plugin information.</returns>
        protected override PluginInfo parsePlugin(XmlNode p_xndPlugin)
        {
            string strName = p_xndPlugin.Attributes["name"].InnerText;
            string strDesc = p_xndPlugin.SelectSingleNode("description").InnerText.Trim();
            IPluginType iptType = null;
            XmlNode xndTypeDescriptor = p_xndPlugin.SelectSingleNode("typeDescriptor").FirstChild;
            switch (xndTypeDescriptor.Name)
            {
                case "type":
                    iptType = new StaticPluginType((PluginType)Enum.Parse(typeof(PluginType), xndTypeDescriptor.Attributes["name"].InnerText));
                    break;
                case "dependencyType":
                    PluginType ptpDefaultType = (PluginType)Enum.Parse(typeof(PluginType), xndTypeDescriptor.SelectSingleNode("defaultType").Attributes["name"].InnerText);
                    iptType = new DependencyPluginType(ptpDefaultType);
                    DependencyPluginType dptDependentType = (DependencyPluginType)iptType;

                    XmlNodeList xnlPatterns = xndTypeDescriptor.SelectNodes("patterns/*");
                    foreach (XmlNode xndPattern in xnlPatterns)
                    {
                        PluginType ptpType = (PluginType)Enum.Parse(typeof(PluginType), xndPattern.SelectSingleNode("type").Attributes["name"].InnerText);
                        CompositeDependency cdpDependency = loadDependency(xndPattern.SelectSingleNode("dependencies"));
                        dptDependentType.AddPattern(ptpType, cdpDependency);
                    }
                    break;
                default:
                    throw new ParserException("Invalid plaug type descriptor node: " + xndTypeDescriptor.Name + ". At this point the config file has been validated against the schema, so there's something wrong with the parser.");
            }
            XmlNode xndImage = p_xndPlugin.SelectSingleNode("image");
            Image imgImage = null;
            if (xndImage != null)
            {
                string strImageFilePath = xndImage.Attributes["path"].InnerText;
                imgImage = Fomod.GetImage(strImageFilePath);
            }
            PluginInfo pifPlugin = new PluginInfo(strName, strDesc, imgImage, iptType);

            XmlNodeList xnlPluginFiles = p_xndPlugin.SelectNodes("files/*");
            pifPlugin.Files.AddRange(readFileInfo(xnlPluginFiles));

            XmlNodeList xnlPluginFlags = p_xndPlugin.SelectNodes("conditionFlags/*");
            pifPlugin.Flags.AddRange(readFlagInfo(xnlPluginFlags));

            return pifPlugin;
        }
Example #25
0
 private Message create_plugin_list(PluginManager manager)
 {
     Message message = new Message();
     message.type = Message.Type.Plugins;
     message.creator_plugin_hash = this.GetHashCode().ToString();
     Plugins message_content = new Plugins();
     Hashtable plugins = new Hashtable();
     Plugins plugin_message = new Plugins();
     ArrayList loaded_plugins = manager.get_all();
     PluginInfo info;
     foreach(Plugin plug in loaded_plugins)
     {
         info = new PluginInfo();
         info.name = plug.name;
         info.hash = plug.GetHashCode().ToString();
         info.version = plug.version;
         plugins[info.name] = info;
     }
     message_content.plugins = plugins;
     message.content = message_content;
     return message;
 }
Example #26
0
 protected ProfileModule(PluginInfo pluginInfo) : base(pluginInfo)
 {
 }
Example #27
0
        public PluginInfo?AddPlugin(IPackage plugin)
        {
            if (plugin == null)
            {
                throw new ArgumentNullException("plugin");
            }

            if (PluginsDirectory == null)
            {
                return(null);
            }

            try
            {
                var pluginInfo = new PluginInfo(plugin.Id, plugin.Version);

                var targetPath = GetTargetPath(pluginInfo);
                if (Directory.Exists(targetPath))
                {
                    UIServices.Value.Show(
                        "Adding plugin failed. There is already an existing plugin with the same Id and Version.",
                        MessageLevel.Error);
                }
                else
                {
                    Directory.CreateDirectory(targetPath);
                    if (Directory.Exists(targetPath))
                    {
                        // make sure there is no .delete file lurking around for this plugin
                        var deleteMePath = targetPath + DeleteMeExtension;
                        File.Delete(deleteMePath);

                        // copy assemblies
                        var numberOfFilesCopied =
                            FrameworkFolderForAssemblies.Sum(folder => plugin.UnpackPackage(folder, targetPath));

                        if (numberOfFilesCopied == 0)
                        {
                            Directory.Delete(targetPath);
                            UIServices.Value.Show(
                                "Adding plugin failed. The selected package does not have any assembly inside the 'lib\\net*' folder.",
                                MessageLevel.Error);
                        }
                        else
                        {
                            var succeeded = AddPluginToCatalog(pluginInfo, targetPath, quietMode: false);
                            if (!succeeded)
                            {
                                DeletePlugin(pluginInfo);
                            }
                            return(succeeded ? pluginInfo : null);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                DiagnosticsClient.TrackException(exception);
                UIServices.Value.Show(exception.Message, MessageLevel.Error);
            }

            return(null);
        }
 private static string GetTargetPath(PluginInfo plugin)
 {
     string pluginName = plugin.Id + "[" + plugin.Version + "]";
     return Path.Combine(PluginsDirectory, pluginName);
 }
Example #29
0
 public void ActivatePlugin(PluginInfo pluginInfo)
 {
     UpdatePluginActiveStatus(pluginInfo, true);
 }
Example #30
0
        public PreferencesDialog() : base(null, "PreferencesDialog")
        {
            dialog        = base.Dialog;
            dialog.Shown += delegate {
                if (settings.FirstRun)
                {
                    on_redetectConnectionButton_clicked(redetectConnectionButton, EventArgs.Empty);
                    base.Dialog.SkipPagerHint   = false;
                    base.Dialog.SkipTaskbarHint = false;
                }
            };

            settings = Gui.Settings;

            /* Configure gui */

            firewallImage.Pixbuf           = new Gdk.Pixbuf(null, "FileFind.Meshwork.GtkClient.firewall-small.png");
            internetConnectionImage.Pixbuf = new Gdk.Pixbuf(null, "FileFind.Meshwork.GtkClient.network1.png");
            folderImage = Gui.LoadIcon(24, "folder");

            sharedFoldersListStore  = new Gtk.ListStore(typeof(string));
            sharedFoldersList.Model = sharedFoldersListStore;
            var imageCell = new CellRendererPixbuf();
            var textCell  = new CellRendererText();
            var column    = new TreeViewColumn();

            column.PackStart(imageCell, false);
            column.PackStart(textCell, true);
            column.SetCellDataFunc(imageCell, new TreeCellDataFunc(showFolderIcon));
            column.SetCellDataFunc(textCell, new TreeCellDataFunc(showFolderText));
            sharedFoldersList.AppendColumn(column);
            sharedFoldersList.RulesHint = true;

            Gtk.Drag.DestSet(sharedFoldersList, Gtk.DestDefaults.All, new Gtk.TargetEntry [] { new Gtk.TargetEntry("text/uri-list", 0, 0) }, Gdk.DragAction.Copy);
            sharedFoldersList.DragDataReceived += OnSharedFoldersListDragDataReceived;

            advancedListStore  = new Gtk.ListStore(typeof(string), typeof(int));
            advancedList.Model = advancedListStore;
            advancedList.AppendColumn("Text", new CellRendererText(), "text", 0);

            advancedNotebook.ShowTabs = false;

            for (int x = 0; x < advancedNotebook.NPages; x++)
            {
                Widget widget = advancedNotebook.GetNthPage(x);
                advancedListStore.AppendValues(advancedNotebook.GetTabLabelText(widget), x);
            }

            TreeIter iter;

            advancedListStore.GetIterFirst(out iter);
            advancedList.Selection.SelectIter(iter);

            if (Gui.MainWindow != null)
            {
                dialog.TransientFor = Gui.MainWindow.Window;
            }
            else
            {
                // First run!
            }

            Gtk.Drag.DestSet(avatarButton, DestDefaults.All, target_table, Gdk.DragAction.Copy | Gdk.DragAction.Move);


            provider = new RSACryptoServiceProvider();
            provider.ImportParameters(settings.EncryptionParameters);
            nodeid = Common.SHA512Str(provider.ToXmlString(false));

            /**** Load options ****/

            // General Tab
            nicknameEntry.Text = settings.NickName;
            nameEntry.Text     = settings.RealName;
            nodeIdLabel.Markup = "<span font=\"monospace\">" + Common.FormatFingerprint(nodeid, 7) + "</span>";
            emailEntry.Text    = settings.Email;

            string avatarDirectory = Path.Combine(Settings.ConfigurationDirectory, "avatars");
            string myAvatarFile    = Path.Combine(avatarDirectory, String.Format("{0}.png", nodeid));

            if (File.Exists(myAvatarFile))
            {
                avatarImage.Pixbuf = new Gdk.Pixbuf(myAvatarFile);
            }
            else
            {
                avatarImage.Pixbuf    = new Gdk.Pixbuf(null, "FileFind.Meshwork.GtkClient.avatar-generic-large.png");
                avatarImage.Sensitive = false;
            }

            // Networks tab
            networksListStore = new ListStore(typeof(NetworkInfo));

            foreach (NetworkInfo networkInfo in settings.Networks)
            {
                networksListStore.AppendValues(networkInfo.Clone());
            }

            networksTreeView.AppendColumn("Network Name", new CellRendererText(), new TreeCellDataFunc(NetworkNameFunc));
            networksTreeView.Model = networksListStore;

            // File Sharing Tab

            foreach (string dir in settings.SharedDirectories)
            {
                sharedFoldersListStore.AppendValues(new object[] { dir });
            }
            downloadsChooser.SetCurrentFolder(settings.IncompleteDownloadDir);
            completedDownloadsChooser.SetCurrentFolder(settings.CompletedDownloadDir);

            // Connection Tab

            tcpPortLabel.Text = settings.TcpListenPort.ToString();

            firewallStatusLabel.Text = String.Empty;

            if (CheckForNat())
            {
                natStatusLabel.Markup = "You <b>are</b> behind a NAT router.";
                // XXX: Include UPnP Info!
            }
            else
            {
                natStatusLabel.Markup     = "You <b>are not</b> behind a NAT router.";
                natOptionsTable.Sensitive = false;
            }

            bool foundIPv6Internal = false;
            bool foundIPv6External = false;

            foreach (IDestination destination in Core.DestinationManager.Destinations)
            {
                if (destination is IPv6Destination)
                {
                    if (((IPv6Destination)destination).IsExternal)
                    {
                        foundIPv6External = true;
                    }
                    else
                    {
                        foundIPv6Internal = true;
                    }
                }
                else if (destination is IPv4Destination && destination.IsExternal)
                {
                    internetIPLabel.Text = ((IPDestination)destination).Address.ToString();
                }
            }
            if (foundIPv6External)
            {
                supportsIPv6Label.Text = "Yes";
            }
            else if (foundIPv6Internal)
            {
                supportsIPv6Label.Text = "LAN Only";
            }
            else
            {
                supportsIPv6Label.Text = "No";
            }

            // Plugins Tab

            pluginsListStore = new ListStore(typeof(PluginInfo));
            pluginsTreeView.AppendColumn("Plugin Info", new CellRendererText(), new TreeCellDataFunc(PluginInfoFunc));
            pluginsTreeView.Model = pluginsListStore;

            foreach (string fileName in settings.Plugins)
            {
                try {
                    PluginInfo info = new PluginInfo(fileName);
                    pluginsListStore.AppendValues(info);
                } catch (Exception ex) {
                    Core.LoggingService.LogError(ex);
                }
            }

            // Advanced -> Appearance

            startInTrayCheckButton.Active = settings.StartInTray;

            // Advanced -> Auto-connect Tab
            autoConnectTreeStore  = new Gtk.TreeStore(typeof(object));
            autoConnectList.Model = autoConnectTreeStore;

            CellRendererToggle autoConnectToggleCell = new CellRendererToggle();

            autoConnectToggleCell.Toggled += OnAutoConnectItemToggled;

            CellRendererText autoConnectTextCell = new CellRendererText();

            column = new TreeViewColumn();
            column.PackStart(autoConnectToggleCell, false);
            column.SetCellDataFunc(autoConnectToggleCell, new TreeCellDataFunc(ShowAutoConnectToggle));
            column.PackStart(autoConnectTextCell, true);
            column.SetCellDataFunc(autoConnectTextCell, new TreeCellDataFunc(ShowAutoConnectName));
            autoConnectList.AppendColumn(column);
            autoConnectList.AppendColumn("IP", new CellRendererText(), new Gtk.TreeCellDataFunc(ShowAutoConnectIP));
            PopulateAutoConnectList();
            autoConnectCountSpinButton.Value = settings.AutoConnectCount;

            // Advanced -> Connection
            nodePortSpinButton.Value       = settings.TcpListenPort;
            nodePortOpenCheckButton.Active = settings.TcpListenPortOpen;
            detectIPCheckButton.Active     = settings.DetectInternetIPOnStart;
            externalIPv4AddressEntry.Text  = internetIPLabel.Text;
            stunServerEntry.Text           = settings.StunServer;

            ipv6LocalInterfaceComboBox.Model = new ListStore(typeof(string), typeof(int));
            ((ListStore)ipv6LocalInterfaceComboBox.Model).AppendValues("Disabled", -1);
            var interfaces = new Dictionary <string, int>();

            foreach (InterfaceAddress addr in Core.OS.GetInterfaceAddresses())
            {
                if (addr.Address.AddressFamily == AddressFamily.InterNetworkV6 && (!IPAddress.IsLoopback(addr.Address)))
                {
                    if (!interfaces.ContainsKey(addr.Name))
                    {
                        interfaces[addr.Name] = addr.InterfaceIndex;
                    }
                }
            }
            foreach (string name in interfaces.Keys)
            {
                ((ListStore)ipv6LocalInterfaceComboBox.Model).AppendValues(name, interfaces[name]);
            }

            if (ipv6LocalInterfaceComboBox.Model.GetIterFirst(out iter))
            {
                do
                {
                    int index = (int)ipv6LocalInterfaceComboBox.Model.GetValue(iter, 1);
                    if (index == settings.IPv6LinkLocalInterfaceIndex)
                    {
                        ipv6LocalInterfaceComboBox.SetActiveIter(iter);
                        break;
                    }
                } while (ipv6LocalInterfaceComboBox.Model.IterNext(ref iter));
            }

            UpdateFirewallLabel();

            // Advanced -> File Transfer
            limitDownSpeedCheckButton.Active = settings.EnableGlobalDownloadSpeedLimit;
            limitDownSpeedSpinButton.Value   = settings.GlobalDownloadSpeedLimit;

            limitUpSpeedCheckButton.Active = settings.EnableGlobalUploadSpeedLimit;
            limitUpSpeedSpinButton.Value   = settings.GlobalUploadSpeedLimit;

            // I cant seem to make anything default with just the glade file.
            nicknameEntry.GrabFocus();
        }
Example #31
0
 public void Awake()
 {
     logger     = Logger;
     pluginInfo = Info;
     Main.Init();
 }
Example #32
0
 public WootingDeviceProvider(PluginInfo pluginInfo, IRgbService rgbService) : base(pluginInfo, RGB.NET.Devices.Wooting.WootingDeviceProvider.Instance)
 {
     _rgbService = rgbService;
 }
 internal void SetPluginDirectory(PluginInfo pluginInfo, string directory)
 {
     pluginInfo.MainClass.Directory = directory;
 }
Example #34
0
 /// <summary>
 /// Gets the name of the specified mod.
 /// It will return the <see cref="IUserMod.Name"/> if found, otherwise it will return
 /// <see cref="PluginInfo.name"/> (assembly name).
 /// </summary>
 /// <param name="plugin">The <see cref="PluginInfo"/> associated with the mod.</param>
 /// <returns>The name of the specified plugin.</returns>
 private string GetModName(PluginInfo plugin)
 {
     return(((IUserMod)plugin.userModInstance).Name);
 }
Example #35
0
	void DisplayPluginUpdate(PluginUpdateInfo updateInfo, PluginInfo installedInfo, bool installed, string message)
	{
		pgUpdatePlugin.Visible = true;
		lblUpPluginName.Text = installedInfo.Name;
		lblUpPluginVersion.Text = installedInfo.Version;

		if (installed)
		{
			lblUpPluginStatus.Text = "Update was successful";
			lblUpPluginStatus.ForeColor = Color.Green;
			btnUpPluginUpdate.Enabled = false;
		}
		else if (updateInfo == null)
		{
			lblUpPluginStatus.Text = "Unable to check for update.";
			lblUpPluginStatus.ForeColor = Color.Red;
			btnUpPluginUpdate.Enabled = false;
		}
		else
		{
			lblUpPluginName.Text = updateInfo.PluginName;
			lblUpPluginVersion.Text = updateInfo.Version;
			if (Common.CompareASProxyVersions(updateInfo.Version, installedInfo.Version) == 1)
			{
				lblUpPluginStatus.Text = "Update is available.";
				lblUpPluginStatus.ForeColor = Color.Green;
				btnUpPluginUpdate.Enabled = true;
			}
			else
			{
				lblUpPluginStatus.Text = "Update is not available.";
				lblUpPluginStatus.ForeColor = Color.Red;
				btnUpPluginUpdate.Enabled = false;
			}
		}
		if (!string.IsNullOrEmpty(message))
			lblUpPluginStatus.Text = message;

	}
Example #36
0
 public Info(Assembly asm, PluginInfo info)
 {
     this.Assembly   = asm;
     this.PluginInfo = info;
 }
Example #37
0
        /// <summary>
        /// 创建订单
        /// </summary>
        /// <param name="partUserInfo">用户信息</param>
        /// <param name="orderProductList">订单商品列表</param>
        /// <param name="singlePromotionList">单品促销活动列表</param>
        /// <param name="fullShipAddressInfo">配送地址</param>
        /// <param name="payMode">支付方式(0代表货到付款,1代表在线支付)</param>
        /// <param name="shipPluginInfo">配送方式</param>
        /// <param name="payCreditCount">支付积分数</param>
        /// <param name="couponList">优惠劵列表</param>
        /// <param name="fullCut">满减</param>
        /// <param name="buyerRemark">买家备注</param>
        /// <param name="bestTime">最佳配送时间</param>
        /// <param name="ip">ip地址</param>
        /// <returns>订单信息</returns>
        public static OrderInfo CreateOrder(PartUserInfo partUserInfo, List <OrderProductInfo> orderProductList, List <SinglePromotionInfo> singlePromotionList, FullShipAddressInfo fullShipAddressInfo, int payMode, PluginInfo shipPluginInfo, int payCreditCount, List <CouponInfo> couponList, int fullCut, string buyerRemark, DateTime bestTime, string ip)
        {
            DateTime    nowTime    = DateTime.Now;
            IShipPlugin shipPlugin = (IShipPlugin)shipPluginInfo.Instance;

            OrderInfo orderInfo = new OrderInfo();

            orderInfo.OSN = GenerateOSN(partUserInfo.Uid, fullShipAddressInfo.RegionId, nowTime);
            orderInfo.Uid = partUserInfo.Uid;

            orderInfo.Weight        = Carts.SumOrderProductWeight(orderProductList);
            orderInfo.ProductAmount = Carts.SumOrderProductAmount(orderProductList);
            orderInfo.FullCut       = fullCut;

            orderInfo.ShipFee        = shipPlugin.GetShipFee(orderInfo.Weight, (orderInfo.ProductAmount - orderInfo.FullCut), orderProductList, nowTime, fullShipAddressInfo.ProvinceId, fullShipAddressInfo.CityId, fullShipAddressInfo.RegionId, partUserInfo);
            orderInfo.OrderAmount    = orderInfo.ProductAmount - orderInfo.FullCut + orderInfo.ShipFee;
            orderInfo.PayCreditCount = payCreditCount;
            orderInfo.PayCreditMoney = Credits.PayCreditsToMoney(payCreditCount);
            orderInfo.CouponMoney    = Coupons.SumCouponMoney(couponList);
            orderInfo.SurplusMoney   = orderInfo.OrderAmount - orderInfo.PayCreditMoney - orderInfo.CouponMoney;
            if (orderInfo.SurplusMoney < 0)
            {
                orderInfo.SurplusMoney = 0;
            }

            orderInfo.OrderState = (orderInfo.SurplusMoney <= 0 || payMode == 0) ? (int)OrderState.Confirming : (int)OrderState.WaitPaying;

            orderInfo.IsReview       = 0;
            orderInfo.AddTime        = nowTime;
            orderInfo.ShipSystemName = shipPluginInfo.SystemName;
            orderInfo.ShipFriendName = shipPluginInfo.FriendlyName;
            orderInfo.ShipTime       = new DateTime(1900, 1, 1);
            orderInfo.PaySystemName  = payMode == 0 ? "cod" : "";
            orderInfo.PayFriendName  = payMode == 0 ? "货到付款" : "";
            orderInfo.PayMode        = payMode;
            orderInfo.PayTime        = new DateTime(1900, 1, 1);

            orderInfo.RegionId  = fullShipAddressInfo.RegionId;
            orderInfo.Consignee = fullShipAddressInfo.Consignee;
            orderInfo.Mobile    = fullShipAddressInfo.Mobile;
            orderInfo.Phone     = fullShipAddressInfo.Phone;
            orderInfo.Email     = string.IsNullOrWhiteSpace(fullShipAddressInfo.Email)? partUserInfo.Email: fullShipAddressInfo.Email;
            orderInfo.ZipCode   = fullShipAddressInfo.ZipCode;
            orderInfo.Address   = fullShipAddressInfo.Address;
            orderInfo.BestTime  = bestTime;

            orderInfo.BuyerRemark = buyerRemark;
            orderInfo.IP          = ip;

            try
            {
                //添加订单
                int oid = _iorderstrategy.CreateOrder(orderInfo, Carts.IsPersistOrderProduct, orderProductList);
                if (oid > 0)
                {
                    orderInfo.Oid = oid;

                    //减少商品库存数量
                    Products.DecreaseProductStockNumber(orderProductList);
                    //更新限购库存
                    if (singlePromotionList.Count > 0)
                    {
                        Promotions.UpdateSinglePromotionStock(singlePromotionList);
                    }
                    //使用支付积分
                    Credits.PayOrder(ref partUserInfo, orderInfo, orderInfo.PayCreditCount, nowTime);
                    //使用优惠劵
                    foreach (CouponInfo couponInfo in couponList)
                    {
                        if (couponInfo.Uid > 0)
                        {
                            Coupons.UseCoupon(couponInfo.CouponId, oid, nowTime, ip);
                        }
                        else
                        {
                            Coupons.ActivateAndUseCoupon(couponInfo.CouponId, partUserInfo.Uid, oid, nowTime, ip);
                        }
                    }

                    return(orderInfo);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(null);
        }
Example #38
0
        BaseRecord Clone(BaseRecord record, bool bRecursive)
        {
            var p = GetPluginFromNode(record);
            PluginInfo info;
            if (!pluginMap.TryGetValue(p, out info))
                pluginMap.Add(p, info = new PluginInfo() { Masters = p.GetMasters() });

            var result = record.Clone(recursive: bRecursive);
            foreach (var rec in result.Enumerate().OfType<Record>())
            {
                uint newid;
                if (info.References.TryGetValue(rec.FormID, out newid) && rec.FormID != newid)
                    rec.FormID = newid;

                // now handle child references
                rec.MatchRecordStructureToRecord();
                foreach (var elem in rec.SubRecords
                    .SelectMany(sr => sr.EnumerateElements())
                    .Where(elem => elem.Structure != null && elem.Structure.type == ElementValueType.FormID)
                    )
                {
                    var value = elem.GetValue<uint>();
                    if (info.References.TryGetValue(value, out newid) && value != newid)
                        elem.AssignValue<uint>(newid);
                }
            }
            return result;
        }
 public void Deactivate(PluginInfo pluginInfo)
 {
     throw new System.NotImplementedException();
 }
Example #40
0
		public Plugin(PluginInfo info) {
			this.info = info;
		}
Example #41
0
 public PluginContext(PluginInfo plugin)
 {
     this.plugin = plugin;
 }
Example #42
0
        public PluginInfo[] ReadPluginList()
        {
            try
            {
                List<PluginInfo> listPI = new List<PluginInfo>();
                string[] DLLs = System.IO.Directory.GetFiles(GetPluginFolder(), "*.dll");
                foreach (var dllfile in DLLs)
                {
                    try
                    {
                        PluginInfo pi = new PluginInfo();
                        Assembly asmUC = LoadAssemblyPluginToMemory(dllfile);
                        pi.UserControlAsm = asmUC;
                        UserControl UCPlugin = CreateInstanceOfUserControlPlugin(asmUC);
                        pi.Name = (string)UCPlugin.GetType().UnderlyingSystemType.InvokeMember("PluginName", BindingFlags.GetProperty, null, UCPlugin, null);
                        pi.Description = (string)UCPlugin.GetType().UnderlyingSystemType.InvokeMember("PluginDescription", BindingFlags.GetProperty, null, UCPlugin, null);
                        pi.Author = (string)UCPlugin.GetType().UnderlyingSystemType.InvokeMember("PluginAuthor", BindingFlags.GetProperty, null, UCPlugin, null);
                        pi.CategoryId = (string)UCPlugin.GetType().UnderlyingSystemType.InvokeMember("PluginCategoryId", BindingFlags.GetProperty, null, UCPlugin, null);
                        pi.HelpPage = (string)UCPlugin.GetType().UnderlyingSystemType.InvokeMember("PluginHelpPage", BindingFlags.GetProperty, null, UCPlugin, null);
                        pi.Version = (string)UCPlugin.GetType().UnderlyingSystemType.InvokeMember("PluginVersion", BindingFlags.GetProperty, null, UCPlugin, null);
                        pi.Guid = (string)UCPlugin.GetType().UnderlyingSystemType.InvokeMember("PluginGuid", BindingFlags.GetProperty, null, UCPlugin, null);
                        pi.TreeIcon = (Bitmap)UCPlugin.GetType().UnderlyingSystemType.InvokeMember("PluginIcon", BindingFlags.GetProperty, null, UCPlugin, null);
                        UCPlugin.Dispose();
                        listPI.Add(pi);
                    }
                    catch (System.Exception ex)
                    {

                    }

                }

                return listPI.ToArray();


            }
            catch (System.Exception ex)
            {
                return null;
            }
        
        }
Example #43
0
        private void on_okButton_clicked(object o, EventArgs args)
        {
            dialog.Respond((int)Gtk.ResponseType.None);

            ArrayList badOptions = new ArrayList();

            if (nicknameEntry.Text == String.Empty)
            {
                badOptions.Add("Nickname");
            }

            if (Directory.Exists(completedDownloadsChooser.CurrentFolder) == false)
            {
                badOptions.Add("Completed dowmnloads directory");
            }

            if (Directory.Exists(downloadsChooser.CurrentFolder) == false)
            {
                badOptions.Add("Incomplete dowmnloads directory");
            }


            if (Common.IsValidIP(externalIPv4AddressEntry.Text) == false)
            {
                badOptions.Add("External IP Address");
            }

            if (networksListStore.IterNChildren() == 0)
            {
                badOptions.Add("Please define at least one network");
            }

            if (badOptions.Count > 0)
            {
                BadOptionsDialog badOptionsWindow = new BadOptionsDialog(dialog, badOptions);
                badOptionsWindow.Run();
                return;
            }

            settings.NickName = nicknameEntry.Text;
            settings.RealName = nameEntry.Text;
            settings.Email    = emailEntry.Text;

            settings.Networks.Clear();
            foreach (object[] row in networksListStore)
            {
                settings.Networks.Add((NetworkInfo)row[0]);
            }

            var newSharedDirectories = new List <string>();

            TreeIter iter;

            sharedFoldersListStore.GetIterFirst(out iter);
            if (sharedFoldersListStore.IterIsValid(iter))
            {
                foreach (object[] currentRow in sharedFoldersListStore)
                {
                    newSharedDirectories.Add((string)currentRow[0]);
                }
            }

            settings.SharedDirectories = newSharedDirectories.ToArray();

            settings.CompletedDownloadDir  = completedDownloadsChooser.CurrentFolder;
            settings.IncompleteDownloadDir = downloadsChooser.CurrentFolder;

            settings.SavedDestinationInfos.Clear();

            TCPIPv4Destination destination    = new TCPIPv4Destination(IPAddress.Parse(externalIPv4AddressEntry.Text), (uint)nodePortSpinButton.Value, nodePortOpenCheckButton.Active);
            DestinationInfo    externalIPInfo = destination.CreateDestinationInfo();

            externalIPInfo.Local = true;
            settings.SavedDestinationInfos.Add(externalIPInfo);

            settings.TcpListenPortOpen = nodePortOpenCheckButton.Active;
            settings.TcpListenPort     = (int)nodePortSpinButton.Value;

            if (ipv6LocalInterfaceComboBox.GetActiveIter(out iter))
            {
                int index = (int)ipv6LocalInterfaceComboBox.Model.GetValue(iter, 1);
                settings.IPv6LinkLocalInterfaceIndex = index;
            }
            else
            {
                settings.IPv6LinkLocalInterfaceIndex = -1;
            }

            if (stunServerEntry.Text != String.Empty)
            {
                settings.StunServer = stunServerEntry.Text;
            }
            else
            {
                settings.StunServer = Settings.DefaultStunServer;
            }

            settings.StartInTray      = startInTrayCheckButton.Active;
            settings.AutoConnectCount = autoConnectCountSpinButton.ValueAsInt;

            string avatarDirectory = Path.Combine(Settings.ConfigurationDirectory, "avatars");

            if (Directory.Exists(avatarDirectory) == false)
            {
                Directory.CreateDirectory(avatarDirectory);
            }

            string myAvatarFile = Path.Combine(avatarDirectory, String.Format("{0}.png", nodeid));

            //if (avatarImage.Pixbuf != null)
            if (avatarImage.Sensitive == true)
            {
                avatarImage.Pixbuf.Save(myAvatarFile, "png");
            }
            else
            if (File.Exists(myAvatarFile))
            {
                File.Delete(myAvatarFile);
            }

            settings.Plugins.Clear();
            foreach (object[] row in pluginsListStore)
            {
                PluginInfo info = (PluginInfo)row[0];
                settings.Plugins.Add(info.FilePath);
            }


            settings.SetFirstRun(false);
            settings.SaveSettings();

            if (Core.AvatarManager != null)
            {
                Core.AvatarManager.UpdateMyAvatar();
            }

            // Advanced -> File Transfer
            settings.EnableGlobalDownloadSpeedLimit = limitDownSpeedCheckButton.Active;
            settings.GlobalDownloadSpeedLimit       = Convert.ToInt32(limitDownSpeedSpinButton.Value);

            settings.EnableGlobalUploadSpeedLimit = limitUpSpeedCheckButton.Active;
            settings.GlobalUploadSpeedLimit       = Convert.ToInt32(limitUpSpeedSpinButton.Value);

            // Save and go!
            Core.ReloadSettings();
            dialog.Respond((int)Gtk.ResponseType.Ok);
        }
Example #44
0
 internal PluginViewPluginNode(PluginInfo plugin)
 {
     _plugin = plugin;
 }
Example #45
0
 private static int ComparePluginInfos(PluginInfo x, PluginInfo y)
 {
     return(string.Compare(x.Name, y.Name, StrUtil.CaseIgnoreCmp));
 }
Example #46
0
        static void loadFile(string fileName)
        {
            // Attempts to load the file. On failure, it will call unload.
            // Loading part does not take out a lock.
            // Lock is only done after loading is finished and dictionaries need updating.

            // We might get a load for a file that's no longer there. Just unload the old one.
            if (!File.Exists(fileName))
            {
                unloadFile(fileName);
                return;
            }

            Type pmType;

            switch (Path.GetExtension(fileName).ToLowerInvariant())
            {
            case ".dll":
                pmType = typeof(AsmPluginManager);
                break;

            case ".exe":     // TODO these need to come from config
            case ".fsx":
            case ".vbx":
            case ".csx":
            case ".jsx":
                pmType = typeof(ScriptPluginManager);
                break;

            default:
                pmType = null;
                break;
            }
            if (pmType == null)
            {
                return;
            }

            // App domain setup
            var setup = new AppDomainSetup();

            if (File.Exists(fileName + ".config"))
            {
                setup.ConfigurationFile = fileName + ".config";
            }
            setup.ApplicationBase       = Native.freeswitch.SWITCH_GLOBAL_dirs.mod_dir;
            setup.ShadowCopyDirectories = managedDir + ";";
            setup.LoaderOptimization    = LoaderOptimization.MultiDomainHost; // TODO: would MultiDomain work better since FreeSWITCH.Managed isn't gac'd?
            setup.CachePath             = shadowDir;
            setup.ShadowCopyFiles       = "true";
            setup.PrivateBinPath        = "managed";

            // Create domain and load PM inside
            System.Threading.Interlocked.Increment(ref appDomainCount);
            setup.ApplicationName = Path.GetFileName(fileName) + "_" + appDomainCount;
            var domain = AppDomain.CreateDomain(setup.ApplicationName, null, setup);

            PluginManager pm;

            try {
                pm = (PluginManager)domain.CreateInstanceAndUnwrap(pmType.Assembly.FullName, pmType.FullName, null);
                if (!pm.Load(fileName))
                {
                    AppDomain.Unload(domain);
                    unloadFile(fileName);
                    return;
                }
            } catch (Exception ex) {
                // On an exception, we will unload the current file so an old copy doesnt stay active
                Log.WriteLine(LogLevel.Alert, "Exception loading {0}: {1}", fileName, ex.ToString());
                AppDomain.Unload(domain);
                unloadFile(fileName);
                return;
            }

            // Update dictionaries atomically
            lock (loaderLock) {
                unloadFile(fileName);

                var pi = new PluginInfo {
                    FileName = fileName, Domain = domain, Manager = pm
                };
                pluginInfos.Add(pi);
                var newAppExecs = new Dictionary <string, AppPluginExecutor>(appExecs, StringComparer.OrdinalIgnoreCase);
                var newApiExecs = new Dictionary <string, ApiPluginExecutor>(apiExecs, StringComparer.OrdinalIgnoreCase);
                pm.AppExecutors.ForEach(x => x.Aliases.ForEach(y => newAppExecs[y] = x));
                pm.ApiExecutors.ForEach(x => x.Aliases.ForEach(y => newApiExecs[y] = x));
                appExecs = newAppExecs;
                apiExecs = newApiExecs;
                Action <PluginExecutor, string> printLoaded = (pe, type) => {
                    var aliases = pe.Aliases.Aggregate((acc, x) => acc += ", " + x);
                    Log.WriteLine(LogLevel.Notice, "Loaded {3} {0}, aliases '{1}', into domain {2}.", pe.Name, aliases, pi.Domain.FriendlyName, type);
                };
                pm.AppExecutors.ForEach(x => printLoaded(x, "App"));
                pm.ApiExecutors.ForEach(x => printLoaded(x, "Api"));
                Log.WriteLine(LogLevel.Info, "Finished loading {0} into domain {1}.", pi.FileName, pi.Domain.FriendlyName);
            }
        }
Example #47
0
 /// <summary>
 /// Gets the <see cref="Guid"/> of a mod.
 /// </summary>
 /// <param name="plugin">The <see cref="PluginInfo"/> associated with the mod.</param>
 /// <returns>The <see cref="Guid"/> of the mod.</returns>
 private Guid GetModGuid(PluginInfo plugin)
 {
     return(plugin.userModInstance.GetType().Assembly.ManifestModule.ModuleVersionId);
 }
Example #48
0
        static Mod()
        {
            try
            {
                //#if DEBUG

                /* Workaround for https://github.com/drok/Harmony-CitiesSkylines/issues/1
                 */
                var a = Assembly.GetExecutingAssembly();
                mainMod = Singleton <PluginManager> .instance.GetPluginsInfo().FirstOrDefault((x) => x.ContainsAssembly(a));

                if (mainMod != null)
                {
                    if (!mainMod.isEnabled)
                    {
                        var stackTrace = new System.Diagnostics.StackTrace(0, false);
                        var caller     = stackTrace.GetFrame(stackTrace.FrameCount - 1).GetMethod();
                        var callerName = caller.DeclaringType.FullName + "." + caller.Name;
#if TRACE
                        UnityEngine.Debug.LogError($"[{Versioning.FULL_PACKAGE_NAME}] In Mod..cctor() thread={Thread.CurrentThread.ManagedThreadId} plugin={mainMod != null} initiated by {callerName}\n{(new System.Diagnostics.StackTrace(0, true)).ToString()}");
#endif
                        if (callerName == "MenuPanel.Start")
                        {
                            /* Need to call EnableOnce after the constructor returns */
                            needAutoEnableCall = true;
                        }
                        else /* assume call from Starter.Awake() */

                        /* When instantiated via Starter, it is likely another mod scanning the mod list,
                         * instantiating all, including disabled mods, and not the Starter instantiating
                         * because this mod is actually enabled.
                         *
                         * This logic of examining the stack trace is needed because of these scanning mods
                         * Without them, it would be simply
                         * if (mainMod != null && !mainMod.isEnabled) {
                         *      ActiveAutoEnableOnce();
                         * }
                         *
                         * However, because of them, the instantiation happens inside the PluginManager.AddPlugins()
                         * loop, which means mod.IsEnabled=true cannot be called, but must be scheduled for later.
                         * mod.IsEnabled=true would cause a second instance to be instantiated first and OnEnabled(),
                         * but the first instance added as userModInstance, not OnEnabled(), but present
                         * on the instance list.
                         */
                        {
                            /* I've already been added to the plugin list. Need active enable */
                            Singleton <PluginManager> .instance.eventPluginsChanged += ActiveAutoEnableOnce;
                        }
                    }
#if DEVELOPER_UPDATER
                    AutoInstallHelperOnce(mainMod);
                    needInstallCall = false;
#endif
                }
            }
            catch (Exception ex)
            {
                UnityEngine.Debug.LogWarning($"[{Versioning.FULL_PACKAGE_NAME}] Mod..cctor: ({Report.ExMessage(ex, true)})");
            }
#if HEAVY_TRACE
            UnityEngine.Debug.LogError($"[{Versioning.FULL_PACKAGE_NAME}] Mod..cctor DONE");
#endif
        }
Example #49
0
        public Plugins()
        {
            List <string> files = new List <string>();

            string exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            try {
                foreach (string file in Directory.GetFiles(Path.Combine(exePath, "Plugins"), "*.dll"))
                {
                    files.Add(file);
                }
            } catch { }

            if (PlatformDetection.IsMac)
            {
                try {
                    foreach (string file in Directory.GetFiles(Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(exePath)), "Plugins"), "*.dll"))
                    {
                        files.Add(file);
                    }
                } catch { }
            }

            string applicationData = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Weland");

            try {
                foreach (string file in Directory.GetFiles(Path.Combine(applicationData, "Plugins"), "*.dll"))
                {
                    files.Add(file);
                }
            } catch { }

            foreach (string file in files)
            {
                try {
                    // needs to have at least name and run or gtkrun
                    Assembly a = Assembly.LoadFrom(file);

                    foreach (Type t in a.GetTypes())
                    {
                        PluginInfo plugin           = new PluginInfo();
                        MethodInfo compatibleMethod = t.GetMethod("Compatible");
                        if (compatibleMethod == null || !compatibleMethod.IsStatic || !((bool)compatibleMethod.Invoke(0, new object[0])))
                        {
                            continue;
                        }

                        MethodInfo nameMethod = t.GetMethod("Name");
                        if (nameMethod != null && nameMethod.IsStatic)
                        {
                            plugin.Name   = (string)nameMethod.Invoke(0, new object[0]);
                            plugin.Run    = t.GetMethod("Run");
                            plugin.GtkRun = t.GetMethod("GtkRun");

                            if (plugin.Run != null && !plugin.Run.IsStatic)
                            {
                                plugin.Run = null;
                            }

                            if (plugin.GtkRun != null && !plugin.GtkRun.IsStatic)
                            {
                                plugin.GtkRun = null;
                            }

                            if (plugin.Run != null || plugin.GtkRun != null)
                            {
                                plugins.Add(plugin);
                                break;
                            }
                        }
                    }
                } catch {
                    continue;
                }
            }
        }
Example #50
0
        public void OnEnabled()
        {
            try
            {
#if DEBUG
                ListLoadedMods();
#endif
                if (handover == null)
                {
                    handover = new Handover(this);
                }

#if TRACE
                UnityEngine.Debug.LogWarning($"[{Versioning.FULL_PACKAGE_NAME}] Mod.OnEnabled() I am={handover.self.name} #{instancenum}");
#endif

                if (handover.BootStrapMainMod())
                {
                    if (handover.isHelper)
                    {
                        helperMod = handover.helperMod;
                    }
                    var mainModName = $"{(handover.mainMod().userModInstance as IUserMod).Name} {handover.mainModVersion}";
#if TRACE
                    UnityEngine.Debug.Log($"[{Versioning.FULL_PACKAGE_NAME}] INFO: Helper, main Mod '{mainModName}' was bootstrapped.");
#endif
                }
                else
                {
#if TRACE
                    UnityEngine.Debug.Log($"[{Versioning.FULL_PACKAGE_NAME}] INFO: I am the active Harmony.");
#endif

                    OnActive();

#if DEVELOPER
                    if (!handover.isFirst && !handover.isHelperFirst)
                    {
                        UnityEngine.Debug.LogError($"[{Versioning.FULL_PACKAGE_NAME}] INFO - reporting - SelfProblemType.NotLoadedFirst on SELF");
                        SelfReport(SelfProblemType.NotLoadedFirst);
                    }

#if DEVELOPER_UPDATER
                    /* Update helper if I (main) am not first.
                     * Write its DLL with my _helper_dll file, which is a higher version of myself.
                     *
                     * Also when the workshop mod is updated, the local helper's DLL will be updated to the
                     * newly released _helper_dll.
                     *
                     * The _helper_dll file is the same as the main DLL, but with version incremented by 1
                     * This allows the game to recongnize the helper and the workshop mod as distinct mods.
                     * If they are identical, the game only loads the workshop (late).
                     *
                     * On the next game restart, the helper will be main and remain main.
                     * If the file copy fails, the local helper will handover to the more recent
                     * main mod from workshop.
                     */
                    if (needInstallCall)
                    {
                        if (helperMod != null && helperMod.userModInstance.GetType().Assembly.GetName().Version < Assembly.GetExecutingAssembly().GetName().Version)
                        {
                            needInstallCall = false;
                            AutoInstallHelperOnce(mainMod);
                            //HelperUpdate(handover.mainMod());
                        }
                    }
#endif
#endif
                }
            }
            catch (Exception ex)
            {
                UnityEngine.Debug.LogError($"[{Versioning.FULL_PACKAGE_NAME}] ERROR FAIL TO INIT:\n{Report.ExMessage(ex, true)} ... \n {ex.StackTrace}\n\ncall from {new System.Diagnostics.StackTrace(true)}");
                SelfReport(SelfProblemType.FailedToInitialize, ex);
            }
        }
Example #51
0
        /// <summary>
        /// Search through records and determine what masters to add prior to replacement
        /// </summary>
        /// <param name="records"></param>
        void PrepMasters(IEnumerable<BaseRecord> records)
        {
            // ensure masters are added
            bool changed = false;
            foreach (var key in plugin.GetMasters())
                this.masters.Add(key, key);
            var recordList = records.SelectMany(x => x.Enumerate()).OfType<Record>().ToList();

            // use 0xFF as temporary master placeholder
            uint newid = (plugin.GetNewFormID(increment: false) & 0x00FFFFFF) | 0xFF000000;

            // build list of records getting new ids.  So we know if need to masters for references
            if (!Override)
            {
                foreach (var sn in recordList.Where(rec => !NoNewCopyTypes.Contains(rec.Name))) // skip loose references
                {
                    var p = sn.GetPlugin();
                    PluginInfo info;
                    if (!pluginMap.TryGetValue(p, out info))
                        pluginMap.Add(p, info = new PluginInfo() { Masters = p.GetMasters() });
                    info.References[sn.FormID] = newid++; // not an override
                }
            }

            foreach (var rec in recordList)
            {
                var p = rec.GetPlugin();
                PluginInfo info;
                if (!pluginMap.TryGetValue(p, out info))
                    pluginMap.Add(p, info = new PluginInfo() { Masters = p.GetMasters() });

                // now handle child references
                rec.MatchRecordStructureToRecord();
                var ids = rec.SubRecords.SelectMany(sr => sr.EnumerateElements())
                    .Where(elem => elem.Structure != null && elem.Structure.type == ElementValueType.FormID)
                    .Select(elem => TypeConverter.h2i(elem.Data)).Distinct().ToList();
                ids.Add(rec.FormID);
                ids.Sort(); // processing in sort order should keep master orders slightly more sane

                foreach (var id in ids)
                {
                    if (info.References.ContainsKey(id))
                        continue;

                    var idx = id >> 24;
                    var masterName = idx >= info.Masters.Length ? p.Name : info.Masters[idx];
                    if (!masters.ContainsKey(masterName))
                    {
                        plugin.AddMaster(masterName);
                        this.masters.Add(masterName, masterName);
                        changed = true;
                    }

                    var newidx = this.masters.FindIndex(masterName);
                    if (newidx < 0) newidx = 0xFF;
                    info.References[id] = (id & 0x00FFFFFF) | (uint)(newidx << 24);
                }
            }

            // fix up the new references after all masters have been added
            var masterId = (uint)(this.masters.Count << 24);
            foreach (var info in this.pluginMap.Values)
            {
                foreach (
                    var kvp in info.References.Where(kvp => ((kvp.Value & 0xFF000000) == 0xFF000000)).ToArray())
                {
                    info.References[kvp.Key] = (kvp.Value & 0x00FFFFFF) | masterId;
                }
            }

            plugin.UpdateNextFormID(newid & 0x00FFFFFF);
            if (changed) PluginList.FixMasters();
        }
Example #52
0
        /* FIXME: If the app is shutting down, I have to be last to disable,
         * to catch exceptions from other mods disabling, and to turn off HarmonyLib(s) last.
         */
        // void IAwareness.IAmAware.OnMainModChanged(IAwareness0::IAwareness.IAmAware main, bool enabled)
        void IAmAware.OnMainModChanged(IAmAware main, bool enabled)
        {
            try
            {
                if (handover != null)
                {
#if TRACE
                    UnityEngine.Debug.LogError($"[{Versioning.FULL_PACKAGE_NAME}] In Mod.OnMainModChanged() enabled={enabled} I am={handover.self.name}");
#endif

                    /* TODO: Implement */
                    if (handover.BootStrapMainMod(enabled))
                    {
                        var mainModName = $"{(handover.mainMod().userModInstance as IUserMod).Name} {handover.mainModVersion}";
                        if (handover.isHelper)
                        {
                            helperMod       = handover.helperMod;
                            mainMod         = handover.mainMod();
                            mainModInstance = mainMod.userModInstance as Mod;

                            UnityEngine.Debug.Log($"[{Versioning.FULL_PACKAGE_NAME}] INFO: I switched to Helper role to Mod '{mainModName}'");
                        }
                        else
                        {
                            UnityEngine.Debug.Log($"[{Versioning.FULL_PACKAGE_NAME}] INFO: I switched to Standby role to Mod '{mainModName}'");
                        }


                        if (enabled)
                        {
#if HEAVY_TRACE
                            resolver.Uninstall();
#endif
                            patcher.Uninstall();
                            main.PutModReports(report.modReports);
                            report.OnDisabled(handover.self, true);
                            report = null;
                        }
                    }
                    else
                    {
#if DEBUG
                        var oldMain = Singleton <PluginManager> .instance.GetPluginsInfo().First((x) => x.isEnabledNoOverride && x.userModInstance == main);

                        UnityEngine.Debug.Log($"[{Versioning.FULL_PACKAGE_NAME}] INFO: I switched to Main role from {oldMain.name}");
#endif
                        OnActive();
                    }

                    Assert.IsTrue(mainMod.userModInstance is IAmAware,
                                  "Only IAmAware instances can be main mods");
                    Assert.IsFalse(enabled && handover.isMainMod,
                                   "Notified instance should concur that it is no longer the main Mod");
                    Assert.IsTrue(main == handover.mainMod(),
                                  "Notification of another Harmony mod being main should be accurate");
                }
#if HEAVY_TRACE
                else
                {
                    UnityEngine.Debug.LogError($"[{Versioning.FULL_PACKAGE_NAME}] In Mod.OnMainModChanged() enabled={enabled}");
                }
#endif
            }
            catch (Exception ex)
            {
                SelfReport(SelfProblemType.FailedToYieldToMain, ex);
            }
        }
Example #53
0
        /// <summary>
        /// The entrypoint for the BepInEx plugin system.
        /// </summary>
        public static void Start()
        {
            if (_loaded)
            {
                return;
            }

            if (!_initialized)
            {
                throw new InvalidOperationException("BepInEx has not been initialized. Please call Chainloader.Initialize prior to starting the chainloader instance.");
            }

            if (!Directory.Exists(Paths.PluginPath))
            {
                Directory.CreateDirectory(Paths.PluginPath);
            }

            if (!Directory.Exists(Paths.PatcherPluginPath))
            {
                Directory.CreateDirectory(Paths.PatcherPluginPath);
            }

            try
            {
                var productNameProp = typeof(Application).GetProperty("productName", BindingFlags.Public | BindingFlags.Static);

                if (ConsoleManager.ConsoleActive)
                {
                    ConsoleManager.SetConsoleTitle($"{CurrentAssemblyName} {CurrentAssemblyVersion} - {productNameProp?.GetValue(null, null) ?? Paths.ProcessName}");
                }

                Logger.LogMessage("Chainloader started");

                ManagerObject = new GameObject("BepInEx_Manager");

                UnityEngine.Object.DontDestroyOnLoad(ManagerObject);

                var pluginsToLoad = TypeLoader.FindPluginTypes(Paths.PluginPath, ToPluginInfo, HasBepinPlugins, "chainloader");
                foreach (var keyValuePair in pluginsToLoad)
                {
                    foreach (var pluginInfo in keyValuePair.Value)
                    {
                        pluginInfo.Location = keyValuePair.Key;
                    }
                }
                var pluginInfos      = pluginsToLoad.SelectMany(p => p.Value).ToList();
                var loadedAssemblies = new Dictionary <string, Assembly>();

                Logger.LogInfo($"{pluginInfos.Count} plugins to load");

                // We use a sorted dictionary to ensure consistent load order
                var dependencyDict = new SortedDictionary <string, IEnumerable <string> >(StringComparer.InvariantCultureIgnoreCase);
                var pluginsByGUID  = new Dictionary <string, PluginInfo>();

                foreach (var pluginInfoGroup in pluginInfos.GroupBy(info => info.Metadata.GUID))
                {
                    PluginInfo loadedVersion = null;
                    foreach (var pluginInfo in pluginInfoGroup.OrderByDescending(x => x.Metadata.Version))
                    {
                        if (loadedVersion != null)
                        {
                            Logger.LogWarning($"Skipping [{pluginInfo}] because a newer version exists ({loadedVersion})");
                            continue;
                        }

                        loadedVersion = pluginInfo;

                        // Perform checks that will prevent loading plugins in this run
                        var  filters            = pluginInfo.Processes.ToList();
                        bool invalidProcessName = filters.Count != 0 && filters.All(x => !string.Equals(x.ProcessName.Replace(".exe", ""), Paths.ProcessName, StringComparison.InvariantCultureIgnoreCase));

                        if (invalidProcessName)
                        {
                            Logger.LogWarning($"Skipping [{pluginInfo}] because of process filters ({string.Join(", ", pluginInfo.Processes.Select(p => p.ProcessName).ToArray())})");
                            continue;
                        }

                        dependencyDict[pluginInfo.Metadata.GUID] = pluginInfo.Dependencies.Select(d => d.DependencyGUID);
                        pluginsByGUID[pluginInfo.Metadata.GUID]  = pluginInfo;
                    }
                }

                foreach (var pluginInfo in pluginsByGUID.Values.ToList())
                {
                    if (pluginInfo.Incompatibilities.Any(incompatibility => pluginsByGUID.ContainsKey(incompatibility.IncompatibilityGUID)))
                    {
                        pluginsByGUID.Remove(pluginInfo.Metadata.GUID);
                        dependencyDict.Remove(pluginInfo.Metadata.GUID);

                        var    incompatiblePlugins = pluginInfo.Incompatibilities.Select(x => x.IncompatibilityGUID).Where(x => pluginsByGUID.ContainsKey(x)).ToArray();
                        string message             = $@"Could not load [{pluginInfo}] because it is incompatible with: {string.Join(", ", incompatiblePlugins)}";
                        DependencyErrors.Add(message);
                        Logger.LogError(message);
                    }
                    else if (PluginTargetsWrongBepin(pluginInfo))
                    {
                        string message = $@"Plugin [{pluginInfo}] targets a wrong version of BepInEx ({pluginInfo.TargettedBepInExVersion}) and might not work until you update";
                        DependencyErrors.Add(message);
                        Logger.LogWarning(message);
                    }
                }

                var emptyDependencies = new string[0];

                // Sort plugins by their dependencies.
                // Give missing dependencies no dependencies of its own, which will cause missing plugins to be first in the resulting list.
                var sortedPlugins = Utility.TopologicalSort(dependencyDict.Keys, x => dependencyDict.TryGetValue(x, out var deps) ? deps : emptyDependencies).ToList();

                var invalidPlugins   = new HashSet <string>();
                var processedPlugins = new Dictionary <string, Version>();

                foreach (var pluginGUID in sortedPlugins)
                {
                    // If the plugin is missing, don't process it
                    if (!pluginsByGUID.TryGetValue(pluginGUID, out var pluginInfo))
                    {
                        continue;
                    }

                    var dependsOnInvalidPlugin = false;
                    var missingDependencies    = new List <BepInDependency>();
                    foreach (var dependency in pluginInfo.Dependencies)
                    {
                        bool IsHardDependency(BepInDependency dep) => (dep.Flags & BepInDependency.DependencyFlags.HardDependency) != 0;

                        // If the dependency wasn't already processed, it's missing altogether
                        bool dependencyExists = processedPlugins.TryGetValue(dependency.DependencyGUID, out var pluginVersion);
                        if (!dependencyExists || pluginVersion < dependency.MinimumVersion)
                        {
                            // If the dependency is hard, collect it into a list to show
                            if (IsHardDependency(dependency))
                            {
                                missingDependencies.Add(dependency);
                            }
                            continue;
                        }

                        // If the dependency is invalid (e.g. has missing dependencies) and hard, report that to the user
                        if (invalidPlugins.Contains(dependency.DependencyGUID) && IsHardDependency(dependency))
                        {
                            dependsOnInvalidPlugin = true;
                            break;
                        }
                    }

                    processedPlugins.Add(pluginGUID, pluginInfo.Metadata.Version);

                    if (dependsOnInvalidPlugin)
                    {
                        string message = $"Skipping [{pluginInfo}] because it has a dependency that was not loaded. See previous errors for details.";
                        DependencyErrors.Add(message);
                        Logger.LogWarning(message);
                        continue;
                    }

                    if (missingDependencies.Count != 0)
                    {
                        bool IsEmptyVersion(Version v) => v.Major == 0 && v.Minor == 0 && v.Build <= 0 && v.Revision <= 0;

                        string message = $@"Could not load [{pluginInfo}] because it has missing dependencies: {
							string.Join(", ", missingDependencies.Select(s => IsEmptyVersion(s.MinimumVersion) ? s.DependencyGUID : $"{s.DependencyGUID} (v{s.MinimumVersion} or newer)").ToArray())
							}"                            ;
                        DependencyErrors.Add(message);
                        Logger.LogError(message);

                        invalidPlugins.Add(pluginGUID);
                        continue;
                    }

                    try
                    {
                        Logger.LogInfo($"Loading [{pluginInfo}]");

                        if (!loadedAssemblies.TryGetValue(pluginInfo.Location, out var ass))
                        {
                            loadedAssemblies[pluginInfo.Location] = ass = Assembly.LoadFile(pluginInfo.Location);
                        }

                        PluginInfos[pluginGUID] = pluginInfo;
                        pluginInfo.Instance     = (BaseUnityPlugin)ManagerObject.AddComponent(ass.GetType(pluginInfo.TypeName));

                        _plugins.Add(pluginInfo.Instance);
                    }
                    catch (Exception ex)
                    {
                        invalidPlugins.Add(pluginGUID);
                        PluginInfos.Remove(pluginGUID);

                        Logger.LogError($"Error loading [{pluginInfo}] : {ex.Message}");
                        if (ex is ReflectionTypeLoadException re)
                        {
                            Logger.LogDebug(TypeLoader.TypeLoadExceptionToString(re));
                        }
                        else
                        {
                            Logger.LogDebug(ex);
                        }
                    }
                }
            }
Example #54
0
        private void loadPlugin(string name, string pluginSpec, ref string[] cmdArgs)
        {
            Debug.Assert(_communicator != null);

            string[] args       = null;
            string   entryPoint = null;

            if (pluginSpec.Length > 0)
            {
                //
                // Split the entire property value into arguments. An entry point containing spaces
                // must be enclosed in quotes.
                //
                try
                {
                    args = IceUtilInternal.Options.split(pluginSpec);
                }
                catch (IceUtilInternal.Options.BadQuote ex)
                {
                    PluginInitializationException e = new PluginInitializationException();
                    e.reason = "invalid arguments for plug-in `" + name + "':\n" + ex.Message;
                    throw e;
                }

                Debug.Assert(args.Length > 0);

                entryPoint = args[0];

                //
                // Shift the arguments.
                //
                string[] tmp = new string[args.Length - 1];
                Array.Copy(args, 1, tmp, 0, args.Length - 1);
                args = tmp;

                //
                // Convert command-line options into properties. First
                // we convert the options from the plug-in
                // configuration, then we convert the options from the
                // application command-line.
                //
                Properties properties = _communicator.getProperties();
                args    = properties.parseCommandLineOptions(name, args);
                cmdArgs = properties.parseCommandLineOptions(name, cmdArgs);
            }

            string err = "unable to load plug-in `" + entryPoint + "': ";
            //
            // Always check the static plugin factory table first, it takes
            // precedence over the the entryPoint specified in the plugin
            // property value.
            //
            PluginFactory pluginFactory = null;

            if (!_factories.TryGetValue(name, out pluginFactory))
            {
                //
                // Extract the assembly name and the class name.
                //
                int sepPos = entryPoint.IndexOf(':');
                if (sepPos != -1)
                {
                    const string driveLetters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
                    if (entryPoint.Length > 3 &&
                        sepPos == 1 &&
                        driveLetters.IndexOf(entryPoint[0]) != -1 &&
                        (entryPoint[2] == '\\' || entryPoint[2] == '/'))
                    {
                        sepPos = entryPoint.IndexOf(':', 3);
                    }
                }
                if (sepPos == -1)
                {
                    PluginInitializationException e = new PluginInitializationException();
                    e.reason = err + "invalid entry point format";
                    throw e;
                }

                System.Reflection.Assembly pluginAssembly = null;
                string assemblyName = entryPoint.Substring(0, sepPos);
                string className    = entryPoint.Substring(sepPos + 1);

                try
                {
                    //
                    // First try to load the assembly using Assembly.Load, which will succeed
                    // if a fully-qualified name is provided or if a partial name has been qualified
                    // in configuration. If that fails, try Assembly.LoadFrom(), which will succeed
                    // if a file name is configured or a partial name is configured and DEVPATH is used.
                    //
                    // We catch System.Exception as this can fail with System.ArgumentNullException
                    // or System.IO.IOException depending of the .NET framework and platform.
                    //
                    try
                    {
                        pluginAssembly = System.Reflection.Assembly.Load(assemblyName);
                    }
                    catch (System.Exception ex)
                    {
                        try
                        {
                            pluginAssembly = System.Reflection.Assembly.LoadFrom(assemblyName);
                        }
                        catch (System.IO.IOException)
                        {
                            throw ex;
                        }
                    }
                }
                catch (System.Exception ex)
                {
                    PluginInitializationException e = new PluginInitializationException();
                    e.reason = err + "unable to load assembly: `" + assemblyName + "': " + ex.ToString();
                    throw e;
                }

                //
                // Instantiate the class.
                //
                System.Type c = null;
                try
                {
                    c = pluginAssembly.GetType(className, true);
                }
                catch (System.Exception ex)
                {
                    PluginInitializationException e = new PluginInitializationException(ex);
                    e.reason = err + "GetType failed for `" + className + "'";
                    throw e;
                }

                try
                {
                    pluginFactory = (PluginFactory)IceInternal.AssemblyUtil.createInstance(c);
                    if (pluginFactory == null)
                    {
                        PluginInitializationException e = new PluginInitializationException();
                        e.reason = err + "can't find constructor for `" + className + "'";
                        throw e;
                    }
                }
                catch (InvalidCastException ex)
                {
                    PluginInitializationException e = new PluginInitializationException(ex);
                    e.reason = err + "InvalidCastException to Ice.PluginFactory";
                    throw e;
                }
                catch (UnauthorizedAccessException ex)
                {
                    PluginInitializationException e = new PluginInitializationException(ex);
                    e.reason = err + "UnauthorizedAccessException: " + ex.ToString();
                    throw e;
                }
                catch (System.Exception ex)
                {
                    PluginInitializationException e = new PluginInitializationException(ex);
                    e.reason = err + "System.Exception: " + ex.ToString();
                    throw e;
                }
            }

            Plugin plugin = null;

            try
            {
                plugin = pluginFactory.create(_communicator, name, args);
            }
            catch (PluginInitializationException ex)
            {
                ex.reason = err + ex.reason;
                throw;
            }
            catch (System.Exception ex)
            {
                PluginInitializationException e = new PluginInitializationException(ex);
                e.reason = err + "System.Exception in factory.create: " + ex.ToString();
                throw e;
            }

            if (plugin == null)
            {
                PluginInitializationException ex = new PluginInitializationException();
                ex.reason = err + "factory.create returned null plug-in";
                throw ex;
            }

            PluginInfo info = new PluginInfo();

            info.name   = name;
            info.plugin = plugin;
            _plugins.Add(info);
        }
Example #55
0
        private static string GetTargetPath(PluginInfo plugin)
        {
            var pluginName = plugin.Id + "[" + plugin.Version + "]";

            return(Path.Combine(PluginsDirectory, pluginName));
        }
Example #56
0
 public static bool IsInstalled(PluginInfo pluginInfo)
 {
     return Plugins.Any(x => x.SystemName == pluginInfo.SystemName);
 }
Example #57
0
 public void UninstallPlugin(PluginInfo pluginInfo)
 {
     _pluginInstallerService.Uninstall(pluginInfo);
     _pluginSettings.UpdatePluginStatus(pluginInfo.SystemName, false, false);
 }
Example #58
0
 /// <summary>
 /// Marks a plugin as uninstalled
 /// </summary>
 /// <param name="pluginInfo"></param>
 public static void MarkUninstalled(PluginInfo pluginInfo)
 {
     pluginInfo.Installed = false;
     pluginInfo.Active = false;
     PluginConfigurator.WriteConfigFile(Plugins.ToList(), HostingEnvironment.MapPath(PluginsFile));
 }
Example #59
0
 public void DeactivatePlugin(PluginInfo pluginInfo)
 {
     UpdatePluginActiveStatus(pluginInfo, false);
 }
Example #60
0
 public PluginEventArgs( PluginInfo pluginAssemblyInfo )
 {
     PluginAssemblyInfo = pluginAssemblyInfo;
 }