예제 #1
0
        protected bool CheckValidity(IProcessingContext processingContext, KraftModule module, LoadedNodeSet loadedNodeSet)
        {
            if (processingContext.InputModel.LoaderType == ELoaderType.None)
            {
                Utilities.ExtensionMethods.KraftResult(_HttpContext, HttpStatusCode.NotFound, $"You have to specify a loader type.");
                return(false);
            }
            if (module == null)
            {
                Utilities.ExtensionMethods.KraftResult(_HttpContext, HttpStatusCode.NotFound, $"Requested module: {processingContext.InputModel.Module} doesn't exist or not loaded.");
                return(false);
            }

            if (loadedNodeSet == null)
            {
                Utilities.ExtensionMethods.KraftResult(_HttpContext, HttpStatusCode.NotFound, $"Requested nodeset: {processingContext.InputModel.NodeSet} doesn't exist or not loaded.");
                return(false);
            }
            //If authentication is required but the user is not logged in redirect to authentication
            if (loadedNodeSet.StartNode.RequireAuthentication && !processingContext.InputModel.SecurityModel.IsAuthenticated)
            {
                Utilities.ExtensionMethods.KraftResult(_HttpContext, HttpStatusCode.Unauthorized, null);
                return(false);
            }
            return(true);
        }
예제 #2
0
        protected bool CheckValidity(IProcessingContext processingContext, KraftModule module, LoadedNodeSet loadedNodeSet)
        {
            if (processingContext.InputModel.LoaderType == ELoaderType.None)
            {
                Utilities.ExtensionMethods.KraftResult(_HttpContext, HttpStatusCode.NotFound, $"You have to specify a loader type.");
                return(false);
            }
            if (module == null)
            {
                Utilities.ExtensionMethods.KraftResult(_HttpContext, HttpStatusCode.NotFound, $"Requested module: {processingContext.InputModel.Module} doesn't exist or not loaded.");
                return(false);
            }

            if (loadedNodeSet == null)
            {
                Utilities.ExtensionMethods.KraftResult(_HttpContext, HttpStatusCode.NotFound, $"Requested nodeset: {processingContext.InputModel.NodeSet} doesn't exist or not loaded.");
                return(false);
            }
            if (loadedNodeSet.StartNode == null)//Handle errors better and show when a node is addressed but missing.
            {
                string error = $"Node: {processingContext.InputModel.Nodepath} from module: {processingContext.InputModel.Module}, nodeset: {processingContext.InputModel.NodeSet} is missing!";
                KraftLogger.LogError(error);
                Utilities.ExtensionMethods.KraftResult(_HttpContext, HttpStatusCode.InternalServerError, error);
                return(false);
            }
            //If authentication is required but the user is not logged in redirect to authentication
            if (loadedNodeSet.StartNode.RequireAuthentication && !processingContext.InputModel.SecurityModel.IsAuthenticated)
            {
                Utilities.ExtensionMethods.KraftResult(_HttpContext, HttpStatusCode.Unauthorized, null);
                return(false);
            }
            return(true);
        }
