示例#1
0
        internal static void Prepare(IHostingEnvironment env)
        {
            var tenum = DefaultAssemblyPartDiscoveryProvider.DiscoverAssemblyParts(env.ApplicationName).
                        Where(m => !m.Name.StartsWith("MvcControlsToolkit"))
                        .SelectMany(m => (m as AssemblyPart).Types).Where(m => m.IsPublic &&
                                                                          m.GetInterfaces().Contains(typeof(ITagHelpersProviderExtension)))
                        .Select(m => m.AsType());

            foreach (var x in tenum)
            {
                ITagHelpersProviderExtension curr = Activator.CreateInstance(x) as ITagHelpersProviderExtension;
                var res = GetProcessors(curr.For);
                if (res.Count == 0)
                {
                    allExtensions[curr.For] = res;
                }
                res.AddRange(curr.TagProcessors);
                var res1 = GetTemplates(curr.For);
                if (res1.Count == 0)
                {
                    allTemplates[curr.For] = res1;
                }
                res.AddRange(curr.TagProcessors);
            }
        }
        internal static void Prepare(IHostingEnvironment env)
        {
            var tenum = DefaultAssemblyPartDiscoveryProvider.DiscoverAssemblyParts(env.ApplicationName).
                        Where(m => !m.Name.StartsWith("MvcControlsToolkit"))
                        .SelectMany(m => (m as AssemblyPart).Types).Where(m => m.IsPublic &&
                                                                          m.GetCustomAttribute(typeof(MvcControlsToolkit.Core.DataAnnotations.RunTimeTypeAttribute)) != null)
                        .Select(m => m.AsType());

            if (DefaultTypes != null)
            {
                tenum = tenum.Union(DefaultTypes);
            }
            var tlist = new List <Type>();

            foreach (var t in tenum)
            {
                var st = t;
                while (st != null && st != typeof(object))
                {
                    tlist.Add(st);
                    st = st.GetTypeInfo().BaseType;
                }
            }
            int i = 0;

            InverseAllRunTimeTypes = tlist.Distinct().Select(m => new KeyValuePair <Type, int>(m, i++))
                                     .ToArray();

            AllRunTimeTypes = InverseAllRunTimeTypes
                              .ToDictionary(m => m.Key, m => m.Value);
        }
示例#3
0
        private static ApplicationPartManager GetApplicationPartManager(IServiceCollection services)
        {
            var manager = GetServiceFromCollection <ApplicationPartManager>(services);

            if (manager == null)
            {
                manager = new ApplicationPartManager();

                var environment       = GetServiceFromCollection <IHostingEnvironment>(services);
                var entryAssemblyName = environment?.ApplicationName;
                if (string.IsNullOrEmpty(entryAssemblyName))
                {
                    return(manager);
                }

                // Parts appear in the ApplicationParts collection in precedence order. The part that represents the
                // current application appears first, followed by all other parts sorted by name.
                var parts = DefaultAssemblyPartDiscoveryProvider.DiscoverAssemblyParts(entryAssemblyName)
                            .OrderBy(part => string.Equals(entryAssemblyName, part.Name, StringComparison.Ordinal) ? 0 : 1)
                            .ThenBy(part => part.Name, StringComparer.Ordinal);
                foreach (var part in parts)
                {
                    manager.ApplicationParts.Add(part);
                }
            }

            return(manager);
        }
        private static void RegisterModuleDependencies(IServiceCollection serviceCollection)
        {
            var             assemblies = DefaultAssemblyPartDiscoveryProvider.DiscoverAssemblyParts(Globals.ApplicationEntryPoint);
            List <TypeInfo> moduleServiceCollectors = new List <TypeInfo>();

            Type       moduleServiceCollectionType = typeof(IModuleConfigurator);
            MethodInfo registerServiceMethodInfo   = moduleServiceCollectionType.GetMethod("ConfigureServices");

            foreach (var assembly in assemblies)
            {
                var controllerTypes = assembly.DefinedTypes.Where(t => moduleServiceCollectionType.IsAssignableFrom(t)).ToList();

                if (controllerTypes != null && controllerTypes.Count > 0)
                {
                    moduleServiceCollectors.AddRange(controllerTypes);
                }
            }

            if (moduleServiceCollectors.Count > 0)
            {
                foreach (var serviceCollectorType in moduleServiceCollectors)
                {
                    var obj = Activator.CreateInstance(serviceCollectorType);
                    registerServiceMethodInfo.Invoke(obj, new object[] { serviceCollection });
                }
            }
        }
        private static IEnumerable <Assembly> GetCandidateAssemblies(IHostingEnvironment environment)
        {
            var parts = DefaultAssemblyPartDiscoveryProvider.DiscoverAssemblyParts(environment.ApplicationName);

            return(parts
                   .OfType <AssemblyPart>()
                   .Select(p => p.Assembly)
                   .ToArray());
        }
