public override void Initialize(string store) { lock (_lock) { if (IsInitialized) { Logger.Technical().From <SqlCache>().Debug($"Sql Cache {store} is already initialized.").Log(); return; } Name = store; if (Container.TryResolve <IKeyValueSettings>(store, out var settings)) { if (settings.Values.ContainsKey(ConnectionStringKey)) { ConnectionString = settings.Values[ConnectionStringKey]; } if (settings.Values.ContainsKey(TableNameKey)) { TableName = settings.Values[TableNameKey]; } if (settings.Values.ContainsKey(SchemaNameKey)) { SchemaName = settings.Values[SchemaNameKey]; } if (settings.Values.ContainsKey(SerializerNameKey)) { SerializerName = settings.Values[SerializerNameKey]; } else { SerializerName = store; } var option = new SqlServerCacheOptions { ConnectionString = ConnectionString, TableName = TableName, SchemaName = SchemaName }; DistributeCache = new SqlServerCache(option); if (!Container.TryResolve <IObjectSerialization>(SerializerName, out var serializerFactory)) { SerializerFactory = Container.Resolve <IObjectSerialization>(); } else { SerializerFactory = serializerFactory; } IsInitialized = true; Logger.Technical().From <SqlCache>().System($"Sql Cache {store} is initialized.").Log(); } } }
protected internal override void AddInternal(IDistributedCacheBuilder builder) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } var sqlServerCacheOptions = new SqlServerCacheOptions(); this.BindSqlServerCacheOptions(builder.Configuration, sqlServerCacheOptions); builder.Services.AddDbContext <SqlServerCacheContext>(optionsBuilder => { optionsBuilder.UseSqlServer(sqlServerCacheOptions.ConnectionString, options => { if (this.MigrationsAssembly != null) { options.MigrationsAssembly(this.MigrationsAssembly); } } ); }); builder.Services.AddDistributedSqlServerCache(options => { this.BindSqlServerCacheOptions(builder.Configuration, options); }); }
public SqlCacheService(IDistributedCache distributedCache, IOptions <SqlServerCacheOptions> option) { GuardClausesParameter.Null(option, nameof(option)); _distributedCache = distributedCache; _sqlServerCacheOptions = option.Value; }
private IDistributedCache GetSqlServerCache(SqlServerCacheOptions options = null) { if (options == null) { options = GetCacheOptions(); } return(new SqlServerCache(options)); }
public static void SetDefaults(this SqlServerCacheOptions options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } options.SchemaName = "dbo"; options.TableName = nameof(SqlServerCacheContext.Cache); }
private void SpinUpCache(string sqlConnection) { SqlServerCacheOptions sqlServerCacheOptions = new SqlServerCacheOptions(); sqlServerCacheOptions.ConnectionString = sqlConnection; sqlServerCacheOptions.SchemaName = "dbo"; sqlServerCacheOptions.TableName = "TestCache"; sqlServerCacheOptions.DefaultSlidingExpiration = TimeSpan.FromSeconds(SlidingCacheExpiryTimeInSeconds); _cache = new SqlServerCache(sqlServerCacheOptions); }
/// <summary> /// Constructor with explicit configuration properties. /// </summary> /// <param name="connectionString">See <see cref="SqlServerCacheOptions.ConnectionString" />.</param> /// <param name="schemaName">See <see cref="SqlServerCacheOptions.SchemaName" />.</param> /// <param name="tableName">See <see cref="SqlServerCacheOptions.TableName" />.</param> /// <param name="expiredItemsDeletionInterval">See <see cref="SqlServerCacheOptions.ExpiredItemsDeletionInterval" />.</param> public SqlServerFactory( string connectionString, string schemaName, string tableName, TimeSpan?expiredItemsDeletionInterval) { _options = new SqlServerCacheOptions { ConnectionString = connectionString, SchemaName = schemaName, TableName = tableName, ExpiredItemsDeletionInterval = expiredItemsDeletionInterval }; }
public SqlServerCacheAdapter(IConfiguration configuration) { _expiration = new TimeSpan(0, 0, configuration.GetValue <int>("cacheSeconds")); var options = new SqlServerCacheOptions() { SchemaName = configuration.GetValue <string>("sqlSchema"), TableName = configuration.GetValue <string>("sqlTable"), ConnectionString = configuration.GetValue <string>("sqlConnection"), DefaultSlidingExpiration = _expiration }; _cache = new SqlServerCache(Options.Create <SqlServerCacheOptions>(options)); }
public static void UseSqlServer( this ConcurrencyOptionsBuilder concurrencyOptionsBuilder, Action <SqlServerCacheOptions> callback) { if (callback == null) { throw new ArgumentNullException(nameof(callback)); } var options = new SqlServerCacheOptions(); callback(options); UseSqlServer(concurrencyOptionsBuilder, options); }
public SqlServerStorage(SqlServerCacheOptions options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } var builder = new ServiceCollection(); builder.AddSingleton <IDistributedCache>(serviceProvider => new SqlServerCache(Options.Create(options))); var provider = builder.BuildServiceProvider(); Initialize((IDistributedCache)provider.GetService(typeof(IDistributedCache))); }
public static void UseSqlServer( this ConcurrencyOptionsBuilder concurrencyOptionsBuilder, SqlServerCacheOptions options) { if (concurrencyOptionsBuilder == null) { throw new ArgumentNullException(nameof(concurrencyOptionsBuilder)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } concurrencyOptionsBuilder.ConcurrencyOptions.Storage = new SqlServerStorage(options); }
public static void CacheConfigure(this IServiceCollection services, IConfiguration configuration) { string cacheConfigType = string.Empty; var cacheConfig = configuration.GetSection(CacheConfigurationTypeKey); if (!cacheConfig.Exists()) { return; } cacheConfigType = cacheConfig.Value; switch (cacheConfigType.ToLower()) { case "distributedsqlservercache": var distributedSqlServerCacheOptions = new SqlServerCacheOptions(); configuration.GetSection($"{CacheConfigurationSection}:DistributedSqlServerCache").Bind(distributedSqlServerCacheOptions); services.AddDistributedSqlServerCache(options => { options.ConnectionString = distributedSqlServerCacheOptions.ConnectionString; options.TableName = distributedSqlServerCacheOptions.TableName; options.SchemaName = distributedSqlServerCacheOptions.SchemaName; }); services.AddSingleton <ICacheAdapter, DistributedCacheAdapter>(); break; case "memorycache": services.AddMemoryCache(); services.AddSingleton <ICacheAdapter, MemoryCacheAdapter>(); break; case "distributedmemorycache": services.AddDistributedMemoryCache(); services.AddSingleton <ICacheAdapter, DistributedCacheAdapter>(); break; default: break; } }
public async Task BindSqlServerCacheOptions_IfConfigurationIsEmpty_ShouldWorkProperly() { await Task.CompletedTask; var configurationBuilder = Global.CreateConfigurationBuilder("appsettings.json", "appsettings.SqlServer1.json"); //configurationBuilder.AddInMemoryCollection(new Dictionary<string, string> // { }); var configuration = configurationBuilder.Build(); var services = Global.CreateServices(configuration); services.AddDistributedCache(configuration, Global.HostEnvironment, new InstanceFactory()); await using (var serviceProvider = services.BuildServiceProvider()) { var sqlServerOptions = (SqlServerOptions)serviceProvider.GetRequiredService <DistributedCacheOptions>(); var sqlServerCacheOptions = new SqlServerCacheOptions(); sqlServerOptions.BindSqlServerCacheOptions(new ConfigurationBuilder().Build(), sqlServerCacheOptions); Assert.IsNull(sqlServerCacheOptions.ConnectionString); Assert.AreEqual("dbo", sqlServerCacheOptions.SchemaName); Assert.AreEqual("Cache", sqlServerCacheOptions.TableName); } }
private static int CreateTableAndIndexes(SqlServerCacheOptions options) { using (var connection = new SqlConnection(options.ConnectionString)) { connection.Open(); var sqlQueries = new SqlQueries(options.SchemaName, options.TableName); var command = new SqlCommand(sqlQueries.TableInfo, connection); using (var reader = command.ExecuteReader(CommandBehavior.SingleRow)) { if (reader.Read()) { return(1); } } using (var transaction = connection.BeginTransaction()) { try { command = new SqlCommand(sqlQueries.CreateTable, connection, transaction); command.ExecuteNonQuery(); command = new SqlCommand( sqlQueries.CreateNonClusteredIndexOnExpirationTime, connection, transaction); command.ExecuteNonQuery(); transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); return(1); } } } return(0); }
protected internal override void AddInternal(IDistributedCacheBuilder builder) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } base.AddInternal(builder); var sqlServerOptions = new SqlServerOptions { ConnectionStringName = this.ConnectionStringName, MigrationsAssembly = this.MigrationsAssembly, Options = this.Options }; var sqlServerCacheOptions = new SqlServerCacheOptions(); sqlServerOptions.BindSqlServerCacheOptions(builder.Configuration, sqlServerCacheOptions); builder.Services.AddDbContextFactory <SqlServerCacheContext>(optionsBuilder => { optionsBuilder.UseSqlServer(sqlServerCacheOptions.ConnectionString, options => { if (this.MigrationsAssembly != null) { options.MigrationsAssembly(this.MigrationsAssembly); } }); }); builder.Services.AddSingleton <IDistributedCache, DateTimeOffsetCacheMock>(); builder.Services.Configure <DateTimeOffsetCacheOptionsMock>(options => { this.Options?.Bind(options); }); }
private SqlServerCacheOptions GetSqlServerCacheOptions() { using (log.Activity(m => m($"Executing {nameof(GetSqlServerCacheOptions)}"))) { var option = new SqlServerCacheOptions(); using (log.Activity(m => m($"Read {nameof(SqlServerCacheOptions.ConnectionString)}"))) { var pattern = ConfigurationManager.ConnectionStrings["BD.MedView.Services.Models.CacheContext"]?.ConnectionString; option.ConnectionString = string.IsNullOrWhiteSpace(pattern) ? option.ConnectionString : pattern; } using (log.Activity(m => m($"Read {nameof(SqlServerCacheOptions.SchemaName)}"))) { var pattern = ConfigurationManager.AppSettings["SqlServerCacheOptions:SchemaName"] ?? ConfigurationManager.AppSettings["cache-schema-name"]; option.SchemaName = string.IsNullOrWhiteSpace(pattern) ? "ext" : pattern; } using (log.Activity(m => m($"Read {nameof(SqlServerCacheOptions.TableName)}"))) { var pattern = ConfigurationManager.AppSettings["SqlServerCacheOptions:TableName"] ?? ConfigurationManager.AppSettings["cache-schema-name"]; option.TableName = string.IsNullOrWhiteSpace(pattern) ? "Cache" : pattern; } return(option); } }
public CacheConfiguration(IOptions <SqlServerCacheOptions> options) { _options = options.Value; }
public CacheDbContextModelSnapshot(IOptions <SqlServerCacheOptions> options) { _options = options.Value; }
public void Init() { if (Settings == null) { Settings = new Dictionary <string, string>(); } try { if (!File.Exists(Assembly.GetExecutingAssembly().Location.Replace(".dll", ".json"))) { File.WriteAllText(Assembly.GetExecutingAssembly().Location.Replace(".dll", ".json"), Properties.Resources.Plugin_SQLCache); } if (File.Exists(Assembly.GetExecutingAssembly().Location.Replace(".dll", ".json"))) { JConfig = JObject.Parse(File.ReadAllText(Assembly.GetExecutingAssembly().Location.Replace(".dll", ".json"))); bReadOnly = JConfig["ReadOnly"].Value <bool>(); ContinueAfterWrite = JConfig["ContinueAfterWrite"].Value <bool>(); CacheFull = JConfig["CacheFull"].Value <bool>(); CacheKeys = JConfig["CacheKeys"].Value <bool>(); SQLConnectionString = JConfig["SQLConnectionString"].Value <string>(); SQLTable = JConfig["SQLTable"].Value <string>(); SlidingExpiration = JConfig["SlidingExpiration"].Value <int>(); } else { JConfig = new JObject(); } try { SqlServerCacheOptions oOption = new SqlServerCacheOptions() { ConnectionString = SQLConnectionString, SchemaName = "dbo", TableName = "JCache", DefaultSlidingExpiration = new TimeSpan(0, 0, 0, SlidingExpiration) }; oSrv = new SqlServerCache(oOption); oSrv.SetString("key1", "value1", new DistributedCacheEntryOptions() { SlidingExpiration = new TimeSpan(1000) }); } catch { try { using (SqlConnection connection = new SqlConnection(SQLConnectionString)) { SqlCommand command = new SqlCommand(Properties.Resources.CreateTable, connection); command.Connection.Open(); command.ExecuteNonQuery(); } SqlServerCacheOptions oOption = new SqlServerCacheOptions() { ConnectionString = SQLConnectionString, SchemaName = "dbo", TableName = "JCache", DefaultSlidingExpiration = new TimeSpan(0, 0, 0, SlidingExpiration) }; oSrv = new SqlServerCache(oOption); Console.WriteLine("SQL Table 'JCache' created..."); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } } oSrv.SetString("key1", "value1", new DistributedCacheEntryOptions() { SlidingExpiration = new TimeSpan(1000) }); Console.WriteLine(oSrv.GetString("key1")); } catch { } }
protected internal virtual void BindSqlServerCacheOptions(IConfiguration configuration, SqlServerCacheOptions sqlServerCacheOptions) { if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } if (sqlServerCacheOptions == null) { throw new ArgumentNullException(nameof(sqlServerCacheOptions)); } sqlServerCacheOptions.SetDefaults(); if (this.ConnectionStringName != null) { sqlServerCacheOptions.ConnectionString = configuration.GetConnectionString(this.ConnectionStringName); } this.Options?.Bind(sqlServerCacheOptions); if (string.IsNullOrWhiteSpace(sqlServerCacheOptions.ConnectionString)) { return; } var connectionStringBuilder = new SqlConnectionStringBuilder(sqlServerCacheOptions.ConnectionString); if (string.IsNullOrEmpty(connectionStringBuilder.AttachDBFilename)) { return; } connectionStringBuilder.AttachDBFilename = connectionStringBuilder.AttachDBFilename.ResolveDataDirectorySubstitution(); if (string.IsNullOrEmpty(connectionStringBuilder.InitialCatalog)) { connectionStringBuilder.InitialCatalog = connectionStringBuilder.AttachDBFilename; } sqlServerCacheOptions.ConnectionString = connectionStringBuilder.ToString(); }
/// <summary> /// Constructor with configuration properties. It supports <c>connection-string</c>, <c>schema-name</c>, /// <c>table-name</c> and <c>expired-items-deletion-interval</c> properties. /// See <see cref="SqlServerCacheOptions" />. /// </summary> /// <param name="properties">The configurations properties.</param> /// <remarks> /// If <c>expired-items-deletion-interval</c> is provided as an integer, this integer will be used as a number /// of minutes. Otherwise the setting will be parsed as a <see cref="TimeSpan" />. /// </remarks> public SqlServerFactory(IDictionary <string, string> properties) { _options = new SqlServerCacheOptions(); if (properties == null) { return; } if (properties.TryGetValue(_connectionString, out var connectionString)) { _options.ConnectionString = connectionString; Log.Info("ConnectionString set as '{0}'", connectionString); } else { Log.Warn("No {0} property provided", _connectionString); } if (properties.TryGetValue(_schemaName, out var schemaName)) { _options.SchemaName = schemaName; Log.Info("SchemaName set as '{0}'", schemaName); } else { Log.Warn("No {0} property provided", _schemaName); } if (properties.TryGetValue(_tableName, out var tableName)) { _options.TableName = tableName; Log.Info("TableName set as '{0}'", tableName); } else { Log.Warn("No {0} property provided", _tableName); } if (properties.TryGetValue(_expiredItemsDeletionInterval, out var eidi)) { if (eidi != null) { if (int.TryParse(eidi, out var minutes)) { _options.ExpiredItemsDeletionInterval = TimeSpan.FromMinutes(minutes); } else if (TimeSpan.TryParse(eidi, out var expirationScanFrequency)) { _options.ExpiredItemsDeletionInterval = expirationScanFrequency; } else { Log.Warn( "Invalid value '{0}' for {1} setting: it is neither an int nor a TimeSpan. Ignoring.", eidi, _expiredItemsDeletionInterval); } } else { Log.Warn("Invalid property {0}: it lacks a value. Ignoring.", _expiredItemsDeletionInterval); } } }
public Init_Cache(IOptions <SqlServerCacheOptions> options) { _options = options.Value; }
public void SqlServerOptions(SqlServerCacheOptions obj) { obj.ConnectionString = ConnectionString; obj.SchemaName = "dbo"; obj.TableName = StorageName; }