예제 #3
0
        private IProcessingContextCollection PrepareSignals(string moduleName, string signalKey, bool isWriteOperation, InputModelParameters inputModelParametersTemplate)
        {
            List <IProcessingContext> resultContexts = new List <IProcessingContext>();
            bool isMaintenance = false;
            InputModelParameters inputModelParameters = inputModelParametersTemplate.DeepClone();

            if (string.IsNullOrEmpty(moduleName) || moduleName.Equals("null", StringComparison.OrdinalIgnoreCase))//Apply for all modules
            {
                foreach (KraftModule kraftModule in _KraftModuleCollection.GetSortedModules())
                {
                    KraftModuleSignal signal = FindSignal(kraftModule, signalKey);
                    if (signal != null)
                    {
                        isMaintenance = signal.Maintenance;
                        if (kraftModule.KraftModuleRootConf.Signals.Count > 0)
                        {
                            resultContexts.Add(Signal2ProcessingContext(inputModelParameters, kraftModule, signal, isWriteOperation));
                        }
                    }
                }
            }
            else
            {
                KraftModule       kraftModule = _KraftModuleCollection.GetSortedModules().Find(m => m.Key.Equals(moduleName, StringComparison.OrdinalIgnoreCase));
                KraftModuleSignal signal      = FindSignal(kraftModule, signalKey);
                if (signal != null)
                {
                    isMaintenance = signal.Maintenance;
                    resultContexts.Add(Signal2ProcessingContext(inputModelParameters, kraftModule, signal, isWriteOperation));
                }
            }
            _ProcessingContextCollection = new ProcessingContextCollection(resultContexts, isMaintenance);
            return(_ProcessingContextCollection);
        }
예제 #4
0
        public void Execute(IProcessingContext processingContext, ITransactionScopeContext transactionScopeContext)
        {
            KraftModule   loadedModule  = _KraftModuleCollection.GetModule(processingContext.InputModel.Module);
            LoadedNodeSet loadedNodeSet = _NodesSetService.LoadNodeSet(
                processingContext.InputModel.Module,
                processingContext.InputModel.NodeSet,
                processingContext.InputModel.Nodepath);
            StringBuilder sb;

            if (!CheckValidity(processingContext, loadedModule, loadedNodeSet, out sb))
            {
                PluginAccessorImp <IDataLoaderPlugin> externalService = new PluginAccessorImp <IDataLoaderPlugin>(transactionScopeContext, loadedModule.ModuleSettings);
                PluginAccessorImp <INodePlugin>       customService   = new PluginAccessorImp <INodePlugin>(transactionScopeContext, loadedModule.ModuleSettings);
                INodeTaskExecutor taskExecutor = new NodeTaskExecutor(transactionScopeContext, loadedModule.ModuleSettings);
                taskExecutor.Execute(loadedNodeSet, processingContext, externalService, customService);
            }
            else
            {
                processingContext.ReturnModel.Status.IsSuccessful = false;
                processingContext.ReturnModel.Status.StatusResults.Add(new StatusResult()
                {
                    Message = sb.ToString(), StatusResultType = SysPlugins.Interfaces.Packet.StatusResultEnum.EStatusResult.StatusResultError
                });
            }
        }
예제 #5
0
        public override void Execute(IProcessingContext processingContext, ITransactionScopeContext transactionScopeContext)
        {
            KraftModule   loadedModule  = _KraftModuleCollection.GetModule(processingContext.InputModel.Module);
            LoadedNodeSet loadedNodeSet = _NodesSetService.LoadNodeSet(
                processingContext.InputModel.Module,
                processingContext.InputModel.NodeSet,
                processingContext.InputModel.Nodepath);

            if (CheckValidity(processingContext, loadedModule, loadedNodeSet))
            {
                PluginAccessorImp <IDataLoaderPlugin> externalService = new PluginAccessorImp <IDataLoaderPlugin>(transactionScopeContext, loadedModule.ModuleSettings);
                PluginAccessorImp <INodePlugin>       customService   = new PluginAccessorImp <INodePlugin>(transactionScopeContext, loadedModule.ModuleSettings);
                INodeTaskExecutor taskExecutor = new NodeTaskExecutor(transactionScopeContext, loadedModule.ModuleSettings);
                taskExecutor.Execute(loadedNodeSet, processingContext, externalService, customService);
            }
        }
