Exemplo n.º 1
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseSwagger();

            app.UseSwaggerUI(CacheProfile =>
            {
                CacheProfile.SwaggerEndpoint("/swagger/v1/swagger.json/", "My API V1");
            });

            var option = new RewriteOptions();

            option.AddRedirect("^$", "swagger");
            app.UseRewriter(option);

            app.UseHttpsRedirection();
            app.UseMvc();
        }
Exemplo n.º 2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddResponseCaching();
            services.AddMvc(options =>
            {
                CacheProfile homeProfile = new CacheProfile();
                Configuration.Bind("ResponseCache:Home", homeProfile);
                options.CacheProfiles.Add("Home", homeProfile);
            });
            services.AddRazorPages().AddRazorRuntimeCompilation();
            services.AddControllersWithViews();
            //services.AddTransient<IReceiptService, AdoNetReceiptService>();
            services.AddTransient <IReceiptService, EfCoreReceiptService>();
            services.AddTransient <IErrorService, SwitcherErrorService>();
            services.AddTransient <IDatabaseManager, SqliteDatabaseManager>();
            services.AddTransient <IChachedReceiptService, MemoryCachedReceiptService>();

            //services.AddScoped<ScontriniWebAppDbContext>();
            services.AddDbContextPool <ScontriniWebAppDbContext>(optionsBuilder =>
            {
                optionsBuilder.UseSqlite(Configuration.GetConnectionString("Default"));
            });

            //----------- Options
            services.Configure <ReceiptsOptions>(Configuration.GetSection("Receipts"));
            services.Configure <CacheOptions>(Configuration.GetSection("Cache"));
        }
