Exemple #1
0
 public static IMvcBuilder AddAuthenticationViewLocationExpander(this IMvcBuilder builder)
 {
     return(builder.AddRazorOptions(razor =>
     {
         razor.ViewLocationExpanders.Add(new BodegasViewLocationExpander());
     }));
 }
Exemple #2
0
        public void ConfigureMvc(IMvcBuilder builder)
        {
            var serviceProvider = builder.Services.BuildServiceProvider();
            var env             = serviceProvider.GetRequiredService <IHostingEnvironment>();

            var services = new ServiceCollection();

            services.AddSingleton <IHostingEnvironment>(env);

            var startUp = new Startup(env);

            startUp.ConfigureServices(services);

            serviceProvider = services.BuildServiceProvider();
            var loggerFactory = serviceProvider.GetRequiredService <ILoggerFactory>();

            var app = new ApplicationBuilder(serviceProvider);

            startUp.Configure(app, loggerFactory);

            builder.AddRazorOptions(options =>
            {
                var expander = new ModuleViewLocationExpander();
                options.ViewLocationExpanders.Add(expander);

                var extensionLibraryService = services.BuildServiceProvider().GetService <IExtensionLibraryService>();
                ((List <MetadataReference>)options.AdditionalCompilationReferences).AddRange(extensionLibraryService.MetadataReferences());
            });
        }
Exemple #3
0
        /// <summary>
        /// Registers the MVC services inside the DI.
        /// </summary>
        /// <param name="serviceCollection">
        /// Will be provided by the ExtCore and might be used to register any service inside the DI.
        /// </param>
        /// <param name="serviceProvider">
        /// Will be provided by the ExtCore and might be used to get any service that is registered inside the DI at this moment.
        /// </param>
        public void Execute(IServiceCollection services, IServiceProvider serviceProvider)
        {
            IMvcBuilder mvcBuilder = services.AddMvc();

            foreach (Assembly assembly in ExtensionManager.Assemblies)
            {
                mvcBuilder.AddApplicationPart(assembly);
            }

            mvcBuilder.AddRazorOptions(
                o =>
            {
                foreach (Assembly assembly in ExtensionManager.Assemblies)
                {
                    o.FileProviders.Add(new EmbeddedFileProvider(assembly, assembly.GetName().Name));
                }
            }
                );

            foreach (IAddMvcAction action in ExtensionManager.GetInstances <IAddMvcAction>().OrderBy(a => a.Priority))
            {
                ILogger logger = serviceProvider.GetService <ILoggerFactory>().CreateLogger("ExtCore.Mvc");

                logger.LogInformation("Executing AddMvc action '{0}'", action.GetType().FullName);
                action.Execute(mvcBuilder, serviceProvider);
            }
        }
