private static void AddToAppcationPart(ApplicationPartManager manager, Assembly assembly) { var partFactory = ApplicationPartFactory.GetApplicationPartFactory(assembly); var applicationParts = partFactory.GetApplicationParts(assembly); foreach (var part in applicationParts) { if (part is AssemblyPart assemblyPart) { manager.ApplicationParts.Add(new WidgetAssemblyPart(assembly)); } else if (part is CompiledRazorAssemblyPart) { manager.ApplicationParts.Add(new WidgetRazorAssemblyPart(new CompiledRazorAssemblyPart(assembly))); } else { manager.ApplicationParts.Add(part); } } // load related assemblies var relatedAssemblies = RelatedAssemblyAttribute.GetRelatedAssemblies(assembly, true); foreach (var item in relatedAssemblies) { AddToAppcationPart(manager, item); } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); var rootDir = new DirectoryInfo(_hostingEnvironment.ContentRootPath).Parent; var dir = new DirectoryInfo(Path.Combine(rootDir.ToString(), "Plugin1", "bin", "Debug", "netstandard2.0")); foreach (var file in dir.GetFileSystemInfos("*.dll", SearchOption.AllDirectories)) { Assembly assembly; try { assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(file.FullName); } catch (FileLoadException) { // Get loaded assembly. This assembly might be loaded assembly = Assembly.Load(new AssemblyName(Path.GetFileNameWithoutExtension(file.Name))); if (assembly == null) { throw; } } } services.Configure <RazorViewEngineOptions>( options => { options.ViewLocationExpanders.Add(new ThemeableViewLocationExpander()); }); var mvcBuilder = services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); mvcBuilder.AddRazorOptions(o => { o.AdditionalCompilationReferences.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("Plugin1")).Location)); }); var pluginAssembly = Assembly.Load(new AssemblyName("Plugin1")); var partFactory = ApplicationPartFactory.GetApplicationPartFactory(pluginAssembly); foreach (var part in partFactory.GetApplicationParts(pluginAssembly)) { mvcBuilder.PartManager.ApplicationParts.Add(part); } var relatedAssemblies = RelatedAssemblyAttribute.GetRelatedAssemblies(pluginAssembly, throwOnError: true); foreach (var assembly in relatedAssemblies) { partFactory = ApplicationPartFactory.GetApplicationPartFactory(assembly); foreach (var part in partFactory.GetApplicationParts(assembly)) { mvcBuilder.PartManager.ApplicationParts.Add(part); } } }
public void ConfigureServices(IServiceCollection services) { var builder = services .AddMvc() .ConfigureApplicationPartManager(manager => manager.ApplicationParts.Clear()) .AddApplicationPart(typeof(TimeScheduleController).GetTypeInfo().Assembly) .ConfigureApplicationPartManager(manager => { manager.ApplicationParts.Add(new TypesPart( typeof(AnotherController), typeof(ComponentFromServicesViewComponent), typeof(InServicesTagHelper))); var relatedAssenbly = RelatedAssemblyAttribute .GetRelatedAssemblies(GetType().Assembly, throwOnError: true) .SingleOrDefault(); foreach (var part in CompiledRazorAssemblyApplicationPartFactory.GetDefaultApplicationParts(relatedAssenbly)) { manager.ApplicationParts.Add(part); } }) .AddControllersAsServices() .AddViewComponentsAsServices() .AddTagHelpersAsServices() .SetCompatibilityVersion(CompatibilityVersion.Latest); services.AddTransient <QueryValueService>(); services.AddTransient <ValueService>(); services.AddHttpContextAccessor(); }
public static IMvcBuilder ConfigureAsRazorModule(this IMvcBuilder builder) { var frame = new StackFrame(1); var method = frame.GetMethod(); var type = method.DeclaringType; if (type == null) { return(builder); } var moduleAssembly = type.Assembly; builder.ConfigureApplicationPartManager(apm => { apm.ApplicationParts.Add(new AssemblyPart(moduleAssembly)); var relatedAssemblies = RelatedAssemblyAttribute.GetRelatedAssemblies(moduleAssembly, false); foreach (var relatedAssembly in relatedAssemblies) { var partFactory = ApplicationPartFactory.GetApplicationPartFactory(relatedAssembly); foreach (var part in partFactory.GetApplicationParts(relatedAssembly)) { apm.ApplicationParts.Add(part); } } }); return(builder); }
public static IMvcBuilder AddModularityApplicationParts(this IMvcBuilder mvcBuilder) { var modularity = ModularityBuilder.Get(); foreach (var area in modularity.Areas) { foreach (ModularityModule module in area.Modules) { var partFactory = ApplicationPartFactory.GetApplicationPartFactory(module.Assembly); foreach (var part in partFactory.GetApplicationParts(module.Assembly)) { mvcBuilder.PartManager.ApplicationParts.Add(part); } var relatedAssemblies = RelatedAssemblyAttribute.GetRelatedAssemblies(module.Assembly, throwOnError: false); foreach (var relatedAssembly in relatedAssemblies) { partFactory = ApplicationPartFactory.GetApplicationPartFactory(relatedAssembly); foreach (var part in partFactory.GetApplicationParts(relatedAssembly)) { mvcBuilder.PartManager.ApplicationParts.Add(part); } } } } return(mvcBuilder); }
/// <summary> /// Adds a Kerykeion built default Identity pages UI. /// </summary> /// <returns> /// A KerykeionCmsBuilder that can be used to further configure the KerykeionCms services. /// </returns> public virtual KerykeionCmsBuilder AddKerykeionIdentityUI() { var kerykeionCmsUIAssembly = typeof(RegisterModel).Assembly; var kerykeionIdentityUIrelatedAssembly = RelatedAssemblyAttribute.GetRelatedAssemblies(kerykeionCmsUIAssembly, throwOnError: true).FirstOrDefault(a => a.FullName.Contains("KerykeionIdentityUI.Views", StringComparison.OrdinalIgnoreCase)); Services.AddMvc() .ConfigureApplicationPartManager(apm => { apm.ApplicationParts.Remove(apm.ApplicationParts.FirstOrDefault(p => p.Name.Equals("KerykeionLoginUI", StringComparison.OrdinalIgnoreCase))); apm.ApplicationParts.Remove(apm.ApplicationParts.FirstOrDefault(p => p.Name.Equals("KerykeionLoginUI.Views", StringComparison.OrdinalIgnoreCase))); apm.ApplicationParts.Remove(apm.ApplicationParts.FirstOrDefault(p => p.Name.Equals("KerykeionLoginUI.Views", StringComparison.OrdinalIgnoreCase))); }).AddApplicationPart(kerykeionIdentityUIrelatedAssembly); IdentityBuilder.AddDefaultUI(); Services.ConfigureApplicationCookie(options => { options.LoginPath = "/Identity/Account/Login"; options.AccessDeniedPath = "/Identity/Account/AccessDenied"; options.SlidingExpiration = true; }); return(this); }
private static void AddApplicationPart(IMvcCoreBuilder mvcCoreBuilder, Assembly assembly, string systemName, string filename) { try { //we can now register the plugin definition Log.Information("Adding to ApplicationParts: '{0}'", systemName); mvcCoreBuilder.AddApplicationPart(assembly); var relatedAssemblies = RelatedAssemblyAttribute.GetRelatedAssemblies(assembly, throwOnError: false); foreach (var relatedAssembly in relatedAssemblies) { var applicationPartFactory = ApplicationPartFactory.GetApplicationPartFactory(relatedAssembly); foreach (var part in applicationPartFactory.GetApplicationParts(relatedAssembly)) { mvcCoreBuilder.PartManager.ApplicationParts.Add(part); } } } catch (Exception ex) { Log.Error(ex, "PluginManager"); throw new InvalidOperationException($"The plugin directory for the {systemName} file exists in a folder outside of the allowed grandnode folder hierarchy - exception because of {filename} - exception: {ex.Message}"); } }
public void ConfigureServices(IServiceCollection services) { var mvcBuilder = services .AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); foreach (var dir in Directory.GetDirectories(Path.Combine(AppContext.BaseDirectory, "plugins"))) { var pluginName = Path.GetFileName(dir); var plugin = PluginLoader.CreateFromAssemblyFile(Path.Combine(dir, pluginName + ".dll")); var pluginAssembly = plugin.LoadDefaultAssembly(); Console.WriteLine($"Loading application parts from plugin {pluginName}"); // This loads MVC application parts from plugin assemblies var partFactory = ApplicationPartFactory.GetApplicationPartFactory(pluginAssembly); foreach (var part in partFactory.GetApplicationParts(pluginAssembly)) { Console.WriteLine($"* {part.Name}"); mvcBuilder.PartManager.ApplicationParts.Add(part); } // This piece finds and loads related parts, such as MvcAppPlugin1.Views.dll. var relatedAssemblies = RelatedAssemblyAttribute.GetRelatedAssemblies(pluginAssembly, throwOnError: true); foreach (var assembly in relatedAssemblies) { partFactory = ApplicationPartFactory.GetApplicationPartFactory(assembly); foreach (var part in partFactory.GetApplicationParts(assembly)) { Console.WriteLine($" * {part.Name}"); mvcBuilder.PartManager.ApplicationParts.Add(part); } } } }
private static void AddApplicationPart(IMvcBuilder mvcBuilder, Assembly assembly) { try { var partFactory = ApplicationPartFactory.GetApplicationPartFactory(assembly); foreach (var part in partFactory.GetApplicationParts(assembly)) { mvcBuilder.PartManager.ApplicationParts.Add(part); } var relatedAssemblies = RelatedAssemblyAttribute.GetRelatedAssemblies(assembly, throwOnError: false); foreach (var relatedAssembly in relatedAssemblies) { partFactory = ApplicationPartFactory.GetApplicationPartFactory(relatedAssembly); foreach (var part in partFactory.GetApplicationParts(relatedAssembly)) { mvcBuilder.PartManager.ApplicationParts.Add(part); } } } catch (Exception ex) { ex.Message.ToString(); } }
private static void AddApplicationPart(IMvcBuilder mvcBuilder, Assembly assembly) { AddApplicationPart(ref mvcBuilder, assembly); var relatedAssemblies = RelatedAssemblyAttribute.GetRelatedAssemblies(assembly, throwOnError: false); foreach (var relatedAssembly in relatedAssemblies) { AddApplicationPart(ref mvcBuilder, assembly); } }
private static IEnumerable <ApplicationPart> GetAdditionalParts() { var thisAssembly = typeof(AzureADB2CAuthenticationBuilderExtensions).Assembly; var relatedAssemblies = RelatedAssemblyAttribute.GetRelatedAssemblies(thisAssembly, throwOnError: true); foreach (var reference in relatedAssemblies) { yield return(new CompiledRazorAssemblyPart(reference)); } }
private static IEnumerable <ApplicationPart> GetAdditionalParts() { var thisAssembly = typeof(D2LOAuth2AccountControllerFeatureProvider).Assembly; var relatedAssemblies = RelatedAssemblyAttribute.GetRelatedAssemblies(thisAssembly, throwOnError: true); foreach (var reference in relatedAssemblies) { yield return(new CompiledRazorAssemblyPart(reference)); } }
public RazorTemplateEngineV2() { var thisAssembly = Assembly.GetExecutingAssembly(); var viewAssembly = RelatedAssemblyAttribute.GetRelatedAssemblies(thisAssembly, false).Single(); var razorCompiledItems = new RazorCompiledItemLoader().LoadItems(viewAssembly); foreach (var item in razorCompiledItems) { _razorCompiledItems.Add(item.Identifier, item); } }
public void GetRelatedAssemblies_Noops_ForDynamicAssemblies() { // Arrange var name = new AssemblyName($"DynamicAssembly-{Guid.NewGuid()}"); var assembly = AssemblyBuilder.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndCollect); // Act var result = RelatedAssemblyAttribute.GetRelatedAssemblies(assembly, throwOnError: true); // Assert Assert.Empty(result); }
private static IEnumerable <Assembly> GetAssemblyClosure(Assembly assembly) { yield return(assembly); var relatedAssemblies = RelatedAssemblyAttribute.GetRelatedAssemblies(assembly, throwOnError: false) .OrderBy(assembly => assembly.FullName, StringComparer.Ordinal); foreach (var relatedAssembly in relatedAssemblies) { yield return(relatedAssembly); } }
public void GetRelatedAssemblies_ThrowsIfAssemblyCannotBeFound() { // Arrange var assemblyPath = Path.Combine(AssemblyDirectory, "MyAssembly.dll"); var assembly = new TestAssembly { AttributeAssembly = "DoesNotExist" }; // Act & Assert Assert.Throws <FileNotFoundException>(() => RelatedAssemblyAttribute.GetRelatedAssemblies(assembly, throwOnError: true)); }
public void GetRelatedAssemblies_ThrowsIfRelatedAttributeReferencesSelf() { // Arrange var expected = "RelatedAssemblyAttribute specified on MyAssembly cannot be self referential."; var assembly = new TestAssembly { AttributeAssembly = "MyAssembly" }; // Act & Assert var ex = Assert.Throws <InvalidOperationException>(() => RelatedAssemblyAttribute.GetRelatedAssemblies(assembly, throwOnError: true)); Assert.Equal(expected, ex.Message); }
private static void AddRelatedParts(IdentityBuilder builder) { builder.Services.AddMvc().ConfigureApplicationPartManager( partManager => { foreach (ApplicationPart applicationPart in RelatedAssemblyAttribute .GetRelatedAssemblies(typeof(ServiceCollectionExtensions).Assembly, true).SelectMany( CompiledRazorAssemblyApplicationPartFactory.GetDefaultApplicationParts)) { partManager.ApplicationParts.Add(applicationPart); } }); }
public static void AddParts(this Assembly assembly, IMvcBuilder mvcBuilder) { mvcBuilder.ConfigureApplicationPartManager(manager => { var parts = manager.ApplicationParts; AddParts(parts, assembly); foreach (var reference in RelatedAssemblyAttribute.GetRelatedAssemblies(assembly, false)) { AddParts(parts, reference); } }); }
/// <summary> /// Get all the application parts that are available in the published project /// What is application part? https://docs.microsoft.com/en-us/aspnet/core/mvc/advanced/app-parts?view=aspnetcore-5.0 /// </summary> /// <returns></returns> public static List <ApplicationPart> GetApplicationParts() { // In ASP.NET Core MVC, the main entry assembly has ApplicationPartAttibute using which the RCL libraries // are identified and their application parts are loaded. This attibute is added only when the project sdk // is set to Microsoft.NET.Sdk.Web // But for other types of projects whose sdk is generally Microsoft.NET.Sdk there won't be any ApplicationPartAttribute added // Hence we need to look over all the assemblies and see if they are RCL assemblies // Thanks to ASP.NET Core source code https://github.com/dotnet/aspnetcore/tree/v5.0.5/src/Mvc/Mvc.Core/src/ApplicationParts var allAssemblies = AppDomain.CurrentDomain.GetAssemblies().ToList(); // To support Azure Functions var binAssemblies = GetAllBinDirectoryAssemblies(); if (binAssemblies?.Any() ?? false) { allAssemblies.AddRange(binAssemblies); } var applicationParts = new List <ApplicationPart>(); var seenAssemblies = new HashSet <Assembly>(); foreach (var assembly in allAssemblies) { if (!seenAssemblies.Add(assembly)) { continue; } // RCL libraries are decorated with RelatedAssemblyAttribute for the compiled Views assembly // Example: ExampleRazorTemplatesLibrary.dll will contain [assembly: RelatedAssembly("ExampleRazorTemplatesLibrary.Views")] var relatedAssemblies = RelatedAssemblyAttribute.GetRelatedAssemblies(assembly, false); foreach (var relatedAssembly in relatedAssemblies) { Logger.Log($"Adding ApplicationParts for pre-compiled view assembly {relatedAssembly.FullName}"); // we can safely say that this assembly is auto generated pre compiled RCL if (relatedAssembly.FullName?.Contains(".Views,") ?? false) { AddApplicationParts(ref applicationParts, relatedAssembly); } } if (relatedAssemblies.Any()) { Logger.Log($"Adding ApplicationParts for main assembly {assembly.GetName()}"); // For View Component Feature and others to work, we need to add the application part of the main RCL assembly. AddApplicationParts(ref applicationParts, assembly); } } return(applicationParts); }
public void GetAssemblyLocation_CodeBase_HasPoundCharacterDOSPath() { var destination = Path.Combine(AssemblyDirectory, "RelatedAssembly.dll"); var expected = @"C:\#NIN\dotnetcore\tryx\try1.dll"; var assembly = new TestAssembly { CodeBaseSettable = "file:///C:/#NIN/dotnetcore/tryx/try1.dll", LocationSettable = expected, }; // Act var actual = RelatedAssemblyAttribute.GetAssemblyLocation(assembly); Assert.Equal(expected, actual); }
public RazorMailerRazorEngineBuilder UseEmbeddedResourcesProject(Assembly viewAssembly) { var relatedAssembly = RelatedAssemblyAttribute.GetRelatedAssemblies(viewAssembly, false).SingleOrDefault(); if (relatedAssembly == null) { _viewAssembly = viewAssembly; return(this); } _viewAssembly = relatedAssembly; return(this); }
public void GetAssemblyLocation_UsesCodeBase() { // Arrange var destination = Path.Combine(AssemblyDirectory, "RelatedAssembly.dll"); var codeBase = "file://x:/file/Assembly.dll"; var expected = new Uri(codeBase).LocalPath; var assembly = new TestAssembly { CodeBaseSettable = codeBase, }; // Act var actual = RelatedAssemblyAttribute.GetAssemblyLocation(assembly); Assert.Equal(expected, actual); }
public void GetRelatedAssemblies_ThrowsIfAssemblyCannotBeFound() { // Arrange var expected = $"Related assembly 'DoesNotExist' specified by assembly 'MyAssembly' could not be found in the directory {AssemblyDirectory}. Related assemblies must be co-located with the specifying assemblies."; var assemblyPath = Path.Combine(AssemblyDirectory, "MyAssembly.dll"); var assembly = new TestAssembly { AttributeAssembly = "DoesNotExist" }; // Act & Assert var ex = Assert.Throws <FileNotFoundException>(() => RelatedAssemblyAttribute.GetRelatedAssemblies(assembly, throwOnError: true)); Assert.Equal(expected, ex.Message); Assert.Equal(Path.Combine(AssemblyDirectory, "DoesNotExist.dll"), ex.FileName); }
public void GetAssemblyLocation_UsesLocation_IfCodeBaseIsNotLocal() { // Arrange var destination = Path.Combine(AssemblyDirectory, "RelatedAssembly.dll"); var expected = Path.Combine(AssemblyDirectory, "Some-Dir", "Assembly.dll"); var assembly = new TestAssembly { CodeBaseSettable = "https://www.microsoft.com/test.dll", LocationSettable = expected, }; // Act var actual = RelatedAssemblyAttribute.GetAssemblyLocation(assembly); Assert.Equal(expected, actual); }
private static IEnumerable <string> GetControllerModules(IFileProvider moduleFileProvider) { var LoadedAssemblies = new List <Assembly>(); AppDomain.CurrentDomain.GetAssemblies().ToList() .ForEach(assembly => { LoadedAssemblies.Add(assembly); LoadedAssemblies.AddRange(RelatedAssemblyAttribute.GetRelatedAssemblies(assembly, throwOnError: false)); }); var LoadedAssemblyNames = LoadedAssemblies.Select(assembly => assembly.GetName().Name); var QueuedAssemblies = moduleFileProvider .GetDirectoryContents("/") .Where(file => !file.IsDirectory && file.Name.EndsWith(".dll") && !file.Name.EndsWith(".Views.dll")) .Where(file => !LoadedAssemblyNames.Contains(file.Name[0..^ 4]))
public static IMvcBuilder AddMyPlugins(this IMvcBuilder mvcBuilder, IConfiguration config) { var pluginManager = new PluginManager(); var options = config.Get <PluginOptions>(); if (options.Plugins != null) { foreach (var path in options.Plugins) { var plugin = LoadPlugin(path); if (plugin != null) { try { var pluginAssembly = plugin.LoadDefaultAssembly(); AddParts(mvcBuilder, pluginAssembly); foreach (var relatedAssembly in RelatedAssemblyAttribute.GetRelatedAssemblies(pluginAssembly, false)) { AddParts(mvcBuilder, relatedAssembly); } pluginManager.Add(path, pluginAssembly); } catch (Exception ex) { pluginManager.LogException(path, "LoadingAssembly", ex); } } else { pluginManager.LogException(path, "LoadingPlugin", new FileNotFoundException($"Cannot find plugin at {path}")); } } } pluginManager.ConfigureServices(mvcBuilder.Services, config); mvcBuilder.Services.AddSingleton(pluginManager); return(mvcBuilder); }
public void GetRelatedAssemblies_LoadsRelatedAssembly() { // Arrange var destination = Path.Combine(AssemblyDirectory, "RelatedAssembly.dll"); var assembly = new TestAssembly { AttributeAssembly = "RelatedAssembly", }; var relatedAssembly = typeof(RelatedAssemblyPartTest).Assembly; var result = RelatedAssemblyAttribute.GetRelatedAssemblies(assembly, throwOnError: true, file => true, file => { Assert.Equal(file, destination); return(relatedAssembly); }); Assert.Equal(new[] { relatedAssembly }, result); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { var mvcBuilder = services .AddMvc() .SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_1); services.AddSingleton <IConfiguration>(Configuration); services.AddHttpClient(); services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(o => o.LoginPath = new PathString("/account/signin")); // Load and install modules. Get all module folder names inside 'Modules' folder if (Directory.Exists(Path.Combine(AppContext.BaseDirectory, "modules"))) { foreach (var dir in Directory.GetDirectories(Path.Combine(AppContext.BaseDirectory, "modules"))) { var moduleAssembly = new CustomAssemblyLoadContext().LoadFromAssemblyPath(Path.Combine(dir, Path.GetFileName(dir)) + ".dll"); Console.WriteLine($"Loading application parts from module {moduleAssembly.FullName}"); // This loads MVC application parts from module assemblies var partFactory = ApplicationPartFactory.GetApplicationPartFactory(moduleAssembly); foreach (var part in partFactory.GetApplicationParts(moduleAssembly)) { Console.WriteLine($"* {part.Name}"); mvcBuilder.PartManager.ApplicationParts.Add(part); } // This piece finds and loads related parts, such as SampleModule.Views.dll. var relatedAssemblies = RelatedAssemblyAttribute.GetRelatedAssemblies(moduleAssembly, throwOnError: true); foreach (var assembly in relatedAssemblies) { partFactory = ApplicationPartFactory.GetApplicationPartFactory(assembly); foreach (var part in partFactory.GetApplicationParts(assembly)) { Console.WriteLine($" * {part.Name}"); mvcBuilder.PartManager.ApplicationParts.Add(part); } } } } }
private static void AddApplicationPart(IMvcBuilder mvcBuilder, Assembly assembly) { var partFactory = ApplicationPartFactory.GetApplicationPartFactory(assembly); foreach (var part in partFactory.GetApplicationParts(assembly)) { mvcBuilder.PartManager.ApplicationParts.Add(part); } var relatedAssemblies = RelatedAssemblyAttribute.GetRelatedAssemblies(assembly, false); foreach (var relatedAssembly in relatedAssemblies) { partFactory = ApplicationPartFactory.GetApplicationPartFactory(relatedAssembly); foreach (var part in partFactory.GetApplicationParts(relatedAssembly)) { mvcBuilder.PartManager.ApplicationParts.Add(part); } } }