示例#6
0
        public static void Main(string[] args)
        {
            var parts = DefaultAssemblyPartDiscoveryProvider.DiscoverAssemblyParts("WebApplication23");

            foreach (var item in parts)
            {
                System.Console.WriteLine(item.Name);
            }
        }
示例#7
0
        public async Task <IHtmlContent> GetAdminPageResult(ActionContext actionContext)
        {
            var currentPage = _scopeService.PageContext.CurrentPage;

            if (currentPage.AdminPage == null)
            {
                return(null);
            }

            var moduleName     = currentPage.AdminPage.ModuleName;
            var modelName      = currentPage.AdminPage.ModelName;
            var moduleMetaInfo = _moduleRegistry.GetModuleMetaInfoByModuleName(moduleName);

            var assembly           = DefaultAssemblyPartDiscoveryProvider.DiscoverAssemblyParts(Globals.EntryPointAssembly).FirstOrDefault(a => a.FullName == moduleMetaInfo.ModuleAssemblyFullName);
            var controllerTypeInfo = assembly.GetDerivedTypeInfos(typeof(IAdminController)).FirstOrDefault();
            var controllerName     = controllerTypeInfo.Name.Replace("Controller", "");
            var actionName         = nameof(AdminController <IAdminConfigurator> .Admin);


            var routeContext = new RouteContext(actionContext.HttpContext);

            routeContext.RouteData = new RouteData();
            //routeContext.RouteData.Values.Add("area", moduleName);
            //routeContext.RouteData.Values.Add("controller", controllerName);
            //routeContext.RouteData.Values.Add("action", actionName);
            //routeContext.RouteData.Values.Add("entity", entityName);

            var routeParams = new RouteValueDictionary(new { model = modelName });
            var routeValues = new RouteValueDictionary(new { area = moduleName, controller = controllerName, action = actionName });

            foreach (var router in actionContext.RouteData.Routers)
            {
                routeContext.RouteData.PushState(router, null, null);
            }

            routeContext.RouteData.PushState(null, routeValues, null);
            routeContext.RouteData.PushState(null, routeParams, null);

            var adminActionContext = GetActionContext(routeContext);


            //var invoker = _moduleInvokerProvider.CreateInvoker(moduleActionContext);
            //var result = await invoker.InvokeAction() as ViewResult;



            var result = await _actionInvoker.InvokeAction(actionContext.HttpContext, controllerTypeInfo.Namespace, controllerName, actionName, adminActionContext) as ViewResult;

            var htmlResult = result.ExecuteResultToHTML(adminActionContext);

            return(htmlResult);
        }
示例#8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            var thisAssembly  = Assembly.GetEntryAssembly();
            var assemblyParts = DefaultAssemblyPartDiscoveryProvider.DiscoverAssemblyParts(thisAssembly.FullName);

            var assemblies = assemblyParts.Select(p => Assembly.Load(new AssemblyName(p.Name))).ToList();

            services.AddApplicationHealthServices(assemblies);
            services.UseRequestGenerators(assemblies);
            services.AddSingleton <IIpService, DummyIpService>();
            services.AddScoped <IRequestValidator>(provider => new HeaderValidator("X-Zeppu-Id", "X-Zeppu-Token"));
            services.AddMvcCore()
            .AddJsonFormatters();
        }