Exemple #4
0
    /*==========================================================================================================================
    | EXTENSION: ADD TOPIC SUPPORT (IMVCBUILDER)
    \-------------------------------------------------------------------------------------------------------------------------*/
    /// <summary>
    ///   Configures the Razor engine to include OnTopic view locations via the <see cref="TopicViewLocationExpander"/>.
    /// </summary>
    public static IMvcBuilder AddTopicSupport(this IMvcBuilder services) {

      /*------------------------------------------------------------------------------------------------------------------------
      | Validate parameters
      \-----------------------------------------------------------------------------------------------------------------------*/
      Contract.Requires(services, nameof(services));

      /*------------------------------------------------------------------------------------------------------------------------
      | Register services
      \-----------------------------------------------------------------------------------------------------------------------*/
      services.Services.TryAddSingleton<IActionResultExecutor<TopicViewResult>, TopicViewResultExecutor>();
      services.Services.TryAddSingleton<TopicRouteValueTransformer>();

      /*------------------------------------------------------------------------------------------------------------------------
      | Configure services
      \-----------------------------------------------------------------------------------------------------------------------*/
      services.AddRazorOptions(o => {
        o.ViewLocationExpanders.Add(new TopicViewLocationExpander());
      });

      /*------------------------------------------------------------------------------------------------------------------------
      | Register local controllers
      \-----------------------------------------------------------------------------------------------------------------------*/
      //Add Topic assembly into scope
      services.AddApplicationPart(typeof(TopicController).Assembly);

      /*------------------------------------------------------------------------------------------------------------------------
      | Return services for fluent API
      \-----------------------------------------------------------------------------------------------------------------------*/
      return services;
    }
        public static IMvcBuilder AddFeatureViewLayout(this IMvcBuilder builder)
        {
            builder.AddMvcOptions(opt => opt.Conventions.Add(new FeatureConvention()));
            builder.AddRazorOptions(opt =>
            {
                opt.ViewLocationFormats.Insert(0, "/Features/Shared/{0}.cshtml");
                opt.ViewLocationFormats.Insert(0, "/Features/Shared/Views/{0}.cshtml");
                opt.ViewLocationFormats.Insert(0, "/Features/{feature}/{0}.cshtml");
                opt.ViewLocationFormats.Insert(0, "/Features/{feature}/Views/{0}.cshtml");
                opt.ViewLocationFormats.Insert(0, "/Features/{feature}/{1}/{0}.cshtml");
                opt.ViewLocationFormats.Insert(0, "/Features/{feature}/{1}/Views/{0}.cshtml");

                opt.AreaViewLocationFormats.Insert(0, "/Features/Shared/{0}.cshtml");
                opt.AreaViewLocationFormats.Insert(0, "/Features/Shared/Views/{0}.cshtml");
                opt.AreaViewLocationFormats.Insert(0, "/Features/{feature:shared}/Shared/{0}.cshtml");
                opt.AreaViewLocationFormats.Insert(0, "/Features/{feature:shared}/Shared/Views/{0}.cshtml");
                opt.AreaViewLocationFormats.Insert(0, "/Features/{feature}/{0}.cshtml");
                opt.AreaViewLocationFormats.Insert(0, "/Features/{feature}/Views/{0}.cshtml");
                opt.AreaViewLocationFormats.Insert(0, "/Features/{feature}/{1}/{0}.cshtml");

                // TODO: should remove after migrate all
                opt.AreaViewLocationFormats.Insert(0, "/Features/{2}/Shared/{0}.cshtml");
                opt.AreaViewLocationFormats.Insert(0, "/Features/{2}/Shared/Views/{0}.cshtml");
                opt.AreaViewLocationFormats.Insert(0, "/Features/{2}/{1}/{0}.cshtml");
                opt.AreaViewLocationFormats.Insert(0, "/Features/{2}/{1}/Views/{0}.cshtml");

                opt.ViewLocationExpanders.Add(new FeatureViewLocationExpander());
            });

            return(builder);
        }
Exemple #6
0
        private void AddMvcServices(IServiceCollection services)
        {
            IMvcBuilder mvcBuilder = services.AddMvc();
            List <MetadataReference> metadataReferences = new List <MetadataReference>();

            foreach (Assembly assembly in ExtensionManager.Assemblies)
            {
                mvcBuilder.AddApplicationPart(assembly);
                metadataReferences.Add(MetadataReference.CreateFromFile(assembly.Location));
            }

            mvcBuilder.AddRazorOptions(
                o =>
            {
                foreach (Assembly assembly in ExtensionManager.Assemblies)
                {
                    o.FileProviders.Add(new EmbeddedFileProvider(assembly, assembly.GetName().Name));
                }

                Action <RoslynCompilationContext> previous = o.CompilationCallback;

                o.CompilationCallback = c =>
                {
                    if (previous != null)
                    {
                        previous(c);
                    }

                    c.Compilation = c.Compilation.AddReferences(metadataReferences);
                };
            }
                );
        }
Exemple #7
0
        private void AddMvc(IServiceCollection services)
        {
            IMvcBuilder mvcBuilder = services.AddMvc();

            foreach (Assembly assembly in ExtensionManager.Assemblies)
            {
                mvcBuilder.AddApplicationPart(assembly);
            }

            mvcBuilder.AddRazorOptions(
                o =>
            {
                foreach (Assembly assembly in ExtensionManager.Assemblies)
                {
                    o.FileProviders.Add(new EmbeddedFileProvider(assembly, assembly.GetName().Name));
                }
            }
                );

            foreach (Action <IMvcBuilder> prioritizedAddMvcAction in this.GetPrioritizedAddMvcActions())
            {
                this.logger.LogInformation("Executing prioritized AddMvc action '{0}' of {1}", this.GetActionMethodInfo(prioritizedAddMvcAction));
                prioritizedAddMvcAction(mvcBuilder);
            }
        }
