예제 #1
0
        public override void PreInitialize()
        {
            //Enable database based localization
            //Configuration.Modules.Zero().LanguageManagement.EnableDbLocalization();
            Configuration.BackgroundJobs.IsJobExecutionEnabled = false;
            //Configure navigation/menu
            Configuration.Navigation.Providers.Add <BlocksNavigationProvider>();

            IocManager.Register <RouteCollection>(RouteTable.Routes);
            var a = WebHostingEnvironment.CreateHostingEnvironment(new WebHostingEnvironment()
            {
                ContentRootPath = HostingEnvironment.ApplicationPhysicalPath
            });

            IocManager.Register <IHostingEnvironment>(a);

            i //RouteTable.Routes.RouteExistingFiles = true;
            Configuration.Settings.Providers.Add <GlobalSettingProvider>();

            //Configure Hangfire - ENABLE TO USE HANGFIRE INSTEAD OF DEFAULT JOB MANAGER
            //Configuration.BackgroundJobs.UseHangfire(configuration =>
            //{
            //    configuration.GlobalConfiguration.UseSqlServerStorage("Default");
            //});
        }
예제 #2
0
        public override void PreInitialize()
        {
            var _currentRootPath          = Directory.GetCurrentDirectory();
            var currentHostingEnvironment = WebHostingEnvironment.CreateHostingEnvironment(new WebHostingEnvironment()
            {
                ContentRootPath = _currentRootPath
            });
            var _defaultVirtualPathProvider = new DefaultVirtualPathProvider(currentHostingEnvironment);

            IocManager.Register <IWebSiteFolder, WebSiteFolder>(
                (Kernel, ComponentModel, CreationContext) =>
            {
                return(new WebSiteFolder(null, _defaultVirtualPathProvider));
            }, DependencyLifeStyle.Singleton);

            IocManager.Register <ExtensionDescriptor, ExtensionDescriptor>(
                (Kernel, ComponentModel, CreationContext) =>
            {
                return(new ExtensionDescriptor()
                {
                    Name = "TestNavigationModule"
                });
            }, DependencyLifeStyle.Singleton);
            IocManager.Register <Localizer, Localizer>(
                (Kernel, ComponentModel, CreationContext) =>
            {
                return((text, param) => new LocalizableString("TestNavigationModule", text, param));
            }, DependencyLifeStyle.Singleton);
        }
예제 #3
0
        public override void PreInitialize()
        {
            Configuration.Settings.Providers.Add <GlobalSettingProvider>();
            var a = WebHostingEnvironment.CreateHostingEnvironment(new WebHostingEnvironment()
            {
                ContentRootPath = AppDomain.CurrentDomain.BaseDirectory //HostingEnvironment.ApplicationPhysicalPath
            });

            IocManager.Register <IHostingEnvironment>(a);
            PerWebRequestLifestyleModule.FuncHttpCache = (noInput) => { return(new Dictionary <object, object>()); };

            //TODO unit test can't read config from appconfig.

            //            var testUserContext = new Mock<ClaimsPrincipal>();
            //                testUserContext.Setup(u => u.Claims)
            //                .Returns(new List<Claim>{ new Claim(AbpClaimTypes.UserId,"testId"),new Claim(AbpClaimTypes.UserName,"testName") });



            Thread.CurrentPrincipal = new ClaimsPrincipal(new List <ClaimsIdentity>
            {
                new ClaimsIdentity(new List <Claim>()
                {
                    new Claim(AbpClaimTypes.UserId, "testId"), new Claim(AbpClaimTypes.UserName, "testName")
                })
            })
            {
            };
        }
        public DefaultVirtualPathProviderTest()
        {
            var currentHostingEnvironment = WebHostingEnvironment.CreateHostingEnvironment(new WebHostingEnvironment()
            {
                ContentRootPath = Directory.GetCurrentDirectory()
            });

            _defaultVirtualPathProvider = new DefaultVirtualPathProvider(currentHostingEnvironment);
        }
        public DefaultVirtualPathMonitorTest()
        {
            _currentRootPath = Directory.GetCurrentDirectory();
            var currentHostingEnvironment = WebHostingEnvironment.CreateHostingEnvironment(new WebHostingEnvironment()
            {
                ContentRootPath = _currentRootPath
            });

            _patchMonitor = new DefaultVirtualPathMonitor(new Clock(), new DefaultVirtualPathProvider(currentHostingEnvironment));
            fileName      = Guid.NewGuid().ToString();
        }