示例#9
0
        private static ApplicationPartManager GetApplicationPartManager(this IServiceCollection services)
        {
            var manager = services.GetService <ApplicationPartManager>();

            if (manager == null)
            {
                manager = new ApplicationPartManager();
                var parts = DefaultAssemblyPartDiscoveryProvider.DiscoverAssemblyParts(Assembly.GetEntryAssembly().FullName);
                foreach (var part in parts)
                {
                    manager.ApplicationParts.Add(part);
                }
            }

            return(manager);
        }
示例#10
0
        public void RegisterAdminSites(IServiceProvider serviceProvider)
        {
            //IServiceScopeFactory _serviceScopeFactory = _serviceProvider.GetRequiredService<IServiceScopeFactory>();
            //using (var scope = _serviceScopeFactory.CreateScope())
            //{
            //    var provider = scope.ServiceProvider;

            var assemblies             = DefaultAssemblyPartDiscoveryProvider.DiscoverAssemblyParts(Globals.EntryPointAssembly);
            var adminConfiguratorTypes = assemblies.GetDerivedTypeInfos(typeof(IAdminConfigurator));

            //assemblies.GetDerivedTypeInfos(typeof(IAdminConfigurator))[0].GetInterfaces()[1].IsGenericType

            foreach (var adminConfiguratorType in adminConfiguratorTypes)
            {
                var          acInterface   = adminConfiguratorType.GetInterfaces().FirstOrDefault(i => i.IsGenericType);
                var          dbContextType = acInterface?.GetGenericArguments().FirstOrDefault();
                var          hasDbContext  = dbContextType != null;
                IAdminSite   adminSite;
                AdminBuilder adminBuilder;

                /**
                 * 1. Crete AdminSite instance
                 * 2. Create AdminConfigurator instance
                 * 3. Invoke IAdminConfigurator.ConfigureAdmin and pass adminSite as argument
                 */

                if (hasDbContext)
                {
                    using var contextObj = (DbContext)serviceProvider.GetRequiredService(dbContextType);
                    adminSite            = new AdminSite(serviceProvider, contextObj /*, serviceProvider.GetRequiredService<IModelMetadataProvider>()*/);
                    adminBuilder         = new AdminBuilder(adminSite);

                    if (!contextObj.Database.CanConnect())
                    {
                        throw new InvalidOperationException($"Database is not exist for {dbContextType}, create a database and try again");
                    }

                    ConfigureAdminSites(adminConfiguratorType, adminSite, adminBuilder);
                }
                else
                {
                    adminSite    = new AdminSite(serviceProvider /*, serviceProvider.GetRequiredService<IModelMetadataProvider>()*/);
                    adminBuilder = new AdminBuilder(adminSite);
                    ConfigureAdminSites(adminConfiguratorType, adminSite, adminBuilder);
                }
            }
        }
        private async Task MigrateModuleContexts(InstallModel installModel)
        {
            var assemblies           = DefaultAssemblyPartDiscoveryProvider.DiscoverAssemblyParts(Globals.EntryPointAssembly);
            var moduleDbContextTypes = new List <TypeInfo>();

            var moduleDbContextBaseType = typeof(ModuleDbContext);

            //var databaseField = moduleDbContextBaseType.GetProperty("Database");
            //var registerServiceMethodInfo = typeof(Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions).GetMethod("MigrateAsync");
            foreach (var assembly in assemblies)
            {
                var moduleDbContextTypesOnAssembly = assembly.DefinedTypes.Where(t => t.IsSubclassOf(moduleDbContextBaseType) && t.BaseType == moduleDbContextBaseType).ToList();

                if (moduleDbContextTypesOnAssembly.Count > 0)
                {
                    moduleDbContextTypes.AddRange(moduleDbContextTypesOnAssembly);
                }
            }

            if (moduleDbContextTypes.Count <= 0)
            {
                return;
            }

            foreach (var moduleDbContextType in moduleDbContextTypes)
            {
                var    assembly = moduleDbContextType.Assembly.GetName().Name;
                var    moduleDbOptionBuilderGType = typeof(DbContextOptionsBuilder <>);
                Type[] typeArgs = { moduleDbContextType };
                var    moduleDbOptionBuilderType = moduleDbOptionBuilderGType.MakeGenericType(typeArgs);
                var    moduleDbOptionBuilder     = Activator.CreateInstance(moduleDbOptionBuilderType); //var optionsBuilder = new DbContextOptionsBuilder<DeviserDbContext>();
                var    dbContextOptionBuilder    = GetDbContextOptionsBuilder(installModel, (DbContextOptionsBuilder)moduleDbOptionBuilder, assembly);

                var contextType = moduleDbContextType.Assembly.DefinedTypes
                                  .FirstOrDefault(t =>
                                                  moduleDbContextType.IsAssignableFrom(t) &&
                                                  t.Name.ToLower().Contains(installModel.DatabaseProvider.ToString().ToLower()));

                await using var moduleDbContext = GetDbContext(contextType, dbContextOptionBuilder.Options);
                await moduleDbContext.Database.MigrateAsync();
            }
        }