Exemple #8
0
        public static void AddMvcHost(
            this IServiceCollection services,
            string extensionsPath)
        {
            ServiceProvider serviceProvider = services.BuildServiceProvider();

            ILogger logger = serviceProvider
                             .GetService <ILoggerFactory>()
                             .CreateLogger("Extensions");

            services
            .AddRouting((options) =>
            {
                options.LowercaseUrls = true;
            });

            IMvcBuilder mvcBuilder = services
                                     .AddMvc()
                                     .AddViewLocalization()
                                     .AddDataAnnotationsLocalization();

            foreach (Assembly assembly in ExtensionManager.Assemblies)
            {
                mvcBuilder.AddApplicationPart(assembly);
            }

            mvcBuilder.AddRazorOptions(razor =>
            {
                IEnumerable <MetadataReference> refs =
                    ExtensionManager.Assemblies
                    .Where(x => !x.IsDynamic &&
                           !string.IsNullOrWhiteSpace(x.Location))
                    .Select(x => MetadataReference
                            .CreateFromFile(x.Location));

                foreach (var portableExecutableReference in refs)
                {
                    razor.AdditionalCompilationReferences
                    .Add(portableExecutableReference);
                }

                razor.ViewLocationExpanders.Clear();

                razor.ViewLocationExpanders
                .Add(new ThemeViewLocationExpander(
                         extensionsPath,
                         new DefaultRequestThemeInfoProvider()));
            });

            foreach (IAddMvcAction action in ExtensionManager
                     .GetServices <IAddMvcAction>())
            {
                logger.LogInformation(
                    "Executing AddMvc action '{0}'",
                    action.GetType().FullName);

                action.Execute(mvcBuilder, serviceProvider);
            }
        }