예제 #6
0
        public override void PreInitialize()
        {
            Configuration.Settings.Providers.Add <GlobalSettingProvider>();
            var a = WebHostingEnvironment.CreateHostingEnvironment(new WebHostingEnvironment()
            {
                ContentRootPath = AppDomain.CurrentDomain.BaseDirectory //HostingEnvironment.ApplicationPhysicalPath
            });

            IocManager.Register <IHostingEnvironment>(a);


            //TODO unit test can't read config from appconfig.
        }
예제 #7
0
        public ActionResult Index()
        {
            var environment = new WebHostingEnvironment();
            var version     = AppVersion.Get();

            var info = new InfoModel
            {
                Environment      = environment.EnvironmentName,
                IsProduction     = environment.IsProduction(),
                FileVersion      = version.FileVersion,
                ProductVersion   = version.ProductVersion,
                ConnectionString = ConfigurationManager.ConnectionStrings["Demo"].ConnectionString,
            };

            return(View(info));
        }
예제 #8
0
        protected virtual void Application_Start(object sender, EventArgs e)
        {
            var stopwatch = new Stopwatch();

            stopwatch.Start();
            PerWebRequestLifestyleModule.FuncHttpCache = (noInput) => { return(HttpContext.Current.Items); };

            AbpBootstrapper.IocManager.IocContainer.AddFacility <Castle.Facilities.Logging.LoggingFacility>(
                f => Blocks.Framework.Logging.Log4Net.LoggingFacilityExtensions.UseLog4Net(f).WithConfig(Server.MapPath(logConfigName))
                );

            ThreadCultureSanitizer.Sanitize();

            var environment = WebHostingEnvironment.CreateHostingEnvironment(new WebHostingEnvironment()
            {
                ContentRootPath = Server.MapPath("~")
            });
            IVirtualPathProvider pathProvider = new DefaultVirtualPathProvider(environment);

            if (pathProvider.DirectoryExists(@"~\Modules"))
            {
                foreach (var modulePath in pathProvider.ListDirectories(@"~\Modules"))
                {
                    var moduleFileList = pathProvider.ListDirectories(modulePath);
//                    if (!moduleFileList.Any(t => string.Equals(t, "Module.txt", StringComparison.CurrentCultureIgnoreCase)))
//                        continue;
                    var moduleBin = moduleFileList.FirstOrDefault(t => t.EndsWith("bin"));
                    moduleBin = moduleBin ?? moduleFileList.FirstOrDefault(t => t.EndsWith("Release"));
                    if (!string.IsNullOrEmpty(moduleBin))
                    {
                        AbpBootstrapper.PlugInSources.AddFolder(pathProvider.MapPath(moduleBin),
                                                                SearchOption.AllDirectories);
                    }
                }
            }

            AbpBootstrapper.Initialize();

            stopwatch.Stop();

            LogHelper.Log(new LogModel()
            {
                Message = "Framework Init time:" + stopwatch.ElapsedMilliseconds + "ms", LogSeverity = LogSeverity.Info
            });
        }
