using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.IO; using System.Reflection; using System.Web.Mvc; using System.Diagnostics; namespace HLWebPluginHost.PluginLib { /// /// Gathers all view locations and registers the plugins /// public class PluginHelper { /// /// Gathers all view locations and adds them to the custom view engine /// internal static void InitializePluginsAndLoadViewLocations() { Assembly[] pluginAssemblies = GetPluginAssemblies(); List viewLocations = new List(); foreach (Assembly plugin in pluginAssemblies) { var pluginAttribute = plugin.GetCustomAttributes(typeof(HLWebPluginViewLocations), false).FirstOrDefault() as HLWebPluginViewLocations; if (pluginAttribute != null) viewLocations.AddRange(pluginAttribute.viewLocations); } //The PluginViewEngine is used to locate views in the assemlbies ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new PluginViewEngine(viewLocations.ToArray())); } /// /// Builds dynamic links defined by the plugins /// /// List of plugin links public static List GetPluginActions() { // todo: Load this links once on Application_Start() and cache them. // Currently the controller calls this everytime it renders the master page Assembly[] pluginAssemblies = GetPluginAssemblies(); List pluginLinks = new List(); foreach (Assembly plugin in pluginAssemblies) { var pluginAttribute = plugin.GetCustomAttributes(typeof(HLWebPluginViewLocations), false).FirstOrDefault() as HLWebPluginViewLocations; if (pluginAttribute.addLink) { pluginLinks.Add(new PluginAction() { Name = pluginAttribute.name, Action = pluginAttribute.action, Controller = pluginAttribute.controller }); } } return pluginLinks; } private static Assembly[] GetPluginAssemblies() { IEnumerable loadedPluginAssemblies = AppDomain.CurrentDomain.GetAssemblies().Where(a => a.GetCustomAttributes(typeof(HLWebPluginViewLocations), false).Count() > 0).AsEnumerable(); Assembly[] distinctLoadedPluginAssemblies = loadedPluginAssemblies.Distinct(new DLLComparer()).ToArray(); return distinctLoadedPluginAssemblies; } public class PluginAction { public string Name { get; set; } public string Controller { get; set; } public string Action { get; set; } } private class DLLComparer : IEqualityComparer { #region IEqualityComparer Members public bool Equals(Assembly x, Assembly y) { return x.ManifestModule.ScopeName == y.ManifestModule.ScopeName; } public int GetHashCode(Assembly obj) { return obj.ManifestModule.ScopeName.GetHashCode(); } #endregion } } }