Exemple #9
0
        public void RegisterThemes(IMvcBuilder mvcBuilder, IServiceCollection services, IServiceProvider serviceProvider, IDirectoryContents themes)
        {
            _themeDlls = new List <Assembly>();
            foreach (var themeFolder in themes.Where(x => x.IsDirectory))
            {
                try
                {
                    var binFolder = new DirectoryInfo(Path.Combine(themeFolder.PhysicalPath, "bin"));
                    if (!binFolder.Exists)
                    {
                        continue;
                    }

                    foreach (var file in binFolder.GetFileSystemInfos("*.dll", SearchOption.AllDirectories))
                    {
                        Assembly assembly;
                        try
                        {
                            assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(file.FullName);
                        }
                        catch (FileLoadException ex)
                        {
                            continue;
                        }
                        catch (BadImageFormatException ex)
                        {
                            continue;
                        }

                        if (assembly.FullName.Contains(themeFolder.Name))
                        {
                            _themeDlls.Add(assembly);
                            if (ThemeHelper.ActiveTheme.Folder == themeFolder.Name)
                            {
                                mvcBuilder.AddApplicationPart(assembly);
                                var widgetTypeList = assembly.GetTypes().Where(x => typeof(Widget).IsAssignableFrom(x)).ToList();
                                foreach (var widgetType in widgetTypeList)
                                {
                                    services.AddTransient(widgetType);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Could not load theme from " + themeFolder);
                }
            }

            mvcBuilder.AddRazorOptions(o =>
            {
                foreach (var theme in _themeDlls)
                {
                    o.AdditionalCompilationReferences.Add(MetadataReference.CreateFromFile(theme.Location));
                }
            });
        }
Exemple #10
0
        /// <summary>
        /// 注册MVC服务
        /// </summary>
        /// <param name="services"></param>
        private void AddGobalMvc(IServiceCollection services)
        {
            IMvcBuilder mvcBuilder = services.AddMvc();
            //Csv
            var csvFormatterOptions = new CsvFormatterOptions();

            mvcBuilder.AddMvcOptions(options =>
            {
                options.Filters.AddService(typeof(HandlerExceptionFilter));
                options.InputFormatters.Add(new CsvInputFormatter(csvFormatterOptions));
                options.OutputFormatters.Add(new CsvOutputFormatter(csvFormatterOptions));
                options.FormatterMappings.SetMediaTypeMappingForFormat("csv", MediaTypeHeaderValue.Parse("text/csv"));

                options.RespectBrowserAcceptHeader = true;
                options.InputFormatters.Add(new XmlSerializerInputFormatter());
                options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
            });
            // Force Camel Case to JSON
            mvcBuilder.AddJsonOptions(opts =>
            {
                opts.SerializerSettings.ContractResolver     = new BaseContractResolver();
                opts.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
                opts.SerializerSettings.NullValueHandling    = NullValueHandling.Ignore;
                opts.SerializerSettings.Converters.Add(new TimeSpanConverter());
                opts.SerializerSettings.Converters.Add(new GuidConverter());
                opts.SerializerSettings.Formatting = Formatting.None;
            });
            //foreach (var module in ExtensionManager.Modules)
            //    // Register controller from modules
            //    mvcBuilder.AddApplicationPart(module.Assembly);

            mvcBuilder.AddRazorOptions(
                o =>
            {
                foreach (Assembly assembly in ExtensionManager.Assemblies)
                {
                    o.FileProviders.Add(new EmbeddedFileProvider(assembly, assembly.GetName().Name));
                }
                foreach (var module in ExtensionManager.Modules)
                {
                    o.AdditionalCompilationReferences.Add(MetadataReference.CreateFromFile(module.Assembly.Location));
                }
            }
                ).AddViewLocalization()
            .AddDataAnnotationsLocalization();

            foreach (Action <IMvcBuilder> prioritizedAddMvcAction in GetPrioritizedAddMvcActions())
            {
                this.logger.LogInformation("Executing prioritized AddMvc action '{0}' of {1}", GetActionMethodInfo(prioritizedAddMvcAction));
                prioritizedAddMvcAction(mvcBuilder);
            }

            //注册模块FluentValidation验证
            foreach (ModuleInfo moduleInfo in ExtensionManager.Modules)
            {
                mvcBuilder.AddFluentValidation(fv => fv.RegisterValidatorsFromAssembly(moduleInfo.Assembly));
            }
        }
        private static IMvcBuilder AddNToastNotifyToMvcBuilder(this IMvcBuilder mvcBuilder, ToastOption defaultOptions = null,
                                                               NToastNotifyOption nToastNotifyOptions = null)
        {
            var services = mvcBuilder.Services;

            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            //Add the file provider to the Razor view engine
            services.Configure <RazorViewEngineOptions>(options =>
            {
                options.FileProviders.Add(GetEmbeddedFileProvider());
            });

            //This is a fix for Feature folders based project structure. Add the view location to ViewLocationExpanders.
            mvcBuilder?.AddRazorOptions(o =>
            {
                o.ViewLocationFormats.Add("/Views/Shared/{0}.cshtml");
            });

            //Add the ToastNotification implementation
            services.AddScoped <IToastNotification, ToastNotification>();

            //Check if a TempDataProvider is already registered.
            var provider         = services.BuildServiceProvider();
            var tempDataProvider = provider.GetService <ITempDataProvider>();

            if (tempDataProvider == null)
            {
                //Add a tempdata provider when one is not already registered
                services.AddSingleton <ITempDataProvider, CookieTempDataProvider>();
            }

            //Add TempDataWrapper for accessing and adding values to tempdata.
            services.AddScoped <ITempDataWrapper, TempDataWrapper>();

            //check if HttpContextAccessor is not registered.
            var httpContextAccessor = provider.GetService <IHttpContextAccessor>();

            if (httpContextAccessor == null)
            {
                services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            }

            // Add the toastr default options that will be rendered by the viewcomponent
            defaultOptions = defaultOptions ?? ToastOption.Defaults;
            services.AddSingleton(defaultOptions);

            // Add the NToastifyOptions to the services container for DI retrieval (options that are not rendered as they are not part of the toastr.js plugin)
            nToastNotifyOptions = nToastNotifyOptions ?? NToastNotifyOption.Defaults;
            services.AddSingleton((NToastNotifyOption)nToastNotifyOptions);
            services.AddSingleton <IMessageContainerFactory, MessageContainerFactory>();
            services.AddScoped <NtoastNotifyMiddleware>();
            return(mvcBuilder);
        }
Exemple #12
0
        public static IMvcBuilder AddFeatureFolders(this IMvcBuilder services)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            services.AddRazorOptions(options => { options.ViewLocationExpanders.Add(new FeatureViewLocationExpander()); });
            return(services);
        }
 /// <summary>
 /// Добавление дирректорий для размещения частичных представлений
 /// </summary>
 public static void ConfigureViewLocationFormats(this IMvcBuilder mvcBuilder)
 {
     mvcBuilder.AddRazorOptions(options =>
     {
         options.AreaPageViewLocationFormats.Add("/Views/Shared/InformElements/{0}.cshtml");
         options.AreaPageViewLocationFormats.Add("/Areas/Workspace/Views/Shared/AddPublication/{0}.cshtml");
         options.AreaPageViewLocationFormats.Add("/Areas/Workspace/Views/Shared/EditProfile/{0}.cshtml");
         options.AreaPageViewLocationFormats.Add("/Areas/Workspace/Views/Shared/TableRows/{0}.cshtml");
         options.AreaPageViewLocationFormats.Add("/Areas/Workspace/Views/Shared/SearchPublication/{0}.cshtml");
     });
 }
Exemple #14
0
        public List <IModule> RegisterModules(IMvcBuilder mvcBuilder, IServiceCollection services, IServiceProvider serviceProvider)
        {
            foreach (var module in modules)
            {
                try
                {
                    var moduleInitializerType = module.Assembly.GetTypes().Where(x => typeof(IModule).IsAssignableFrom(x)).FirstOrDefault();

                    if (moduleInitializerType != null && moduleInitializerType != typeof(IModule))
                    {
                        var moduleInstance = (IModule)Activator.CreateInstance(moduleInitializerType);
                        LoadModuleInfo(moduleInstance, module);

                        NccModule.NccModuleStatus moduleStatus = VerifyModuleInstallation(moduleInstance, serviceProvider);
                        moduleInstance.ModuleStatus = (int)moduleStatus;

                        if (moduleStatus == NccModule.NccModuleStatus.Active)
                        {
                            // Register controller from modules
                            mvcBuilder.AddApplicationPart(module.Assembly);
                        }
                        else if (moduleStatus == NccModule.NccModuleStatus.Duplicate)
                        {
                            //TODO: Raise duplicate error message
                            continue;
                        }

                        // Register dependency in modules
                        moduleInstance.Init(services);
                        RegisterWidgets(moduleInstance, services, serviceProvider);
                        instantiatedModuleList.Add(moduleInstance);
                    }
                }
                catch (Exception ex)
                {
                    //RAISE GLOBAL ERROR
                }
            }

            services.Configure <RazorViewEngineOptions>(options =>
            {
                options.ViewLocationExpanders.Add(new ModuleViewLocationExpendar());
            });

            mvcBuilder.AddRazorOptions(o =>
            {
                foreach (var module in modules)
                {
                    o.AdditionalCompilationReferences.Add(MetadataReference.CreateFromFile(module.Assembly.Location));
                }
            });

            return(instantiatedModuleList);
        }
Exemple #15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            IMvcBuilder mvcBuilder = services.AddMvc();

            services.AddSingleton <Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();
            services.AddSession(options =>
            {
                options.IdleTimeout     = TimeSpan.FromMinutes(20);
                options.Cookie.HttpOnly = true;
            });

            //添加mvc自定义寻址Razor页面地址
            mvcBuilder.AddRazorOptions(options =>
            {
                options.ViewLocationExpanders.Add(new NamespaceViewLocationExpander());
            });

            services.AddAuthentication("IdentityCookieAuthenScheme").AddCookie("IdentityCookieAuthenScheme", options =>
            {
                options.LoginPath   = "/Login/Index";
                options.Cookie.Name = "AuthCookie";
            });
            services.AddDbContextPool <NFineDbContext>(optionsAction =>
            {
                optionsAction.UseSqlServer(Configuration.GetSection("connectionStrings:NFineDbContext").Value, options => options.UseRowNumberForPaging());
#if DEBUG
                optionsAction.ConfigureWarnings(warningsConfigurationBuilderAction => warningsConfigurationBuilderAction.Throw(RelationalEventId.QueryClientEvaluationWarning));
#endif
            });
            services.AddScoped <IRepositoryBase, RepositoryBase>();
            #region 注入repositorybase类
            Assembly asm             = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName("NFine.Repository"));
            var      typesToRegister = asm.GetTypes()
                                       .Where(type => !String.IsNullOrEmpty(type.Namespace) && type.IsPublic).Where(type => type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(RepositoryBase <>));

            foreach (var type in typesToRegister)
            {
                if (type.IsClass)
                {
                    services.AddScoped(type.GetInterface("I" + type.Name), type);
                }
            }
            #endregion

            #region 注入app类
            var nfineApplication = Microsoft.Extensions.DependencyModel.DependencyContext.Default.CompileLibraries.FirstOrDefault(_ => _.Name.Equals("NFine.Application"));
            var application      = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(nfineApplication.Name));
            var apps             = application.GetTypes().Where(_ => _.IsClass && _.IsPublic).Where(type => !String.IsNullOrEmpty(type.Namespace));
            foreach (var type in apps)
            {
                services.AddScoped(type, type);
            }
            #endregion
        }