예제 #9
0
        public override void PreInitialize()
        {
            Configuration.Settings.Providers.Add <GlobalSettingProvider>();
            var a = WebHostingEnvironment.CreateHostingEnvironment(new WebHostingEnvironment()
            {
                ContentRootPath = AppDomain.CurrentDomain.BaseDirectory //HostingEnvironment.ApplicationPhysicalPath
            });

            IocManager.Register <IHostingEnvironment>(a);

            Thread.CurrentPrincipal = new ClaimsPrincipal(new List <ClaimsIdentity>
            {
                new ClaimsIdentity(new List <Claim>()
                {
                    new Claim(AbpClaimTypes.UserId, "testId"), new Claim(AbpClaimTypes.UserName, "testName")
                })
            })
            {
            };
        }
예제 #10
0
        protected virtual void Application_Start(object sender, EventArgs e)
        {
            AbpBootstrapper.IocManager.IocContainer.AddFacility <LoggingFacility>(
                f => f.UseAbpLog4Net().WithConfig(Server.MapPath(logConfigName))
                );

            ThreadCultureSanitizer.Sanitize();

            var environment = WebHostingEnvironment.CreateHostingEnvironment(new WebHostingEnvironment()
            {
                ContentRootPath = Server.MapPath("~")
            });
            IVirtualPathProvider pathProvider = new DefaultVirtualPathProvider(environment);

            if (pathProvider.DirectoryExists(@"~\Modules"))
            {
                AbpBootstrapper.PlugInSources.AddFolder(pathProvider.MapPath(@"~\Modules"),
                                                        SearchOption.AllDirectories);
            }
            AbpBootstrapper.Initialize();
            PerWebRequestLifestyleModule.FuncHttpCache = (noInput) => { return(HttpContext.Current.Items); };
        }