예제 #6
0
        private bool CheckValidity(IProcessingContext processingContext, KraftModule module, LoadedNodeSet loadedNodeSet, out StringBuilder sb)
        {
            sb = new StringBuilder();
            bool isError = false;

            if (module == null)
            {
                sb.Append($"Requested module: {processingContext.InputModel.Module} doesn't exist or not loaded.");
                isError = true;
            }

            if (loadedNodeSet == null)
            {
                sb.Append($"Requested nodeset: {processingContext.InputModel.NodeSet} doesn't exist or not loaded.");
                isError = true;
            }
            if (loadedNodeSet.StartNode == null)//Handle errors better and show when a node is addressed but missing.
            {
                sb.Append($"Node: {processingContext.InputModel.Nodepath} from module: {processingContext.InputModel.Module}, nodeset: {processingContext.InputModel.NodeSet} is missing!");
                isError = true;
            }
            return(isError);
        }
        public static IApplicationBuilder UseBindKraft(this IApplicationBuilder app, IHostingEnvironment env)
        {
            //AntiforgeryService
            //app.Use(next => context =>
            //{
            //    if (string.Equals(context.Request.Path.Value, "/", StringComparison.OrdinalIgnoreCase))
            //    {
            //        AntiforgeryTokenSet tokens = app.ApplicationServices.GetService<IAntiforgery>().GetAndStoreTokens(context);
            //        context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions() { HttpOnly = false });
            //    }
            //    return next(context);
            //});

            _KraftGlobalConfigurationSettings.EnvironmentSettings = new KraftEnvironmentSettings(env.ApplicationName, env.ContentRootPath, env.EnvironmentName, env.WebRootPath);
            try
            {
                ILoggerFactory     loggerFactory      = app.ApplicationServices.GetService <ILoggerFactory>();
                DiagnosticListener diagnosticListener = app.ApplicationServices.GetService <DiagnosticListener>();
                //First statement to register Error handling !!!Keep at the top!!!
                app.UseMiddleware <KraftExceptionHandlerMiddleware>(loggerFactory, new ExceptionHandlerOptions(), diagnosticListener);
                AppDomain.CurrentDomain.UnhandledException += AppDomain_OnUnhandledException;
                AppDomain.CurrentDomain.AssemblyResolve    += AppDomain_OnAssemblyResolve;
                if (_KraftGlobalConfigurationSettings.GeneralSettings.RedirectToWww)
                {
                    RewriteOptions rewrite = new RewriteOptions();
                    rewrite.AddRedirectToWwwPermanent();
                    app.UseRewriter(rewrite);
                }
                if (_KraftGlobalConfigurationSettings.GeneralSettings.RedirectToHttps)
                {
                    app.UseForwardedHeaders();
                    app.UseHsts();
                    app.UseHttpsRedirection();
                }
                ExtensionMethods.Init(app, _Logger);
                app.UseBindKraftLogger(env, loggerFactory, ERRORURLSEGMENT);
                app.UseBindKraftProfiler(env, loggerFactory, _MemoryCache);
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }

                _Builder = app;

                BundleCollection bundleCollection = app.UseBundling(env, loggerFactory.CreateLogger("Bundling"), _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlCssJsSegment, _KraftGlobalConfigurationSettings.GeneralSettings.EnableOptimization);
                bundleCollection.EnableInstrumentations = env.IsDevelopment(); //Logging enabled

                #region Initial module registration
                foreach (string dir in _KraftGlobalConfigurationSettings.GeneralSettings.ModulesRootFolders)
                {
                    if (!Directory.Exists(dir))
                    {
                        throw new Exception($"No \"{dir}\" directory found! The CoreKraft initialization cannot continue.");
                    }
                }
                string kraftUrlSegment = _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlSegment;

                try
                {
                    KraftModuleCollection       modulesCollection   = app.ApplicationServices.GetService <KraftModuleCollection>();
                    Dictionary <string, string> moduleKey2Path      = new Dictionary <string, string>();
                    IApplicationLifetime        applicationLifetime = app.ApplicationServices.GetRequiredService <IApplicationLifetime>();
                    lock (_SyncRoot)
                    {
                        foreach (string dir in _KraftGlobalConfigurationSettings.GeneralSettings.ModulesRootFolders)
                        {
                            string[] moduleDirectories = Directory.GetDirectories(dir);
                            foreach (string subdirectory in moduleDirectories)
                            {
                                DirectoryInfo moduleDirectory = new DirectoryInfo(subdirectory);
                                if (moduleDirectory.Name != null && moduleDirectory.Name.Equals("_PluginsReferences", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    continue;
                                }
                                ICachingService cachingService = app.ApplicationServices.GetService <ICachingService>();
                                KraftModule     kraftModule    = modulesCollection.GetModule(moduleDirectory.Name);
                                if (kraftModule != null)
                                {
                                    continue;
                                }
                                kraftModule = modulesCollection.RegisterModule(dir, moduleDirectory.Name, cachingService);
                                if (kraftModule == null || !kraftModule.IsInitialized)
                                {
                                    _Logger.LogInformation($"Module not created for directory \"{moduleDirectory.Name}\" because of missing configuration files.");
                                    continue;
                                }
                                KraftStaticFiles.RegisterStaticFiles(app, moduleDirectory.FullName, kraftUrlSegment, _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlResourceSegment, _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlModuleImages);
                                KraftStaticFiles.RegisterStaticFiles(app, moduleDirectory.FullName, kraftUrlSegment, _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlResourceSegment, _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlModulePublic);
                                moduleKey2Path.Add(kraftModule.Key.ToLower(), dir);
                                //The application will restart when some files changed in the modules directory and subdirectories but only in RELEASE
                                //Check if module is initialized Robert
                                if (kraftModule.IsInitialized && !env.IsDevelopment())
                                {
                                    string moduleFullPath = Path.Combine(dir, kraftModule.Key);
                                    AttachModulesWatcher(moduleFullPath, false, applicationLifetime);
                                    string path2Data = Path.Combine(moduleFullPath, "Data");
                                    if (!HasWritePermissionOnDir(new DirectoryInfo(path2Data), true))
                                    {
                                        throw new SecurityException($"Write access to folder {path2Data} is required!");
                                    }
                                    path2Data = Path.Combine(moduleFullPath, "Images");
                                    if (!HasWritePermissionOnDir(new DirectoryInfo(path2Data), true))
                                    {
                                        throw new SecurityException($"Write access to folder {path2Data} is required!");
                                    }
                                    AttachModulesWatcher(Path.Combine(moduleFullPath, "Css"), true, applicationLifetime);
                                    AttachModulesWatcher(Path.Combine(moduleFullPath, "Documentation"), true, applicationLifetime);
                                    AttachModulesWatcher(Path.Combine(moduleFullPath, "Localization"), true, applicationLifetime);
                                    AttachModulesWatcher(Path.Combine(moduleFullPath, "NodeSets"), true, applicationLifetime);
                                    AttachModulesWatcher(Path.Combine(moduleFullPath, "Scripts"), true, applicationLifetime);
                                    AttachModulesWatcher(Path.Combine(moduleFullPath, "Templates"), true, applicationLifetime);
                                    AttachModulesWatcher(Path.Combine(moduleFullPath, "Views"), true, applicationLifetime);
                                }
                            }
                        }
                        //try to construct all modules
                        modulesCollection.ResolveModuleDependencies();
                        _KraftGlobalConfigurationSettings.GeneralSettings.ModuleKey2Path = moduleKey2Path;
                    }
                    if (!env.IsDevelopment())
                    {
                        _Configuration.GetReloadToken().RegisterChangeCallback(_ =>
                        {
                            RestartReason restartReason = new RestartReason();
                            restartReason.Reason        = "Configuration Changed";
                            restartReason.Description   = $"'appsettings.Production.json' has been altered";
                            AppDomain.CurrentDomain.UnhandledException -= AppDomain_OnUnhandledException;
                            AppDomain.CurrentDomain.AssemblyResolve    -= AppDomain_OnAssemblyResolve;
                            RestartApplication(applicationLifetime, restartReason);
                        }, null);
                    }
                }
                catch (Exception boom)
                {
                    KraftLogger.LogError(boom);
                    throw new Exception($"CoreKrafts module construction failed! {boom.Message}");
                }
                #endregion Initial module registration
                //Configure the CoreKraft routing
                RouteHandler kraftRoutesHandler = new RouteHandler(KraftMiddleware.ExecutionDelegate(app, _KraftGlobalConfigurationSettings));
                app.UseRouter(KraftRouteBuilder.MakeRouter(app, kraftRoutesHandler, kraftUrlSegment));
                app.UseSession();
                if (_KraftGlobalConfigurationSettings.GeneralSettings.AuthorizationSection.RequireAuthorization)
                {
                    app.UseAuthentication();
                }
                //KraftKeepAlive.RegisterKeepAliveAsync(builder);
                //Configure eventually SignalR
                try
                {
                    if (_KraftGlobalConfigurationSettings.GeneralSettings.SignalRSettings.UseSignalR)
                    {
                        app.UseSignalR(routes =>
                        {
                            MethodInfo mapHub  = typeof(HubRouteBuilder).GetMethod("MapHub", new[] { typeof(PathString) });
                            MethodInfo generic = mapHub.MakeGenericMethod(Type.GetType(_KraftGlobalConfigurationSettings.GeneralSettings.SignalRSettings.HubImplementationAsString));
                            generic.Invoke(routes, new object[] { new PathString(_KraftGlobalConfigurationSettings.GeneralSettings.SignalRSettings.HubRoute) });
                        });
                    }
                }
                catch (Exception e)
                {
                    KraftLogger.LogError("Register signalR middleware. Exception: " + e);
                }
                //Signals
                SignalStartup signalStartup = new SignalStartup(app.ApplicationServices, _KraftGlobalConfigurationSettings);
                signalStartup.ExecuteSignalsOnStartup();
                //End Signals
            }
            catch (Exception ex)
            {
                KraftLogger.LogError("Method: UseBindKraft ", ex);
                KraftExceptionHandlerMiddleware.Exceptions[KraftExceptionHandlerMiddleware.EXCEPTIONSONCONFIGURE].Add(ex);
            }

            //This is the last statement
            KraftExceptionHandlerMiddleware.HandleErrorAction(app);
            return(app);
        }