示例#12
0
        private static void RegisterModuleDependencies(IServiceCollection serviceCollection, bool isConfigureModuleAlone)
        {
            var assemblies = DefaultAssemblyPartDiscoveryProvider.DiscoverAssemblyParts(Globals.EntryPointAssembly);

            var moduleConfiguratorType = typeof(IModuleConfigurator);
            var moduleConfigurators    = assemblies.GetDerivedTypeInfos(moduleConfiguratorType); //new List<TypeInfo>();
            var moduleRegistry         = InternalServiceProvider.Instance.ServiceProvider.GetService <IModuleRegistry>();

            //var registerServiceMethodInfo = moduleConfiguratorType.GetMethod("ConfigureServices");

            if (moduleConfigurators.Count <= 0)
            {
                return;
            }

            foreach (var moduleConfigurator in moduleConfigurators)
            {
                var moduleManifest = new ModuleManifest();
                moduleManifest.ModuleMetaInfo.ModuleAssemblyFullName = moduleConfigurator.Assembly.FullName;
                if (Activator.CreateInstance(moduleConfigurator) is IModuleConfigurator moduleConfig)
                {
                    moduleConfig.ConfigureModule(moduleManifest);
                    moduleManifest.ModuleMetaInfo.AdminConfiguratorTypeInfo =
                        GetAdminConfiguratorInModule(moduleConfigurator.Assembly);
                    moduleRegistry.TryRegisterModule(moduleManifest.ModuleMetaInfo);

                    if (isConfigureModuleAlone)
                    {
                        continue;
                    }

                    moduleConfig.ConfigureServices(serviceCollection);
                }

                if (!isConfigureModuleAlone)
                {
                    //RegisterModuleDbContexts
                    RegisterModuleDbContexts(moduleConfigurator.Assembly, serviceCollection);
                }
            }
        }
示例#13
0
        // TODO: Move this into AssembliesResolver and cache results
        internal static IEnumerable <Type> GetLoadedTypes(AssembliesResolver assembliesResolver)
        {
            var result = new List <Type>();

            foreach (var assembly in assembliesResolver.Assemblies)
            {
                // Go through all assemblies referenced by the application and search for types matching a predicate
                var assemblyParts =
                    DefaultAssemblyPartDiscoveryProvider.DiscoverAssemblyParts(assembly.FullName)
                    .Select(s => (s as AssemblyPart).Assembly);
                foreach (var assemblyPart in assemblyParts)
                {
                    Type[] exportedTypes = null;
                    if (assemblyPart == null || assemblyPart.IsDynamic)
                    {
                        // can't call GetTypes on a null (or dynamic?) assembly
                        continue;
                    }

                    try
                    {
                        exportedTypes = assemblyPart.GetTypes();
                    }
                    catch (ReflectionTypeLoadException ex)
                    {
                        exportedTypes = ex.Types;
                    }
                    catch
                    {
                        continue;
                    }

                    if (exportedTypes != null)
                    {
                        result.AddRange(exportedTypes.Where(t => t != null && t.GetTypeInfo().IsVisible));
                    }
                }
            }
            return(result);
        }