Exemplo n.º 3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddResponseCaching();

            services.AddMvc(options =>
            {
                var homeProfile = new CacheProfile();
                //homeProfile.Duration = Configuration.GetValue<int>("ResponseCache:Home:Duration");
                //homeProfile.Location = Configuration.GetValue<ResponseCacheLocation>("ResponseCache:Home:Location");
                //homeProfile.VaryByQueryKeys = new string[] { "page" };
                Configuration.Bind("ResponseCache:Home", homeProfile);
                options.CacheProfiles.Add("Home", homeProfile);
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddTransient <ICourseService, AdoNetCourseService>();
            //services.AddTransient<ICourseService, EfCoreCourseService>();
            services.AddTransient <IDatabaseAccessor, SqliteDatabaseAccessor>();
            services.AddTransient <ICachedCourseService, MemoryCacheCourseService>();

            services.AddDbContextPool <MyCourseDbContext>(optionsBuilder => {
                string connectionString = Configuration.GetSection("ConnectionStrings").GetValue <string>("Default");
                optionsBuilder.UseSqlite(connectionString);
            });

            //Options
            services.Configure <CoursesOptions>(Configuration.GetSection("Courses"));
            services.Configure <ConnectionStringsOptions>(Configuration.GetSection("ConnectionStrings"));
            services.Configure <MemoryCacheOptions>(Configuration.GetSection("MemoryCache"));
        }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddResponseCaching();

            services.AddMvc(options =>
            {
                var homeProfile = new CacheProfile();
                Configuration.Bind("ResponseCache:Home", homeProfile);
                options.CacheProfiles.Add("Home", homeProfile);
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            // Usiamo AdoNet o EF per l'accesso ai dati?
            services.AddTransient <ICourseService, AdoNetCourseService>();
            // services.AddTransient<ICourseService, EFCoreCourseService>();

            services.AddTransient <IDatabaseService, DatabaseService>();

            services.AddTransient <ICachedCourseService, MemoryCacheCourseService>();

            services.AddDbContextPool <MyCourseDbContext>(optionBuilder => {
                string connectionString = Configuration.GetSection("ConnectionStrings").GetValue <string>("Default");
                optionBuilder.UseSqlite(connectionString);
            });

            services.Configure <ConnectionStringOptions>(Configuration.GetSection("ConnectionStrings"));

            services.Configure <CoursesOptions>(Configuration.GetSection("Courses"));

            services.Configure <CachedLifeOptions>(Configuration.GetSection("CachedLife"));

            services.Configure <MemoryCacheOptions>(Configuration.GetSection("MemoryCache"));
        }
Exemplo n.º 5
0
 // This method gets called by the runtime. Use this method to add services to the container.
 // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
 public void ConfigureServices(IServiceCollection services)
 {
     /*PER MIDDLEWARE DI CACHING*/
     services.AddResponseCaching();
     /*PER MIDDLEWARE DI CACHING*/
     /*SERVIZI MVC*/
     services.AddMvc(option => {
         option.EnableEndpointRouting = false;
         var homeProfile = new CacheProfile();
         configuration.Bind("ResponseCache:Home", homeProfile);
         option.CacheProfiles.Add("Home", homeProfile);
     });
     /*SERVIZI MVC*/
     /*PLACEHOLDER*/
     // services.AddTransient<ICourseService, CourseService>();
     /*PLACEHOLDER*/
     /*ADONET*/
     services.AddTransient <ICourseServiceAsync, AdoNetCourseService>();
     services.AddTransient <IDatabaseAccessor, SqliteDatabaseAccessor>();
     /*ADONET*/
     /*CACHE*/
     services.AddTransient <ICachedCourseService, MemoryCacheCourseService>();
     services.Configure <MemoryCacheOptions>(configuration.GetSection("MemoryCache"));
     /*CACHE*/
     /*STRINGA DI CONNESSIONE AL DB*/
     // string connectionStrin = Configuration.GetSection("ConnectionStrings").GetValue<string>("Default");
     // string connectionStrin = Configuration.GetConnectionString("Default");
     services.Configure <ConnectionStringsOptions>(configuration.GetSection("ConnectionStrings"));
     /*STRINGA DI CONNESSIONE AL DB*/
     /*PAGINAZIONE ED ORDINE*/
     services.Configure <CoursesOptions>(configuration.GetSection("Courses"));
     /*PAGINAZIONE ED ORDINE*/
 }
Exemplo n.º 6
0
        public IEnumerable <string> Keys(CacheProfile cacheProfile, string keyPrefix)
        {
            ArgumentValidation.NotNull(cacheProfile, "cacheProfile");
            var ret = Contents(cacheProfile, keyPrefix).Select(key => key.Split(new[] { CacheConstants.CacheItemKeyDelimiter }, StringSplitOptions.RemoveEmptyEntries)[1]);

            return(ret);
        }
Exemplo n.º 7
0
        private IEnumerable <string> Contents(CacheProfile cacheProfile, string keyPrefix = null)
        {
            var fullPrefix = string.Format("{0}{1}{2}", cacheProfile.ProfileName, CacheConstants.CacheItemKeyDelimiter, keyPrefix).ToLowerInvariant();

            return(from cacheItem in GetMemoryCache(cacheProfile)
                   where cacheItem.Key != null && cacheItem.Key.StartsWith(fullPrefix)
                   select cacheItem.Key);
        }
Exemplo n.º 8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            #if DEBUG
            services.AddLiveReload();
            #endif

            services.AddResponseCaching();
            services.AddMvc(option =>
            {
                var homeProfile = new CacheProfile();
                //homeProfile.Duration = Configuration.GetSection("ResponseCache").GetSection("Home").GetValue<int>("Duration");
                //homeProfile.Location = Configuration.GetValue<ResponseCacheLocation>("ResponseCache:Home:Location");
                //homeProfile.VaryByQueryKeys = new string[] { "page" };
                Configuration.Bind("ResponseCache:Home", homeProfile);

                option.CacheProfiles.Add("Home", homeProfile);
            }).SetCompatibilityVersion(CompatibilityVersion.Latest)
            #if DEBUG
            .AddRazorRuntimeCompilation()
            #endif
            ;


            var persistence = Persistence.AdoNet;

            switch (persistence)
            {
            case Persistence.AdoNet:
                services.AddTransient <ICourseService, AdoNetCourseService>();
                services.AddTransient <IDatabaseAccesso, SQLiteDatabaseAccesso>();
                break;

            case Persistence.EFCore:
                services.AddTransient <ICourseService, EfCoreCourseService>();
                services.AddDbContextPool <MyCourseDbContext>(option =>
                {
                    string connectionString = Configuration.GetSection("ConnectionStrings").GetValue <string>("Default");
                    option.UseSqlite(connectionString);
                }
                                                              );
                break;
            }

            services.AddTransient <ICachedCourseService, MemoryCachedCourseService>();

            services.AddSingleton <IErrorViewSelectorService, ErrorViewSelectorService>();

            //services.AddScoped<MioCourseDbContext>();

            //Options
            services.Configure <ConnectionStringsOptions>(Configuration.GetSection("ConnectionStrings"));
            services.Configure <CoursesOptions>(Configuration.GetSection("Courses"));
            services.Configure <CachedOption>(Configuration.GetSection("CachedTime"));
            //TODO: resolve problem with memorycache and EfCore
            //services.Configure<MemoryCacheOptions>(Configuration.GetSection("MemoryCache"));
        }
Exemplo n.º 9
0
        public void ApplyCacheProfile_DoesNotSetLocationOrDuration_IfNoStoreIsSet(
            CacheProfile cacheProfile,
            string output)
        {
            var context = new DefaultHttpContext();

            context.ApplyCacheProfile(cacheProfile);

            Assert.Equal(output, context.Response.Headers[HeaderNames.CacheControl]);
        }
Exemplo n.º 10
0
        public void ApplyCacheProfile_CanSetCacheControlHeaders_CacheControlAndPragmaSetToOutput(
            CacheProfile cacheProfile,
            string output)
        {
            var context = new DefaultHttpContext();

            context.ApplyCacheProfile(cacheProfile);

            Assert.Equal(output, context.Response.Headers[HeaderNames.CacheControl]);
        }
Exemplo n.º 11
0
    /// <summary>
    /// Adds Cache-Control and Pragma HTTP headers by applying specified cache profile to the HTTP context.
    /// </summary>
    /// <param name="context">HTTP context.</param>
    /// <param name="cacheProfile">Cache profile.</param>
    /// <returns>The same HTTP context.</returns>
    /// <exception cref="System.ArgumentNullException">context or cacheProfile.</exception>
    public static HttpContext ApplyCacheProfile(this HttpContext context, CacheProfile cacheProfile)
    {
        ArgumentNullException.ThrowIfNull(context);
        ArgumentNullException.ThrowIfNull(cacheProfile);

        IHeaderDictionary headers = context.Response.Headers;

        if (!string.IsNullOrEmpty(cacheProfile.VaryByHeader))
        {
            headers[HeaderNames.Vary] = cacheProfile.VaryByHeader;
        }

        if (cacheProfile.NoStore == true)
        {
            // Cache-control: no-store, no-cache is valid.
            if (cacheProfile.Location == ResponseCacheLocation.None)
            {
                headers[HeaderNames.CacheControl] = NoStoreNoCache;
                headers[HeaderNames.Pragma]       = NoCache;
            }
            else
            {
                headers[HeaderNames.CacheControl] = NoStore;
            }
        }
        else
        {
            string cacheControlValue;
            string duration = cacheProfile.Duration.GetValueOrDefault().ToString(CultureInfo.InvariantCulture);
            switch (cacheProfile.Location)
            {
            case ResponseCacheLocation.Any:
                cacheControlValue = PublicMaxAge + duration;
                break;

            case ResponseCacheLocation.Client:
                cacheControlValue = PrivateMaxAge + duration;
                break;

            case ResponseCacheLocation.None:
                cacheControlValue           = NoCacheMaxAge + duration;
                headers[HeaderNames.Pragma] = NoCache;
                break;

            default:
                NotImplementedException exception = new NotImplementedException($"Unknown {nameof(ResponseCacheLocation)}: {cacheProfile.Location}");
                Debug.Fail(exception.ToString());
                throw exception;
            }

            headers[HeaderNames.CacheControl] = cacheControlValue;
        }

        return(context);
    }
Exemplo n.º 12
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddResponseCaching();

            services.AddMvc(options =>
            {
                var homeProfile = new CacheProfile();
                //homeProfile.Duration = Configuration.GetValue<int>("ResponseCache:Home:Duration");
                //homeProfile.Location = Configuration.GetValue<ResponseCacheLocation>("ResponseCache:Home:Location");
                //homeProfile.VaryByQueryKeys = new string[] { "page" };
                Configuration.Bind("ResponseCache:Home", homeProfile);
                options.CacheProfiles.Add("Home", homeProfile);
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddTransient <ICourseService, AdoNetCouseService>();
            //services.AddTransient<ICourseService, EFCoreCoursesService>();
            services.AddTransient <IDatabaseAccessor, SqlliteDatabaseAccessor>();
            services.AddTransient <ICachedCourseService, MemoryCachedCoursesService>();

            services.AddAutoMapper();

            //services.AddScoped<MyCourseDbContext>(); //Equivalente alla riga sotto
            //services.AddDbContext<MyCourseDbContext>();
            services.AddDbContextPool <MyCourseDbContext>(optionsBuilder => {
                string connectionString = Configuration.GetSection("ConnectionStrings").GetValue <string>("Default");
                optionsBuilder.UseSqlite(connectionString);
            });

            //Options
            services.Configure <ConnectionStringsOptions>(Configuration.GetSection("ConnectionStrings"));
            services.Configure <CachingOptions>(Configuration.GetSection("Caching"));
            services.Configure <CoursesOptions>(Configuration.GetSection("Courses"));
            services.Configure <MemoryCacheOptions>(Configuration.GetSection("MemoryCache"));

            #region Configurazione del servizio di cache distribuita

            //Se vogliamo usare Redis, ecco le istruzioni per installarlo: https://docs.microsoft.com/it-it/aspnet/core/performance/caching/distributed?view=aspnetcore-2.2#distributed-redis-cache
            //Bisogna anche installare il pacchetto NuGet: Microsoft.Extensions.Caching.StackExchangeRedis
            //services.AddStackExchangeRedisCache(options =>
            //{
            //    Configuration.Bind("DistributedCache:Redis", options);
            //});

            //Se vogliamo usare Sql Server, ecco le istruzioni per preparare la tabella usata per la cache: https://docs.microsoft.com/it-it/aspnet/core/performance/caching/distributed?view=aspnetcore-2.2#distributed-sql-server-cache

            /*services.AddDistributedSqlServerCache(options =>
             * {
             *  Configuration.Bind("DistributedCache:SqlServer", options);
             * });*/

            //Se vogliamo usare la memoria, mentre siamo in sviluppo
            //services.AddDistributedMemoryCache();

            #endregion
        }
Exemplo n.º 13
0
        public void Clear(CacheProfile cacheProfile, string keyPrefix = null)
        {
            ArgumentValidation.NotNull(cacheProfile, "cacheProfile");

            var cache = GetMemoryCache(cacheProfile);

            foreach (var key in Contents(cacheProfile, keyPrefix))
            {
                cache.Remove(key);
            }
        }
Exemplo n.º 14
0
    public void Execute_DoesNotSetLocationOrDuration_IfNoStoreIsSet(CacheProfile cacheProfile, string output)
    {
        // Arrange
        var executor = new ResponseCacheFilterExecutor(cacheProfile);
        var context  = GetActionExecutingContext();

        // Act
        executor.Execute(context);

        // Assert
        Assert.Equal(output, context.HttpContext.Response.Headers["Cache-control"]);
    }
Exemplo n.º 15
0
    public void Execute_CanSetCacheControlHeaders(CacheProfile cacheProfile, string output)
    {
        // Arrange
        var executor = new ResponseCacheFilterExecutor(cacheProfile);
        var context  = GetActionExecutingContext();

        // Act
        executor.Execute(context);

        // Assert
        Assert.Equal(output, context.HttpContext.Response.Headers["Cache-control"]);
    }
Exemplo n.º 16
0
    public void ResponseCacheCanSetVaryByHeader(CacheProfile cacheProfile, string varyOutput, string cacheControlOutput)
    {
        // Arrange
        var executor = new ResponseCacheFilterExecutor(cacheProfile);
        var context  = GetActionExecutingContext();

        // Act
        executor.Execute(context);

        // Assert
        Assert.Equal(varyOutput, context.HttpContext.Response.Headers["Vary"]);
        Assert.Equal(cacheControlOutput, context.HttpContext.Response.Headers["Cache-control"]);
    }
        /// <summary>
        /// Initializes a new instance of the <see cref="SitemapService" /> class.
        /// </summary>
        /// <param name="cacheProfileSettings">The cache profile settings.</param>
        /// <param name="loggerFactory">The logger factory.</param>
        /// <param name="memoryCache">The memory cache for the application.</param>
        /// <param name="urlHelper">The URL helper.</param>
        public SitemapService(
            IOptions <CacheProfileSettings> cacheProfileSettings,
            ILoggerFactory loggerFactory,
            IMemoryCache memoryCache,
            IUrlHelper urlHelper)
        {
            CacheProfile cacheProfile = cacheProfileSettings.Options.CacheProfiles[CacheProfileName.SitemapNodes];

            this.cacheSlidingExpiration = TimeSpan.FromSeconds(cacheProfile.Duration.Value);
            this.logger      = loggerFactory.CreateLogger <SitemapService>();
            this.memoryCache = memoryCache;
            this.urlHelper   = urlHelper;
        }
Exemplo n.º 18
0
        public IEnumerable <string> Keys(CacheProfile cacheProfile, string keyPrefix = null)
        {
            if (!_session.EnsureConnectionIsOpen())
            {
                return(new string[0]);
            }

            var prefix = keyPrefix == null ? "*" : keyPrefix.ToLowerInvariant() + "*";
            var task   = _session.Connection.Keys.Find(cacheProfile.CacheId, prefix);
            var result = _session.Connection.Wait(task);

            return(result);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SitemapService" /> class.
        /// </summary>
        /// <param name="cacheProfileSettings">The cache profile settings.</param>
        /// <param name="distributedCache">The distributed cache for the application.</param>
        /// <param name="logger">The <see cref="SitemapService"/> logger.</param>
        /// <param name="urlHelper">The URL helper.</param>
        public SitemapService(
            IOptions <CacheProfileSettings> cacheProfileSettings,
            IDistributedCache distributedCache,
            ILogger <SitemapService> logger,
            IUrlHelper urlHelper)
        {
            CacheProfile cacheProfile = cacheProfileSettings.Value.CacheProfiles[CacheProfileName.SitemapNodes];

            this.cacheSlidingExpiration = TimeSpan.FromSeconds(cacheProfile.Duration.Value);
            this.distributedCache       = distributedCache;
            this.logger    = logger;
            this.urlHelper = urlHelper;
        }
Exemplo n.º 20
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddResponseCaching();

            services.AddMvc(options =>
            {
                var homeProfile = new CacheProfile();
                //homeProfile.Duration = Configuration.GetValue<int>("ResponseCache:Home:Duration");
                //homeProfile.Location = Configuration.GetValue<ResponseCacheLocation>("ResponseCache:Home:Location");
                //homeProfile.VaryByQueryKeys = new string[] { "page" };
                Configuration.Bind("ResponseCache:Home", homeProfile);
                options.CacheProfiles.Add("Home", homeProfile);

                options.ModelBinderProviders.Insert(0, new DecimalModelBinderProvider());
            }).SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
            #if DEBUG
            .AddRazorRuntimeCompilation()
            #endif
            ;

            //Usiamo ADO.NET o Entity Framework Core per l'accesso ai dati?
            var persistence = Persistence.AdoNet;
            switch (persistence)
            {
            case Persistence.AdoNet:
                services.AddTransient <ICourseService, AdoNetCourseService>();
                services.AddTransient <ILessonService, AdoNetLessonService>();
                services.AddTransient <IDatabaseAccessor, SqliteDatabaseAccessor>();
                break;

            case Persistence.EfCore:
                services.AddTransient <ICourseService, EfCoreCourseService>();
                services.AddTransient <ILessonService, EfCoreLessonService>();
                services.AddDbContextPool <MyCourseDbContext>(optionsBuilder => {
                    string connectionString = Configuration.GetSection("ConnectionStrings").GetValue <string>("Default");
                    optionsBuilder.UseSqlite(connectionString);
                });
                break;
            }

            services.AddTransient <ICachedCourseService, MemoryCacheCourseService>();
            services.AddTransient <ICachedLessonService, MemoryCacheLessonService>();
            services.AddSingleton <IImagePersister, MagickNetImagePersister>();

            //Options
            services.Configure <CoursesOptions>(Configuration.GetSection("Courses"));
            services.Configure <ConnectionStringsOptions>(Configuration.GetSection("ConnectionStrings"));
            services.Configure <MemoryCacheOptions>(Configuration.GetSection("MemoryCache"));
            services.Configure <KestrelServerOptions>(Configuration.GetSection("Kestrel"));
        }
Exemplo n.º 21
0
        private static void Configure(MvcOptions options)
        {
            var cacheProfile = new CacheProfile()
            {
                Duration        = 30,
                Location        = ResponseCacheLocation.Any,
                NoStore         = false,
                VaryByQueryKeys = new[] { "*" }
            };

            options.CacheProfiles.Add("default", cacheProfile);

            options.Filters.Add <GlobalExceptionFilter>();
            options.Filters.Add <DomainExceptionFilter>();
        }
Exemplo n.º 22
0
    public void ResponseCacheCanSetVaryByQueryKeys(CacheProfile cacheProfile, string[] varyOutput, string cacheControlOutput)
    {
        // Arrange
        var executor = new ResponseCacheFilterExecutor(cacheProfile);
        var context  = GetActionExecutingContext();

        context.HttpContext.Features.Set <IResponseCachingFeature>(new ResponseCachingFeature());

        // Acts
        executor.Execute(context);

        // Assert
        Assert.Equal(varyOutput, context.HttpContext.Features.Get <IResponseCachingFeature>().VaryByQueryKeys);
        Assert.Equal(cacheControlOutput, context.HttpContext.Response.Headers.CacheControl);
    }
Exemplo n.º 23
0
        public void Clear(CacheProfile cacheProfile, string keyPrefix = null)
        {
            if (!_session.EnsureConnectionIsOpen())
            {
                return;
            }

            string[] keys = Keys(cacheProfile, keyPrefix).ToArray();

            if (keys.Length > 0)
            {
                var task = _session.Connection.Keys.Remove(cacheProfile.CacheId, keys);
                _session.Connection.Wait(task);
            }
        }
Exemplo n.º 24
0
        public void ApplyCacheProfile_SetsPragmaOnNoCache_CacheControlSetTonoStoreNoCachePragmaSetToNoCache()
        {
            var cacheProfile = new CacheProfile
            {
                Duration     = 0,
                Location     = ResponseCacheLocation.None,
                NoStore      = true,
                VaryByHeader = null
            };
            var context = new DefaultHttpContext();

            context.ApplyCacheProfile(cacheProfile);

            Assert.Equal("no-store,no-cache", context.Response.Headers[HeaderNames.CacheControl]);
            Assert.Equal("no-cache", context.Response.Headers[HeaderNames.Pragma]);
        }
Exemplo n.º 25
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddResponseCaching();
            services.AddRazorPages();
            services.AddMvc(options => {
                var HomeProfile = new CacheProfile();
                //HomeProfile.Duration = Configuration.GetValue<int>("ResponseCache:Home:Duration");
                //HomeProfile.Location = Configuration.GetValue<ResponseCacheLocation>("ResponseCache:Home:Location");
                //HomeProfile.VaryByQueryKeys = new string[] {"page"};
                Configuration.Bind("ResponseCache:Home", HomeProfile);
                options.CacheProfiles.Add("Home", HomeProfile);
            }).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

            //ado net
            //services.AddTransient<IPasswordService, AdoNetPasswordService>();
            //services.AddTransient<IDatabaseAccessor, SqLiteDatabaseAccessor>();

            //ef core
            services.AddDefaultIdentity <ApplicationUser>(var_Options => {
                var_Options.Password.RequireDigit           = true;
                var_Options.Password.RequiredLength         = 8;
                var_Options.Password.RequireUppercase       = true;
                var_Options.Password.RequireLowercase       = true;
                var_Options.Password.RequireNonAlphanumeric = true;
                var_Options.Password.RequiredUniqueChars    = 4;
                var_Options.SignIn.RequireConfirmedAccount  = true;
            })
            .AddClaimsPrincipalFactory <CustomClaimsPrincipalFactory>()
            .AddPasswordValidator <CommonPasswordValidator <ApplicationUser> >()
            .AddEntityFrameworkStores <PasswordDbContext>();

            services.AddTransient <IPasswordService, EFCorePasswordService>();
            services.AddDbContextPool <PasswordDbContext>(optionsBuilder => {
                String ConnectionString = Configuration.GetSection("ConnectionStrings").GetValue <String>("Default");
                optionsBuilder.UseSqlite(ConnectionString);
            });

            services.AddTransient <ICachedPasswordService, MemoryCachedPasswordService>();
            services.AddSingleton <IImagePersister, MagickNetImagePersister>();
            services.AddSingleton <IEmailSender, MailKitEmailSender>();

            //Options
            services.Configure <MemoryCacheOptions>(Configuration.GetSection("MemoryCache"));
            services.Configure <PasswordsOptions>(Configuration.GetSection("Passwords"));
            services.Configure <ConnectionStringsOptions>(Configuration.GetSection("ConnectionStrings"));
            services.Configure <KestrelServerOptions>(Configuration.GetSection("Kestrel"));
        }
        public static IServiceCollection AddMvcWithFilters(this IServiceCollection services, IConfiguration configuration)
        {
            var siteSettings = new SiteSettings(configuration);

            services
            .AddControllersWithViews(options =>
            {
                options.Filters.Add <SiteSettingsFilter>();

                var defaultCacheProfile = new CacheProfile {
                    Location = ResponseCacheLocation.Any, Duration = siteSettings.DefaultCacheDuration, NoStore = siteSettings.DefaultCacheDuration <= 0
                };
                options.CacheProfiles.Add("Default", defaultCacheProfile);
            });

            return(services);
        }
Exemplo n.º 27
0
        private MemoryCache GetMemoryCache(CacheProfile cacheProfile)
        {
            var cacheId = cacheProfile.CacheId;

            if (!_caches.ContainsKey(cacheId))
            {
                lock (_caches)
                {
                    if (!_caches.ContainsKey(cacheId))
                    {
                        _caches.Add(cacheId, new MemoryCache(cacheId.ToString()));
                    }
                }
            }

            return(_caches[cacheId]);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SitemapService" /> class.
        /// </summary>
        /// <param name="cacheProfileSettings">The cache profile settings.</param>
        /// <param name="distributedCache">The distributed cache for the application.</param>
        /// <param name="logger">The <see cref="SitemapService"/> logger.</param>
        // $Start-ApplicationInsights$
        /// <param name="telemetryClient">The Azure Application Insights telemetry client.</param>
        // $End-ApplicationInsights$
        /// <param name="urlHelper">The URL helper.</param>
        public SitemapService(
            IOptions <CacheProfileSettings> cacheProfileSettings,
            IDistributedCache distributedCache,
            ILogger <SitemapService> logger,
            // $Start-ApplicationInsights$
            TelemetryClient telemetryClient,
            // $End-ApplicationInsights$
            IUrlHelper urlHelper)
        {
            CacheProfile cacheProfile = cacheProfileSettings.Value.CacheProfiles[CacheProfileName.SitemapNodes];

            this.expirationDuration = TimeSpan.FromSeconds(cacheProfile.Duration.Value);
            this.distributedCache   = distributedCache;
            this.logger             = logger;
            // $Start-ApplicationInsights$
            this.telemetryClient = telemetryClient;
            // $End-ApplicationInsights$
            this.urlHelper = urlHelper;
        }
Exemplo n.º 29
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SitemapService" /> class.
        /// </summary>
        /// <param name="cacheProfileSettings">The cache profile settings.</param>
        /// <param name="distributedCache">The distributed cache for the application.</param>
        /// <param name="logger">The <see cref="SitemapService"/> logger.</param>
        /// <param name="urlHelper">The URL helper.</param>
        public SitemapService(
            IOptions <CacheProfileSettings> cacheProfileSettings,
            IDistributedCache distributedCache,
            ILogger <SitemapService> logger,
#if (ApplicationInsights)
            TelemetryClient telemetryClient,
#endif
            IUrlHelper urlHelper)
        {
            CacheProfile cacheProfile = cacheProfileSettings.Value.CacheProfiles[CacheProfileName.SitemapNodes];

            _expirationDuration = TimeSpan.FromSeconds(cacheProfile.Duration.Value);
            _distributedCache   = distributedCache;
            _logger             = logger;
#if (ApplicationInsights)
            this.telemetryClient = telemetryClient;
#endif
            _urlHelper = urlHelper;
        }
Exemplo n.º 30
0
    /// <summary>
    /// Uses the static files middleware to serve static files. Also adds the Cache-Control and Pragma HTTP
    /// headers. The cache duration is controlled from configuration.
    /// See http://andrewlock.net/adding-cache-control-headers-to-static-files-in-asp-net-core/.
    /// </summary>
    public static IApplicationBuilder UseStaticFilesWithCacheControl(this IApplicationBuilder application)
    {
        CacheProfile cacheProfile = application
                                    .ApplicationServices
                                    .GetRequiredService <CacheProfileOptions>()
                                    .Where(x => string.Equals(x.Key, CacheProfileName.StaticFiles, StringComparison.Ordinal))
                                    .Select(x => x.Value)
                                    .SingleOrDefault();

        application.UseStaticFiles(
            new StaticFileOptions()
        {
            OnPrepareResponse = context =>
            {
                context.Context.ApplyCacheProfile(cacheProfile);
            },
        });

        return(application);
    }
Exemplo n.º 31
0
 /// <summary>
 /// Creates a new instance of <see cref="ResponseCacheFilter"/>
 /// </summary>
 /// <param name="cacheProfile">The profile which contains the settings for
 /// <see cref="ResponseCacheFilter"/>.</param>
 public ResponseCacheFilter(CacheProfile cacheProfile)
 {
     _cacheProfile = cacheProfile;
 }