예제 #8
0
 private KraftModuleSignal FindSignal(KraftModule kraftModule, string signalKey)
 {
     return(kraftModule.KraftModuleRootConf.Signals.FirstOrDefault(k => k.Key.Equals(signalKey, StringComparison.OrdinalIgnoreCase)));
 }
예제 #9
0
        private IProcessingContext Signal2ProcessingContext(InputModelParameters inputModelParameters, KraftModule kraftModule, KraftModuleSignal signal, bool isWriteOperation)
        {
            inputModelParameters.Module           = kraftModule.Key;
            inputModelParameters.Nodeset          = signal?.NodeSet;
            inputModelParameters.Nodepath         = signal?.NodePath;
            inputModelParameters.IsWriteOperation = isWriteOperation;
            if (inputModelParameters.LoaderType == ELoaderType.None)
            {
                inputModelParameters.LoaderType = ELoaderType.DataLoader;
            }
            IProcessingContext processingContext = new ProcessingContext(this);

            processingContext.InputModel = new InputModel(inputModelParameters);
            return(processingContext);
        }
예제 #10
0
        public static IApplicationBuilder UseBindKraft(this IApplicationBuilder app, IWebHostEnvironment env, Action <bool> restart = null)
        {
            //AntiforgeryService
            //app.Use(next => context =>
            //{
            //    if (string.Equals(context.Request.Path.Value, "/", StringComparison.OrdinalIgnoreCase))
            //    {
            //        AntiforgeryTokenSet tokens = app.ApplicationServices.GetService<IAntiforgery>().GetAndStoreTokens(context);
            //        context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions() { HttpOnly = false });
            //    }
            //    return next(context);
            //});

            _KraftGlobalConfigurationSettings.EnvironmentSettings = new KraftEnvironmentSettings(env.ApplicationName, env.ContentRootPath, env.EnvironmentName, env.WebRootPath);

            try
            {
                ILoggerFactory     loggerFactory      = app.ApplicationServices.GetService <ILoggerFactory>();
                DiagnosticListener diagnosticListener = app.ApplicationServices.GetService <DiagnosticListener>();
                //First statement to register Error handling !!!Keep at the top!!!
                app.UseMiddleware <KraftExceptionHandlerMiddleware>(loggerFactory, new ExceptionHandlerOptions(), diagnosticListener);
                AppDomain.CurrentDomain.UnhandledException += AppDomain_OnUnhandledException;
                AppDomain.CurrentDomain.AssemblyResolve    += AppDomain_OnAssemblyResolve;
                if (_KraftGlobalConfigurationSettings.GeneralSettings.RedirectToHttps)
                {
                    app.UseForwardedHeaders();
                    app.UseHsts();
                    app.UseHttpsRedirection();
                }
                if (_KraftGlobalConfigurationSettings.GeneralSettings.RedirectToWww)
                {
                    RewriteOptions rewrite = new RewriteOptions();
                    rewrite.AddRedirectToWwwPermanent();
                    app.UseRewriter(rewrite);
                }
                app.UseStaticFiles(new StaticFileOptions
                {
                    FileProvider          = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "wwwroot")),
                    ServeUnknownFileTypes = true,
                    RequestPath           = new PathString(string.Empty),
                });

                ExtensionMethods.Init(app, _Logger);
                ToolSettings tool    = KraftToolsRouteBuilder.GetTool(_KraftGlobalConfigurationSettings, "errors");
                string       segment = null;
                if (tool != null && tool.Enabled)//Errors enabled from configuration
                {
                    segment = tool.Url;
                }
                app.UseBindKraftLogger(env, loggerFactory, segment);
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }

                string           rootVirtualPath  = "/modules";
                BundleCollection bundleCollection = app.UseBundling(env,
                                                                    _KraftGlobalConfigurationSettings.GeneralSettings.ModulesRootFolders,
                                                                    rootVirtualPath,
                                                                    loggerFactory.CreateLogger("Bundling"),
                                                                    _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlCssJsSegment,
                                                                    _KraftGlobalConfigurationSettings.GeneralSettings.EnableOptimization);
                bundleCollection.EnableInstrumentations = env.IsDevelopment(); //Logging enabled

                #region Initial module registration
                foreach (string dir in _KraftGlobalConfigurationSettings.GeneralSettings.ModulesRootFolders)
                {
                    if (!Directory.Exists(dir))
                    {
                        throw new Exception($"No \"{dir}\" directory found in the setting ModulesRootFolders! The CoreKraft initialization cannot continue.");
                    }
                }
                string kraftUrlSegment = _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlSegment;
                try
                {
                    KraftModuleCollection    modulesCollection   = app.ApplicationServices.GetService <KraftModuleCollection>();
                    IHostApplicationLifetime applicationLifetime = app.ApplicationServices.GetRequiredService <IHostApplicationLifetime>();
                    lock (_SyncRoot)
                    {
                        KraftModulesConstruction kraftModulesConstruction = new KraftModulesConstruction();
                        Dictionary <string, IDependable <KraftDependableModule> > kraftDependableModules = kraftModulesConstruction.Init(_KraftGlobalConfigurationSettings.GeneralSettings.DefaultStartModule, _KraftGlobalConfigurationSettings.GeneralSettings.ModulesRootFolders);

                        ICachingService             cachingService = app.ApplicationServices.GetService <ICachingService>();
                        Dictionary <string, string> moduleKey2Path = new Dictionary <string, string>();
                        foreach (KeyValuePair <string, IDependable <KraftDependableModule> > depModule in kraftDependableModules)
                        {
                            KraftDependableModule kraftDependable = (depModule.Value as KraftDependableModule);
                            KraftModule           kraftModule     = modulesCollection.RegisterModule(kraftDependable.KraftModuleRootPath, depModule.Value.Key, kraftDependable, cachingService);
                            KraftStaticFiles.RegisterStaticFiles(app, kraftModule.ModulePath, kraftUrlSegment, _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlResourceSegment, _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlModuleImages);
                            KraftStaticFiles.RegisterStaticFiles(app, kraftModule.ModulePath, kraftUrlSegment, _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlResourceSegment, _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlModulePublic);
                            moduleKey2Path.Add(kraftModule.Key, kraftDependable.KraftModuleRootPath);
                            string moduleFullPath = Path.Combine(kraftDependable.KraftModuleRootPath, kraftModule.Key);
                            string path2Data      = Path.Combine(moduleFullPath, "Data");
                            if (!HasWritePermissionOnDir(new DirectoryInfo(path2Data), true))
                            {
                                throw new SecurityException($"Write access to folder {path2Data} is required!");
                            }
                            path2Data = Path.Combine(moduleFullPath, "Images");
                            if (!HasWritePermissionOnDir(new DirectoryInfo(path2Data), true))
                            {
                                throw new SecurityException($"Write access to folder {path2Data} is required!");
                            }
                            foreach (string validSubFolder in _ValidSubFoldersForWatching)
                            {
                                AttachModulesWatcher(Path.Combine(moduleFullPath, validSubFolder), true, applicationLifetime, restart);
                            }
                        }
                        _KraftGlobalConfigurationSettings.GeneralSettings.ModuleKey2Path = moduleKey2Path;
                    }
                    #region Watching appsettings, PassThroughJsConfig, nlogConfig
                    //appsettings.{Production} configuration watch
                    _Configuration.GetReloadToken().RegisterChangeCallback(_ =>
                    {
                        string environment = "Production";
                        if (env.IsDevelopment())
                        {
                            environment = "Development";
                        }
                        RestartReason restartReason = new RestartReason
                        {
                            Reason      = "appsettings-Configuration Changed",
                            Description = $"'appsettings.{environment}.json' has been altered"
                        };
                        AppDomain.CurrentDomain.UnhandledException -= AppDomain_OnUnhandledException;
                        AppDomain.CurrentDomain.AssemblyResolve    -= AppDomain_OnAssemblyResolve;
                        RestartApplication(applicationLifetime, restartReason, restart);
                    }, null);
                    //PassThroughJsConfig configuration watch
                    IChangeToken changeTokenPassThroughJsConfig = _KraftGlobalConfigurationSettings.GeneralSettings.BindKraftConfigurationGetReloadToken(env);
                    if (changeTokenPassThroughJsConfig != null)
                    {
                        changeTokenPassThroughJsConfig.RegisterChangeCallback(_ =>
                        {
                            RestartReason restartReason = new RestartReason
                            {
                                Reason      = "PassThroughJsConfig Changed",
                                Description = $"'{_KraftGlobalConfigurationSettings.GeneralSettings.PassThroughJsConfig}' has been altered"
                            };
                            AppDomain.CurrentDomain.UnhandledException -= AppDomain_OnUnhandledException;
                            AppDomain.CurrentDomain.AssemblyResolve    -= AppDomain_OnAssemblyResolve;
                            RestartApplication(applicationLifetime, restartReason, restart);
                        }, null);
                    }
                    FileInfo nlogConfig = new FileInfo(Path.Combine(env.ContentRootPath, "nlog.config"));
                    if (nlogConfig.Exists)
                    {
                        IChangeToken changeTokenNlogConfig = env.ContentRootFileProvider.Watch(nlogConfig.Name);
                        if (changeTokenNlogConfig != null)
                        {
                            changeTokenNlogConfig.RegisterChangeCallback(_ =>
                            {
                                RestartReason restartReason = new RestartReason
                                {
                                    Reason      = "Nlog.config Changed",
                                    Description = $"'Nlog.config' has been altered"
                                };
                                AppDomain.CurrentDomain.UnhandledException -= AppDomain_OnUnhandledException;
                                AppDomain.CurrentDomain.AssemblyResolve    -= AppDomain_OnAssemblyResolve;
                                RestartApplication(applicationLifetime, restartReason, restart);
                            }, null);
                        }
                    }
                    #endregion End: Watching appsettings, PassThroughJsConfig, nlogConfig
                }
                catch (Exception boom)
                {
                    KraftLogger.LogError(boom);
                    throw new Exception($"CoreKrafts module construction failed! {boom.Message}");
                }
                #endregion Initial module registration
                //Configure the CoreKraft routing
                RouteHandler kraftRoutesHandler = new RouteHandler(KraftMiddleware.ExecutionDelegate(app, _KraftGlobalConfigurationSettings));
                app.UseRouter(KraftRouteBuilder.MakeRouter(app, kraftRoutesHandler, kraftUrlSegment));

                #region Tools routing
                KraftToolsRouteBuilder.MakeRouters(app, _KraftGlobalConfigurationSettings);
                #endregion Tools routing

                DirectCallService.Instance.Call = KraftMiddleware.ExecutionDelegateDirect(app, _KraftGlobalConfigurationSettings);
                app.UseSession();
                if (_KraftGlobalConfigurationSettings.GeneralSettings.AuthorizationSection.RequireAuthorization)
                {
                    app.UseAuthentication();
                }
                //KraftKeepAlive.RegisterKeepAliveAsync(builder);
                //Configure eventually SignalR
                try
                {
                    if (_KraftGlobalConfigurationSettings.GeneralSettings.SignalRSettings.UseSignalR)
                    {
                        app.UseRouting();
                        app.UseEndpoints(endpoints =>
                        {
                            MethodInfo mapHub = typeof(HubEndpointRouteBuilderExtensions).GetMethod(
                                "MapHub", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(IEndpointRouteBuilder), typeof(string), typeof(Action <HttpConnectionDispatcherOptions>) }, null);
                            MethodInfo generic = mapHub.MakeGenericMethod(Type.GetType(_KraftGlobalConfigurationSettings.GeneralSettings.SignalRSettings.HubImplementationAsString, true));
                            generic.Invoke(null,
                                           new object[] { endpoints, new string(_KraftGlobalConfigurationSettings.GeneralSettings.SignalRSettings.HubRoute),
                                                          (Action <HttpConnectionDispatcherOptions>)(x => { x.ApplicationMaxBufferSize = 3200000; x.WebSockets.CloseTimeout = TimeSpan.FromSeconds(30); x.LongPolling.PollTimeout = TimeSpan.FromSeconds(180); }) });
                        });
                    }
                }
                catch (Exception e)
                {
                    KraftLogger.LogError("Register signalR middleware. Exception: " + e);
                }
                //Signals
                SignalStartup signalStartup = new SignalStartup(app.ApplicationServices, _KraftGlobalConfigurationSettings);
                signalStartup.ExecuteSignalsOnStartup();
                //End Signals
            }
            catch (Exception ex)
            {
                KraftLogger.LogError("Method: UseBindKraft ", ex);
                KraftExceptionHandlerMiddleware.Exceptions[KraftExceptionHandlerMiddleware.EXCEPTIONSONCONFIGURE].Add(ex);
            }

            //This is the last statement
            KraftExceptionHandlerMiddleware.HandleErrorAction(app);
            return(app);
        }