示例#14
0
        private void MigrateModuleContexts(InstallModel installModel)
        {
            var             assemblies           = DefaultAssemblyPartDiscoveryProvider.DiscoverAssemblyParts(Globals.PlatformAssembly);
            List <TypeInfo> moduleDbContextTypes = new List <TypeInfo>();

            Type         moduleDbContextBaseType   = typeof(ModuleDbContext);
            PropertyInfo databaseField             = moduleDbContextBaseType.GetProperty("Database");
            MethodInfo   registerServiceMethodInfo = typeof(Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions).GetMethod("Migrate");

            foreach (var assembly in assemblies)
            {
                var controllerTypes = assembly.DefinedTypes.Where(t => moduleDbContextBaseType.IsAssignableFrom(t)).ToList();

                if (controllerTypes != null && controllerTypes.Count > 0)
                {
                    moduleDbContextTypes.AddRange(controllerTypes);
                }
            }

            if (moduleDbContextTypes.Count > 0)
            {
                foreach (var moduleDbContextType in moduleDbContextTypes)
                {
                    var    moduleDbOptionBuilderGType = typeof(DbContextOptionsBuilder <>);
                    Type[] typeArgs = { moduleDbContextType };
                    var    moduleDbOptionBuilderType = moduleDbOptionBuilderGType.MakeGenericType(typeArgs);
                    var    moduleDbOptionBuilder     = Activator.CreateInstance(moduleDbOptionBuilderType); //var optionsBuilder = new DbContextOptionsBuilder<DeviserDbContext>();
                    var    dbContextOptionBuilder    = GetDbContextOptionsBuilder(installModel, (DbContextOptionsBuilder)moduleDbOptionBuilder);

                    var moduleDbContextObj = Activator.CreateInstance(moduleDbContextType, dbContextOptionBuilder.Options);

                    var databaseObj = databaseField.GetValue(moduleDbContextObj);

                    registerServiceMethodInfo.Invoke(databaseObj, new object[] { databaseObj });
                    //registerServiceMethodInfo.Invoke(obj, new object[] { serviceCollection });
                }
            }
        }
示例#15
0
        private static ApplicationPartManager GetApplicationPartManager(IServiceCollection services)
        {
            var manager = GetServiceFromCollection <ApplicationPartManager>(services);

            if (manager == null)
            {
                manager = new ApplicationPartManager();

                var environment = GetServiceFromCollection <IHostingEnvironment>(services);
                if (string.IsNullOrEmpty(environment?.ApplicationName))
                {
                    return(manager);
                }

                var parts = DefaultAssemblyPartDiscoveryProvider.DiscoverAssemblyParts(environment.ApplicationName);
                foreach (var part in parts)
                {
                    manager.ApplicationParts.Add(part);
                }
            }

            return(manager);
        }
        /// <summary>
        /// Configures <see cref="ApplicationPartManager"/> to include the default set
        /// of <see cref="ApplicationPart"/> provided by <see cref="DefaultAssemblyPartDiscoveryProvider"/>.
        /// </summary>
        /// <returns>An instance of this <see cref="MvcWebApplicationBuilder{TStartup}"/></returns>
        public MvcWebApplicationBuilder <TStartup> UseApplicationAssemblies()
        {
            string depsFileName = $"{typeof(TStartup).Assembly.GetName().Name}.deps.json";
            var    depsFile     = new FileInfo(Path.Combine(AppContext.BaseDirectory, depsFileName));

            if (!depsFile.Exists)
            {
                throw new InvalidOperationException($"Can't find'{depsFile.FullName}'. This file is required for functional tests " +
                                                    "to run properly. There should be a copy of the file on your source project bin folder. If thats not the " +
                                                    "case, make sure that the property PreserveCompilationContext is set to true on your project file. E.g" +
                                                    "'<PreserveCompilationContext>true</PreserveCompilationContext>'." +
                                                    $"For functional tests to work they need to either run from the build output folder or the {Path.GetFileName(depsFile.FullName)} " +
                                                    $"file from your application's output directory must be copied" +
                                                    "to the folder where the tests are running on. A common cause for this error is having shadow copying enabled when the " +
                                                    "tests run.");
            }

            ApplicationAssemblies.AddRange(DefaultAssemblyPartDiscoveryProvider
                                           .DiscoverAssemblyParts(typeof(TStartup).Assembly.GetName().Name)
                                           .Select(s => ((AssemblyPart)s).Assembly)
                                           .ToList());

            return(this);
        }