Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.PluginInfrastructure/3.3/Manager/PluginValidator.cs @ 4068

Last change on this file since 4068 was 4068, checked in by swagner, 14 years ago

Sorted usings and removed unused usings in entire solution (#1094)

File size: 27.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.IO;
25using System.Linq;
26using System.Reflection;
27using System.Security;
28using System.Text;
29
30
31namespace HeuristicLab.PluginInfrastructure.Manager {
32  /// <summary>
33  /// Discovers all installed plugins in the plugin directory. Checks correctness of plugin meta-data and if
34  /// all plugin files are available and checks plugin dependencies.
35  /// </summary>
36  internal sealed class PluginValidator : MarshalByRefObject {
37    // private class to store plugin dependency declarations while reflecting over plugins
38    private class PluginDependency {
39      public string Name { get; private set; }
40      public Version Version { get; private set; }
41
42      public PluginDependency(string name, Version version) {
43        this.Name = name;
44        this.Version = version;
45      }
46    }
47
48
49    internal event EventHandler<PluginInfrastructureEventArgs> PluginLoaded;
50
51    private Dictionary<PluginDescription, IEnumerable<PluginDependency>> pluginDependencies;
52
53    private List<ApplicationDescription> applications;
54    internal IEnumerable<ApplicationDescription> Applications {
55      get {
56        if (string.IsNullOrEmpty(PluginDir)) throw new InvalidOperationException("PluginDir is not set.");
57        if (applications == null) DiscoverAndCheckPlugins();
58        return applications;
59      }
60    }
61
62    private IEnumerable<PluginDescription> plugins;
63    internal IEnumerable<PluginDescription> Plugins {
64      get {
65        if (string.IsNullOrEmpty(PluginDir)) throw new InvalidOperationException("PluginDir is not set.");
66        if (plugins == null) DiscoverAndCheckPlugins();
67        return plugins;
68      }
69    }
70
71    internal string PluginDir { get; set; }
72
73    internal PluginValidator() {
74      this.pluginDependencies = new Dictionary<PluginDescription, IEnumerable<PluginDependency>>();
75
76      // ReflectionOnlyAssemblyResolveEvent must be handled because we load assemblies from the plugin path
77      // (which is not listed in the default assembly lookup locations)
78      AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += ReflectionOnlyAssemblyResolveEventHandler;
79    }
80
81    private Dictionary<string, Assembly> reflectionOnlyAssemblies = new Dictionary<string, Assembly>();
82    private Assembly ReflectionOnlyAssemblyResolveEventHandler(object sender, ResolveEventArgs args) {
83      if (reflectionOnlyAssemblies.ContainsKey(args.Name))
84        return reflectionOnlyAssemblies[args.Name];
85      else
86        return Assembly.ReflectionOnlyLoad(args.Name);
87    }
88
89
90    /// <summary>
91    /// Init first clears all internal datastructures (including plugin lists)
92    /// 1. All assemblies in the plugins directory are loaded into the reflection only context.
93    /// 2. The validator checks if all necessary files for each plugin are available.
94    /// 3. The validator checks if all declared plugin assemblies can be loaded.
95    /// 4. The validator builds the tree of plugin descriptions (dependencies)
96    /// 5. The validator checks if there are any cycles in the plugin dependency graph and disables plugin with circular dependencies
97    /// 6. The validator checks for each plugin if any dependency is disabled.
98    /// 7. All plugins that are not disabled are loaded into the execution context.
99    /// 8. Each loaded plugin (all assemblies) is searched for a types that implement IPlugin
100    ///    then one instance of each IPlugin type is activated and the OnLoad hook is called.
101    /// 9. All types implementing IApplication are discovered
102    /// </summary>
103    internal void DiscoverAndCheckPlugins() {
104      pluginDependencies.Clear();
105
106      IEnumerable<Assembly> reflectionOnlyAssemblies = ReflectionOnlyLoadDlls(PluginDir);
107      IEnumerable<PluginDescription> pluginDescriptions = GatherPluginDescriptions(reflectionOnlyAssemblies);
108      CheckPluginFiles(pluginDescriptions);
109
110      // check if all plugin assemblies can be loaded
111      CheckPluginAssemblies(pluginDescriptions);
112
113      // a full list of plugin descriptions is available now we can build the dependency tree
114      BuildDependencyTree(pluginDescriptions);
115
116      // check for dependency cycles
117      CheckPluginDependencyCycles(pluginDescriptions);
118
119      // recursively check if all necessary plugins are available and not disabled
120      // disable plugins with missing or disabled dependencies
121      CheckPluginDependencies(pluginDescriptions);
122
123      // mark all plugins as enabled that were not disabled in CheckPluginFiles, CheckPluginAssemblies,
124      // CheckCircularDependencies, or CheckPluginDependencies
125      foreach (var desc in pluginDescriptions)
126        if (desc.PluginState != PluginState.Disabled)
127          desc.Enable();
128
129      // test full loading (in contrast to reflection only loading) of plugins
130      // disables plugins that are not loaded correctly
131      LoadPlugins(pluginDescriptions);
132
133      plugins = pluginDescriptions;
134      DiscoverApplications();
135    }
136
137    private void DiscoverApplications() {
138      applications = new List<ApplicationDescription>();
139
140      foreach (IApplication application in GetApplications()) {
141        Type appType = application.GetType();
142        ApplicationAttribute attr = (from x in appType.GetCustomAttributes(typeof(ApplicationAttribute), false)
143                                     select (ApplicationAttribute)x).Single();
144        var declaringPlugin = GetDeclaringPlugin(appType, plugins);
145        ApplicationDescription info = new ApplicationDescription();
146        info.Name = application.Name;
147        info.Version = declaringPlugin.Version;
148        info.Description = application.Description;
149        info.AutoRestart = attr.RestartOnErrors;
150        info.DeclaringAssemblyName = appType.Assembly.GetName().Name;
151        info.DeclaringTypeName = appType.Namespace + "." + application.GetType().Name;
152
153        applications.Add(info);
154      }
155    }
156
157    private static IEnumerable<IApplication> GetApplications() {
158      return from asm in AppDomain.CurrentDomain.GetAssemblies()
159             from t in asm.GetTypes()
160             where typeof(IApplication).IsAssignableFrom(t) &&
161               !t.IsAbstract && !t.IsInterface && !t.HasElementType
162             select (IApplication)Activator.CreateInstance(t);
163    }
164
165    private IEnumerable<Assembly> ReflectionOnlyLoadDlls(string baseDir) {
166      List<Assembly> assemblies = new List<Assembly>();
167      // recursively load .dll files in subdirectories
168      foreach (string dirName in Directory.GetDirectories(baseDir)) {
169        assemblies.AddRange(ReflectionOnlyLoadDlls(dirName));
170      }
171      // try to load each .dll file in the plugin directory into the reflection only context
172      foreach (string filename in Directory.GetFiles(baseDir, "*.dll")) {
173        try {
174          Assembly asm = Assembly.ReflectionOnlyLoadFrom(filename);
175          RegisterLoadedAssembly(asm);
176          assemblies.Add(asm);
177        }
178        catch (BadImageFormatException) { } // just ignore the case that the .dll file is not a CLR assembly (e.g. a native dll)
179        catch (FileLoadException) { }
180        catch (SecurityException) { }
181        catch (ReflectionTypeLoadException) { } // referenced assemblies are missing
182      }
183      return assemblies;
184    }
185
186    /// <summary>
187    /// Checks if all plugin assemblies can be loaded. If an assembly can't be loaded the plugin is disabled.
188    /// </summary>
189    /// <param name="pluginDescriptions"></param>
190    private void CheckPluginAssemblies(IEnumerable<PluginDescription> pluginDescriptions) {
191      foreach (var desc in pluginDescriptions.Where(x => x.PluginState != PluginState.Disabled)) {
192        try {
193          var missingAssemblies = new List<string>();
194          foreach (var asmLocation in desc.AssemblyLocations) {
195            // the assembly must have been loaded in ReflectionOnlyDlls
196            // so we simply determine the name of the assembly and try to find it in the cache of loaded assemblies
197            var asmName = AssemblyName.GetAssemblyName(asmLocation);
198            if (!reflectionOnlyAssemblies.ContainsKey(asmName.FullName)) {
199              missingAssemblies.Add(asmName.FullName);
200            }
201          }
202          if (missingAssemblies.Count > 0) {
203            StringBuilder errorStrBuiler = new StringBuilder();
204            errorStrBuiler.AppendLine("Missing assemblies:");
205            foreach (string missingAsm in missingAssemblies) {
206              errorStrBuiler.AppendLine(missingAsm);
207            }
208            desc.Disable(errorStrBuiler.ToString());
209          }
210        }
211        catch (BadImageFormatException ex) {
212          // disable the plugin
213          desc.Disable("Problem while loading plugin assemblies:" + Environment.NewLine + "BadImageFormatException: " + ex.Message);
214        }
215        catch (FileNotFoundException ex) {
216          // disable the plugin
217          desc.Disable("Problem while loading plugin assemblies:" + Environment.NewLine + "FileNotFoundException: " + ex.Message);
218        }
219        catch (FileLoadException ex) {
220          // disable the plugin
221          desc.Disable("Problem while loading plugin assemblies:" + Environment.NewLine + "FileLoadException: " + ex.Message);
222        }
223        catch (ArgumentException ex) {
224          // disable the plugin
225          desc.Disable("Problem while loading plugin assemblies:" + Environment.NewLine + "ArgumentException: " + ex.Message);
226        }
227        catch (SecurityException ex) {
228          // disable the plugin
229          desc.Disable("Problem while loading plugin assemblies:" + Environment.NewLine + "SecurityException: " + ex.Message);
230        }
231      }
232    }
233
234
235    // find all types implementing IPlugin in the reflectionOnlyAssemblies and create a list of plugin descriptions
236    // the dependencies in the plugin descriptions are not yet set correctly because we need to create
237    // the full list of all plugin descriptions first
238    private IEnumerable<PluginDescription> GatherPluginDescriptions(IEnumerable<Assembly> assemblies) {
239      List<PluginDescription> pluginDescriptions = new List<PluginDescription>();
240      foreach (Assembly assembly in assemblies) {
241        // GetExportedTypes throws FileNotFoundException when a referenced assembly
242        // of the current assembly is missing.
243        try {
244          // if there is a type that implements IPlugin
245          // use AssemblyQualifiedName to compare the types because we can't directly
246          // compare ReflectionOnly types and execution types
247          var assemblyPluginDescriptions = from t in assembly.GetExportedTypes()
248                                           where !t.IsAbstract && t.GetInterfaces().Any(x => x.AssemblyQualifiedName == typeof(IPlugin).AssemblyQualifiedName)
249                                           select GetPluginDescription(t);
250          pluginDescriptions.AddRange(assemblyPluginDescriptions);
251        }
252        // ignore exceptions. Just don't yield a plugin description when an exception is thrown
253        catch (FileNotFoundException) {
254        }
255        catch (FileLoadException) {
256        }
257        catch (InvalidPluginException) {
258        }
259        catch (TypeLoadException) {
260        }
261        catch (MissingMemberException) {
262        }
263      }
264      return pluginDescriptions;
265    }
266
267    /// <summary>
268    /// Extracts plugin information for this type.
269    /// Reads plugin name, list and type of files and dependencies of the plugin. This information is necessary for
270    /// plugin dependency checking before plugin activation.
271    /// </summary>
272    /// <param name="pluginType"></param>
273    private PluginDescription GetPluginDescription(Type pluginType) {
274
275      string pluginName, pluginDescription, pluginVersion;
276      string contactName, contactAddress;
277      GetPluginMetaData(pluginType, out pluginName, out pluginDescription, out pluginVersion);
278      GetPluginContactMetaData(pluginType, out contactName, out contactAddress);
279      var pluginFiles = GetPluginFilesMetaData(pluginType);
280      var pluginDependencies = GetPluginDependencyMetaData(pluginType);
281
282      // minimal sanity check of the attribute values
283      if (!string.IsNullOrEmpty(pluginName) &&
284          pluginFiles.Count() > 0 &&                                 // at least one file
285          pluginFiles.Any(f => f.Type == PluginFileType.Assembly)) { // at least one assembly
286        // create a temporary PluginDescription that contains the attribute values
287        PluginDescription info = new PluginDescription();
288        info.Name = pluginName;
289        info.Description = pluginDescription;
290        info.Version = new Version(pluginVersion);
291        info.ContactName = contactName;
292        info.ContactEmail = contactAddress;
293        info.LicenseText = ReadLicenseFiles(pluginFiles);
294        info.AddFiles(pluginFiles);
295
296        this.pluginDependencies[info] = pluginDependencies;
297        return info;
298      } else {
299        throw new InvalidPluginException("Invalid metadata in plugin " + pluginType.ToString());
300      }
301    }
302
303    private string ReadLicenseFiles(IEnumerable<PluginFile> pluginFiles) {
304      // combine the contents of all plugin files
305      var licenseFiles = from file in pluginFiles
306                         where file.Type == PluginFileType.License
307                         select file;
308      if (licenseFiles.Count() == 0) return string.Empty;
309      StringBuilder licenseTextBuilder = new StringBuilder();
310      licenseTextBuilder.AppendLine(File.ReadAllText(licenseFiles.First().Name));
311      foreach (var licenseFile in licenseFiles.Skip(1)) {
312        licenseTextBuilder.AppendLine().AppendLine(); // leave some empty space between multiple license files
313        licenseTextBuilder.AppendLine(File.ReadAllText(licenseFile.Name));
314      }
315      return licenseTextBuilder.ToString();
316    }
317
318    private static IEnumerable<PluginDependency> GetPluginDependencyMetaData(Type pluginType) {
319      // get all attributes of type PluginDependency
320      var dependencyAttributes = from attr in CustomAttributeData.GetCustomAttributes(pluginType)
321                                 where IsAttributeDataForType(attr, typeof(PluginDependencyAttribute))
322                                 select attr;
323
324      foreach (var dependencyAttr in dependencyAttributes) {
325        string name = (string)dependencyAttr.ConstructorArguments[0].Value;
326        Version version = new Version("0.0.0.0"); // default version
327        // check if version is given for now
328        // later when the constructor of PluginDependencyAttribute with only one argument has been removed
329        // this conditional can be removed as well
330        if (dependencyAttr.ConstructorArguments.Count > 1) {
331          try {
332            version = new Version((string)dependencyAttr.ConstructorArguments[1].Value); // might throw FormatException
333          }
334          catch (FormatException ex) {
335            throw new InvalidPluginException("Invalid version format of dependency " + name + " in plugin " + pluginType.ToString(), ex);
336          }
337        }
338        yield return new PluginDependency(name, version);
339      }
340    }
341
342    private static void GetPluginContactMetaData(Type pluginType, out string contactName, out string contactAddress) {
343      // get attribute of type ContactInformation if there is any
344      var contactInfoAttribute = (from attr in CustomAttributeData.GetCustomAttributes(pluginType)
345                                  where IsAttributeDataForType(attr, typeof(ContactInformationAttribute))
346                                  select attr).SingleOrDefault();
347
348      if (contactInfoAttribute != null) {
349        contactName = (string)contactInfoAttribute.ConstructorArguments[0].Value;
350        contactAddress = (string)contactInfoAttribute.ConstructorArguments[1].Value;
351      } else {
352        contactName = string.Empty;
353        contactAddress = string.Empty;
354      }
355    }
356
357    // not static because we need the PluginDir property
358    private IEnumerable<PluginFile> GetPluginFilesMetaData(Type pluginType) {
359      // get all attributes of type PluginFileAttribute
360      var pluginFileAttributes = from attr in CustomAttributeData.GetCustomAttributes(pluginType)
361                                 where IsAttributeDataForType(attr, typeof(PluginFileAttribute))
362                                 select attr;
363      foreach (var pluginFileAttribute in pluginFileAttributes) {
364        string pluginFileName = (string)pluginFileAttribute.ConstructorArguments[0].Value;
365        PluginFileType fileType = (PluginFileType)pluginFileAttribute.ConstructorArguments[1].Value;
366        yield return new PluginFile(Path.GetFullPath(Path.Combine(PluginDir, pluginFileName)), fileType);
367      }
368    }
369
370    private static void GetPluginMetaData(Type pluginType, out string pluginName, out string pluginDescription, out string pluginVersion) {
371      // there must be a single attribute of type PluginAttribute
372      var pluginMetaDataAttr = (from attr in CustomAttributeData.GetCustomAttributes(pluginType)
373                                where IsAttributeDataForType(attr, typeof(PluginAttribute))
374                                select attr).Single();
375
376      pluginName = (string)pluginMetaDataAttr.ConstructorArguments[0].Value;
377
378      // default description and version
379      pluginVersion = "0.0.0.0";
380      pluginDescription = string.Empty;
381      if (pluginMetaDataAttr.ConstructorArguments.Count() == 2) {
382        // if two arguments are given the second argument is the version
383        pluginVersion = (string)pluginMetaDataAttr.ConstructorArguments[1].Value;
384      } else if (pluginMetaDataAttr.ConstructorArguments.Count() == 3) {
385        // if three arguments are given the second argument is the description and the third is the version
386        pluginDescription = (string)pluginMetaDataAttr.ConstructorArguments[1].Value;
387        pluginVersion = (string)pluginMetaDataAttr.ConstructorArguments[2].Value;
388      }
389    }
390
391    private static bool IsAttributeDataForType(CustomAttributeData attributeData, Type attributeType) {
392      return attributeData.Constructor.DeclaringType.AssemblyQualifiedName == attributeType.AssemblyQualifiedName;
393    }
394
395    // builds a dependency tree of all plugin descriptions
396    // searches matching plugin descriptions based on the list of dependency names for each plugin
397    // and sets the dependencies in the plugin descriptions
398    private void BuildDependencyTree(IEnumerable<PluginDescription> pluginDescriptions) {
399      foreach (var desc in pluginDescriptions) {
400        var missingDependencies = new List<PluginDependency>();
401        foreach (var dependency in pluginDependencies[desc]) {
402          var matchingDescriptions = from availablePlugin in pluginDescriptions
403                                     where availablePlugin.Name == dependency.Name
404                                     where IsCompatiblePluginVersion(availablePlugin.Version, dependency.Version)
405                                     select availablePlugin;
406          if (matchingDescriptions.Count() > 0) {
407            desc.AddDependency(matchingDescriptions.Single());
408          } else {
409            missingDependencies.Add(dependency);
410          }
411        }
412        // no plugin description that matches the dependencies are available => plugin is disabled
413        if (missingDependencies.Count > 0) {
414          StringBuilder errorStrBuilder = new StringBuilder();
415          errorStrBuilder.AppendLine("Missing dependencies:");
416          foreach (var missingDep in missingDependencies) {
417            errorStrBuilder.AppendLine(missingDep.Name + " " + missingDep.Version);
418          }
419          desc.Disable(errorStrBuilder.ToString());
420        }
421      }
422    }
423
424    /// <summary>
425    /// Checks if version <paramref name="available"/> is compatible to version <paramref name="requested"/>.
426    /// Note: the compatibility relation is not bijective.
427    /// Compatibility rules:
428    ///  * major and minor number must be the same
429    ///  * build and revision number of <paramref name="available"/> must be larger or equal to <paramref name="requested"/>.
430    /// </summary>
431    /// <param name="available">The available version which should be compared to <paramref name="requested"/>.</param>
432    /// <param name="requested">The requested version that must be matched.</param>
433    /// <returns></returns>
434    private bool IsCompatiblePluginVersion(Version available, Version requested) {
435      // this condition must be removed after all plugins have been updated to declare plugin and dependency versions
436      if (
437        (requested.Major == 0 && requested.Minor == 0) ||
438        (available.Major == 0 && available.Minor == 0)) return true;
439      return
440        available.Major == requested.Major &&
441        available.Minor == requested.Minor &&
442        available.Build >= requested.Build &&
443        available.Revision >= requested.Revision;
444    }
445
446    private void CheckPluginDependencyCycles(IEnumerable<PluginDescription> pluginDescriptions) {
447      foreach (var plugin in pluginDescriptions) {
448        // if the plugin is not disabled check if there are cycles
449        if (plugin.PluginState != PluginState.Disabled && HasCycleInDependencies(plugin, plugin.Dependencies)) {
450          plugin.Disable("Dependency graph has a cycle.");
451        }
452      }
453    }
454
455    private bool HasCycleInDependencies(PluginDescription plugin, IEnumerable<PluginDescription> pluginDependencies) {
456      foreach (var dep in pluginDependencies) {
457        // if one of the dependencies is the original plugin we found a cycle and can return
458        // if the dependency is already disabled we can ignore the cycle detection because we will disable the plugin anyway
459        // if following one of the dependencies recursively leads to a cycle then we also return
460        if (dep == plugin || dep.PluginState == PluginState.Disabled || HasCycleInDependencies(plugin, dep.Dependencies)) return true;
461      }
462      // no cycle found and none of the direct and indirect dependencies is disabled
463      return false;
464    }
465
466    private void CheckPluginDependencies(IEnumerable<PluginDescription> pluginDescriptions) {
467      foreach (PluginDescription pluginDescription in pluginDescriptions.Where(x => x.PluginState != PluginState.Disabled)) {
468        List<PluginDescription> disabledPlugins = new List<PluginDescription>();
469        if (IsAnyDependencyDisabled(pluginDescription, disabledPlugins)) {
470          StringBuilder errorStrBuilder = new StringBuilder();
471          errorStrBuilder.AppendLine("Dependencies are disabled:");
472          foreach (var disabledPlugin in disabledPlugins) {
473            errorStrBuilder.AppendLine(disabledPlugin.Name + " " + disabledPlugin.Version);
474          }
475          pluginDescription.Disable(errorStrBuilder.ToString());
476        }
477      }
478    }
479
480
481    private bool IsAnyDependencyDisabled(PluginDescription descr, List<PluginDescription> disabledPlugins) {
482      if (descr.PluginState == PluginState.Disabled) {
483        disabledPlugins.Add(descr);
484        return true;
485      }
486      foreach (PluginDescription dependency in descr.Dependencies) {
487        IsAnyDependencyDisabled(dependency, disabledPlugins);
488      }
489      return disabledPlugins.Count > 0;
490    }
491
492    private void LoadPlugins(IEnumerable<PluginDescription> pluginDescriptions) {
493      // load all loadable plugins (all dependencies available) into the execution context
494      foreach (var desc in PluginDescriptionIterator.IterateDependenciesBottomUp(pluginDescriptions
495                                                                                .Where(x => x.PluginState != PluginState.Disabled))) {
496        List<Type> types = new List<Type>();
497        foreach (string assemblyLocation in desc.AssemblyLocations) {
498          // now load the assemblies into the execution context
499          var asm = Assembly.LoadFrom(assemblyLocation);
500          foreach (Type t in asm.GetTypes()) {
501            if (typeof(IPlugin).IsAssignableFrom(t)) {
502              types.Add(t);
503            }
504          }
505        }
506
507        foreach (Type pluginType in types) {
508          if (!pluginType.IsAbstract && !pluginType.IsInterface && !pluginType.HasElementType) {
509            IPlugin plugin = (IPlugin)Activator.CreateInstance(pluginType);
510            plugin.OnLoad();
511            OnPluginLoaded(new PluginInfrastructureEventArgs(desc));
512          }
513        }
514        desc.Load();
515      }
516    }
517
518    // checks if all declared plugin files are actually available and disables plugins with missing files
519    private void CheckPluginFiles(IEnumerable<PluginDescription> pluginDescriptions) {
520      foreach (PluginDescription desc in pluginDescriptions) {
521        IEnumerable<string> missingFiles;
522        if (ArePluginFilesMissing(desc, out missingFiles)) {
523          StringBuilder errorStrBuilder = new StringBuilder();
524          errorStrBuilder.AppendLine("Missing files:");
525          foreach (string fileName in missingFiles) {
526            errorStrBuilder.AppendLine(fileName);
527          }
528          desc.Disable(errorStrBuilder.ToString());
529        }
530      }
531    }
532
533    private bool ArePluginFilesMissing(PluginDescription pluginDescription, out IEnumerable<string> missingFiles) {
534      List<string> missing = new List<string>();
535      foreach (string filename in pluginDescription.Files.Select(x => x.Name)) {
536        if (!FileLiesInDirectory(PluginDir, filename) ||
537          !File.Exists(filename)) {
538          missing.Add(filename);
539        }
540      }
541      missingFiles = missing;
542      return missing.Count > 0;
543    }
544
545    private static bool FileLiesInDirectory(string dir, string fileName) {
546      var basePath = Path.GetFullPath(dir);
547      return Path.GetFullPath(fileName).StartsWith(basePath);
548    }
549
550    private PluginDescription GetDeclaringPlugin(Type appType, IEnumerable<PluginDescription> plugins) {
551      return (from p in plugins
552              from asmLocation in p.AssemblyLocations
553              where Path.GetFullPath(asmLocation).Equals(Path.GetFullPath(appType.Assembly.Location), StringComparison.CurrentCultureIgnoreCase)
554              select p).Single();
555    }
556
557    // register assembly in the assembly cache for the ReflectionOnlyAssemblyResolveEvent
558    private void RegisterLoadedAssembly(Assembly asm) {
559      reflectionOnlyAssemblies.Add(asm.FullName, asm);
560      reflectionOnlyAssemblies.Add(asm.GetName().Name, asm); // add short name
561    }
562
563    private void OnPluginLoaded(PluginInfrastructureEventArgs e) {
564      if (PluginLoaded != null)
565        PluginLoaded(this, e);
566    }
567
568    /// <summary>
569    /// Initializes the life time service with an infinite lease time.
570    /// </summary>
571    /// <returns><c>null</c>.</returns>
572    public override object InitializeLifetimeService() {
573      return null;
574    }
575  }
576}
Note: See TracBrowser for help on using the repository browser.