Exemple #16
0
        public static IMvcBuilder AddForums(this IMvcBuilder target)
        {
            var assembly = typeof(IMvcBuilderExtension).Assembly;

            target.AddApplicationPart(assembly);
            target.AddRazorOptions(options =>
            {
                options.FileProviders.Add(new EmbeddedFileProvider(assembly, "Cobalt.Forums"));
            });

            return(target);
        }
Exemple #17
0
        public static IMvcBuilder UseManagement(this IMvcBuilder mvcBuilder)
        {
            var managementAssembly = typeof(ModuleManagementController).GetTypeInfo().Assembly;
            var fileProvider       = new EmbeddedFileProvider(managementAssembly);

            mvcBuilder.AddApplicationPart(managementAssembly);
            mvcBuilder.AddRazorOptions(options =>
            {
                options.FileProviders.Add(fileProvider);
            });

            return(mvcBuilder);
        }
Exemple #18
0
        /// <summary>
        ///     Use areas with feature folders and custom options
        /// </summary>
        public static IMvcBuilder AddAreaFeatureFolders(this IMvcBuilder services, AreaFeatureFolderOptions options)
        {
            services.AddRazorOptions(o =>
            {
                o.AreaViewLocationFormats.Clear();
                o.AreaViewLocationFormats.Add(options.AreaFolderName + @"\{2}\{0}.cshtml");
                o.AreaViewLocationFormats.Add(options.AreaFolderName + @"\Shared\{0}.cshtml");
                o.AreaViewLocationFormats.Add(options.DefaultAreaViewLocation);
                o.AreaViewLocationFormats.Add(options.FeatureFolderName + @"\Shared\{0}.cshtml");
            });

            return(services);
        }