예제 #11
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Configure logging
            services.AddLogging(loggingBuilder =>
            {
                // Ensure the environment variable pointing to a folder where Serilog will write application log files
                // exists when application services are configured
                string logsHomeDirectoryPath = Environment.GetEnvironmentVariable(LogsHomeEnvironmentVariable);

                if (string.IsNullOrWhiteSpace(logsHomeDirectoryPath) || !Directory.Exists(logsHomeDirectoryPath))
                {
                    var currentWorkingDirectory     = new DirectoryInfo(Directory.GetCurrentDirectory());
                    DirectoryInfo logsHomeDirectory = currentWorkingDirectory.CreateSubdirectory("Logs");
                    Environment.SetEnvironmentVariable(LogsHomeEnvironmentVariable, logsHomeDirectory.FullName);
                }

                loggingBuilder.ClearProviders();
                loggingBuilder.AddSerilog(new LoggerConfiguration()
                                          .ReadFrom.Configuration(Configuration)
                                          .CreateLogger(), dispose: true);
            });

            // Configure EF Core
            services.AddDbContext <TodoDbContext>((serviceProvider, dbContextOptionsBuilder) =>
            {
                var connectionString = Configuration.GetConnectionString("Todo");
                dbContextOptionsBuilder.UseNpgsql(connectionString)
                .UseLoggerFactory(serviceProvider.GetRequiredService <ILoggerFactory>());

                if (WebHostingEnvironment.IsDevelopment())
                {
                    dbContextOptionsBuilder.EnableSensitiveDataLogging();
                    dbContextOptionsBuilder.EnableDetailedErrors();
                }
            });

            // Display personally identifiable information only during development
            IdentityModelEventSource.ShowPII = WebHostingEnvironment.IsDevelopment();

            // Configure authentication & authorization using JSON web tokens
            IConfigurationSection generateJwtOptions = Configuration.GetSection("GenerateJwt");
            // ReSharper disable once SettingNotFoundInConfiguration
            string tokenIssuer = generateJwtOptions.GetValue <string>("Issuer");
            // ReSharper disable once SettingNotFoundInConfiguration
            string tokenAudience = generateJwtOptions.GetValue <string>("Audience");

            services
            .AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         =
                        new SymmetricSecurityKey(
                            // ReSharper disable once SettingNotFoundInConfiguration
                            Encoding.UTF8.GetBytes(generateJwtOptions.GetValue <string>("Secret"))),
                    ValidateIssuer   = true,
                    ValidIssuer      = tokenIssuer,
                    ValidateAudience = true,
                    ValidAudience    = tokenAudience,
                    ValidateLifetime = true,
                    ClockSkew        = TimeSpan.Zero,
                    // Ensure the User.Identity.Name is set to the user identifier and not to the user name.
                    NameClaimType = ClaimTypes.NameIdentifier
                };
                options.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            // Add a custom HTTP header to the response in case the application detected that the current
                            // request is accompanied by an expired security token.
                            context.Response.Headers.Add("Token-Expired", "true");
                        }

                        return(Task.CompletedTask);
                    }
                };
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy(Policies.TodoItems.GetTodoItems,
                                  policy => policy.Requirements.Add(new HasScopeRequirement("get:todo", tokenIssuer)));
                options.AddPolicy(Policies.TodoItems.CreateTodoItem,
                                  policy => policy.Requirements.Add(new HasScopeRequirement("create:todo", tokenIssuer)));
                options.AddPolicy(Policies.TodoItems.UpdateTodoItem,
                                  policy => policy.Requirements.Add(new HasScopeRequirement("update:todo", tokenIssuer)));
                options.AddPolicy(Policies.TodoItems.DeleteTodoItem,
                                  policy => policy.Requirements.Add(new HasScopeRequirement("delete:todo", tokenIssuer)));
            });
            services.AddSingleton <IAuthorizationHandler, HasScopeHandler>();

            // Configure MiniProfiler for Web API and EF Core only when inside development environment.
            // Based on: https://dotnetthoughts.net/using-miniprofiler-in-aspnetcore-webapi/.
            if (ShouldUseMiniProfiler)
            {
                services
                .AddMemoryCache()
                .AddMiniProfiler(options =>
                {
                    // MiniProfiler URLs (assuming options.RouteBasePath has been set to '/miniprofiler')
                    // - show all requests:         /miniprofiler/results-index
                    // - show current request:      /miniprofiler/results
                    // - show all requests as JSON: /miniprofiler/results-list
                    options.RouteBasePath            = Configuration.GetValue <string>("MiniProfiler:RouteBasePath");
                    options.EnableServerTimingHeader = true;
                })
                .AddEntityFramework();
            }

            // Configure ASP.NET Web API services.
            services.AddControllers();

            // Configure Todo Web API services.
            services.AddSingleton <IJwtService, JwtService>();
            services.AddScoped <ITodoItemService, TodoItemService>();

            // Register service with 2 interfaces.
            // See more here: https://andrewlock.net/how-to-register-a-service-with-multiple-interfaces-for-in-asp-net-core-di/.
            services.AddSingleton <LoggingService>();
            services.AddSingleton <IHttpObjectConverter>(serviceProvider =>
                                                         serviceProvider.GetRequiredService <LoggingService>());
            services.AddSingleton <IHttpContextLoggingHandler>(serviceProvider =>
                                                               serviceProvider.GetRequiredService <LoggingService>());

            // Configure options used for customizing generating JWT tokens.
            // Options pattern: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-3.1.
            services.Configure <GenerateJwtOptions>(generateJwtOptions);

            // Configure options used by application flows.
            services.Configure <ApplicationFlowOptions>(Configuration.GetSection("ApplicationFlows"));

            // Register application flows.
            services.AddScoped <IGenerateJwtFlow, GenerateJwtFlow>();
            services.AddScoped <IFetchTodoItemsFlow, FetchTodoItemsFlow>();
            services.AddScoped <IFetchTodoItemByIdFlow, FetchTodoItemByIdFlow>();
            services.AddScoped <IAddTodoItemFlow, AddTodoItemFlow>();
            services.AddScoped <IUpdateTodoItemFlow, UpdateTodoItemFlow>();
            services.AddScoped <IDeleteTodoItemFlow, DeleteTodoItemFlow>();
        }