Exemple #19
0
        public void ConfigureServices(IServiceCollection services)
        {
            // services.AddSingleton<RazorTemplateEngine, ModuleRazorTemplateEngine>(); // don't need this any more if we make use of ModuleBasedRazorProject
            services.AddSingleton <RazorProject, ModuleBasedRazorProject>();

            IMvcBuilder mvcBuilder = services.AddMvc();

            mvcBuilder.AddRazorOptions(options =>
            {
                options.ViewLocationFormats.Add("/{1}/Views/{0}.cshtml");
                options.ViewLocationExpanders.Add(new NamespaceViewLocationExpander());
            });
        }
Exemple #20
0
        public static void RegisterThemes(IMvcBuilder mvcBuilder, IServiceCollection services, IDirectoryContents themes)
        {
            var themeDlls = new List <Assembly>();

            foreach (var themeFolder in themes.Where(x => x.IsDirectory))
            {
                try
                {
                    var binFolder = new DirectoryInfo(Path.Combine(themeFolder.PhysicalPath, "bin"));
                    if (!binFolder.Exists)
                    {
                        continue;
                    }

                    foreach (var file in binFolder.GetFileSystemInfos("*.dll", SearchOption.AllDirectories))
                    {
                        Assembly assembly;
                        try
                        {
                            assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(file.FullName);
                        }
                        catch (FileLoadException ex)
                        {
                            continue;
                        }
                        catch (BadImageFormatException ex)
                        {
                            continue;
                        }

                        if (assembly.FullName.Contains(themeFolder.Name))
                        {
                            themeDlls.Add(assembly);
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Could not load module from " + themeFolder);
                }
            }

            mvcBuilder.AddRazorOptions(o =>
            {
                foreach (var module in themeDlls)
                {
                    o.AdditionalCompilationReferences.Add(MetadataReference.CreateFromFile(module.Location));
                }
            });
        }
Exemple #21
0
        public static IServiceCollection AddModuleDependencies(this IServiceCollection services, IMvcBuilder mvcBuilder)
        {
            mvcBuilder.AddRazorOptions(options =>
            {
                Hashtable moduleDependencies = GlobalContext.GetModuleDependencies();
                foreach (ModuleDependedLibrary mdl in moduleDependencies.Values)
                {
                    foreach (var path in mdl.AssemblyPaths)
                    {
                        options.AdditionalCompilationReferences.Add(MetadataReference.CreateFromFile(path));
                    }
                }
            });

            return(services);
        }
        internal static IMvcBuilder AddNToastNotifyToMvcBuilder <TNotificationImplementation>(this IMvcBuilder mvcBuilder,
                                                                                              ILibrary library,
                                                                                              NToastNotifyOption nToastNotifyOptions)
            where TNotificationImplementation : class, IToastNotification
        {
            //This is a fix for Feature folders based project structure. Add the view location to ViewLocationExpanders.
            mvcBuilder?.AddRazorOptions(o =>
            {
                o.ViewLocationFormats.Add("/Views/Shared/{0}.cshtml");
            });

            var services = mvcBuilder.Services;

            AddNToastNotifyToServiceCollection <TNotificationImplementation>(services, library, nToastNotifyOptions);
            return(mvcBuilder);
        }
 public void ConfigureMvc(IMvcBuilder builder)
 {
     builder.AddRazorOptions(options =>
     {
         var callback = options.CompilationCallback;
         options.CompilationCallback = context =>
         {
             callback(context);
             foreach (var tree in context.Compilation.SyntaxTrees)
             {
                 var rewrittenRoot   = new RazorRewriter().Visit(tree.GetRoot());
                 var rewrittenTree   = tree.WithRootAndOptions(rewrittenRoot, tree.Options);
                 context.Compilation = context.Compilation.ReplaceSyntaxTree(tree, rewrittenTree);
             }
         };
     });
 }
Exemple #24
0
        /// <summary>
        /// 开发模式时,直接读取开发项目的View文件,产品模式则从dll的资源中读取。
        /// </summary>
        /// <param name="services"></param>
        /// <param name="projects"></param>
        /// <param name="env"></param>
        /// <returns></returns>
        public static IMvcBuilder AddDeveloperView(
            this IMvcBuilder mvcBuilder,
            IEnumerable <DeveloperProjectInfo> projects, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                mvcBuilder.AddRazorOptions(options =>
                {
                    foreach (var project in projects)
                    {
                        options.FileProviders.Add(new PhysicalFileProvider(project.Path));
                    }
                });
            }

            return(mvcBuilder);
        }
Exemple #25
0
        public static IMvcBuilder AddFeatureFolders(this IMvcBuilder mvcBuilder, FeatureFolderOptions options)
        {
            mvcBuilder.Services.AddSingleton(options);

            mvcBuilder.Services.ConfigureOptions <FeatureMvcOptionsConfiguration>();

            mvcBuilder.AddRazorOptions(options =>
            {
                // Relocate the default view locations to the 'Features' folder.
                options.ViewLocationFormats.Add("/Features/{0}.cshtml");
                options.ViewLocationFormats.Add("/Features/Shared/{0}.cshtml");

                options.ViewLocationExpanders.Add(new FeatureViewLocationExpander());
            });

            return(mvcBuilder);
        }
Exemple #26
0
        internal static IMvcBuilder AddNToastNotifyToMvcBuilder <TLibrary, TOption, TMessage, TNotificationImplementation>(this IMvcBuilder mvcBuilder,
                                                                                                                           TOption defaultLibOptions,
                                                                                                                           NToastNotifyOption nToastNotifyOptions = null)
            where TLibrary : class, ILibrary <TOption>, new()
            where TOption : class, ILibraryOptions
            where TMessage : class, IToastMessage
            where TNotificationImplementation : class, IToastNotification
        {
            //This is a fix for Feature folders based project structure. Add the view location to ViewLocationExpanders.
            mvcBuilder?.AddRazorOptions(o =>
            {
                o.ViewLocationFormats.Add("/Views/Shared/{0}.cshtml");
            });

            var services = mvcBuilder.Services;

            AddNToastNotifyToServiceCollection <TLibrary, TOption, TMessage, TNotificationImplementation>(services, defaultLibOptions, nToastNotifyOptions);
            return(mvcBuilder);
        }
Exemple #27
0
        public void ConfigureMvc(IMvcBuilder builder)
        {
            builder.AddRazorOptions(options =>
            {
#pragma warning disable CS0618 // Type or member is obsolete
                var callback = options.CompilationCallback;
                options.CompilationCallback = context =>
#pragma warning restore CS0618 // Type or member is obsolete
                {
                    callback(context);
                    foreach (var tree in context.Compilation.SyntaxTrees)
                    {
                        var rewrittenRoot   = new RazorRewriter().Visit(tree.GetRoot());
                        var rewrittenTree   = tree.WithRootAndOptions(rewrittenRoot, tree.Options);
                        context.Compilation = context.Compilation.ReplaceSyntaxTree(tree, rewrittenTree);
                    }
                };
            });
        }
        public static IMvcBuilder LoadModules(this IMvcBuilder mvcBuilder, IModuleRepository moduleRepository)
        {
            var moduleAssemblies = new List <Assembly>();

            foreach (var library in DependencyContext.Default.RuntimeLibraries)
            {
                if (library.Name.StartsWith(modulePrefix))
                {
                    var moduleAssembly = Assembly.Load(new AssemblyName(library.Name));
                    moduleAssemblies.Add(moduleAssembly);

                    // The prefix is 15 chars.
                    var niceName = library.Name.Remove(0, 15);

                    // Insert the modules in the module repository.
                    var module = new Modular.Core.Module(niceName);
                    moduleRepository.AddModule(module);
                }
            }

            var fileProviders = new List <IFileProvider>();

            foreach (var moduleAssembly in moduleAssemblies)
            {
                // Add the module as an application part, so view components will be usable.
                mvcBuilder.AddApplicationPart(moduleAssembly);

                // Create an embedded file provider for static content like views.
                var fileProvider = new EmbeddedFileProvider(moduleAssembly);
                fileProviders.Add(fileProvider);
            }

            mvcBuilder.AddRazorOptions(options =>
            {
                // Add each file provider to the razor engine.
                foreach (var fileProvider in fileProviders)
                {
                    options.FileProviders.Add(fileProvider);
                }
            });

            return(mvcBuilder);
        }
Exemple #29
0
        public static IMvcBuilder AddEmbeddedViews(this IMvcBuilder services, Assembly assembly)
        {
            var optionsSetup = new Action <RazorViewEngineOptions>(options =>
            {
                var ns = assembly.GetName().Name;

                options.FileProviders.Add(new EmbeddedFileProvider(assembly, ns));

                var previous = options.CompilationCallback;
                options.CompilationCallback = context =>
                {
                    previous?.Invoke(context);

                    context.Compilation = context.Compilation.AddReferences(
                        MetadataReference.CreateFromFile(assembly.Location));
                };
            });

            return(services.AddRazorOptions(optionsSetup));
        }
Exemple #30
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            IMvcBuilder mvcBuilder = services.AddMvc();

            services.AddSingleton <Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();
            services.AddSession(options =>
            {
                options.IdleTimeout     = TimeSpan.FromMinutes(20);
                options.Cookie.HttpOnly = true;
            });

            //添加mvc自定义寻址Razor页面地址
            mvcBuilder.AddRazorOptions(options =>
            {
                options.ViewLocationExpanders.Add(new NamespaceViewLocationExpander());
            });

            services.AddAuthentication("IdentityCookieAuthenScheme").AddCookie("IdentityCookieAuthenScheme", options =>
            {
                options.LoginPath   = "/Login/Index";
                options.Cookie.Name = "AuthCookie";
            });
        }