private string ResolveConnectionString(string connectionStringName) { // Multi-tenancy unaware contexts should always use the host connection string if (typeof(TDbContext).IsDefined(typeof(IgnoreMultiTenancyAttribute), false)) { using (_currentTenant.Change(null)) { return(_connectionStringResolver.Resolve(connectionStringName)); } } return(_connectionStringResolver.Resolve(connectionStringName)); }
public TDbContext GetDbContext() { Logger.LogWarning( "UnitOfWorkDbContextProvider.GetDbContext is deprecated. Use GetDbContextAsync instead! " + "You are probably using LINQ (LINQ extensions) directly on a repository. In this case, use repository.GetQueryableAsync() method " + "to obtain an IQueryable<T> instance and use LINQ (LINQ extensions) on this object. " ); Logger.LogWarning(Environment.StackTrace.Truncate(2048)); var unitOfWork = _unitOfWorkManager.Current; if (unitOfWork == null) { throw new AbpException("A DbContext can only be created inside a unit of work!"); } var connectionStringName = ConnectionStringNameAttribute.GetConnStringName <TDbContext>(); var connectionString = _connectionStringResolver.Resolve(connectionStringName); var dbContextKey = $"{typeof(TDbContext).FullName}_{connectionString}"; var databaseApi = unitOfWork.GetOrAddDatabaseApi( dbContextKey, () => new EfCoreDatabaseApi <TDbContext>( CreateDbContext(unitOfWork, connectionStringName, connectionString) )); return(((EfCoreDatabaseApi <TDbContext>)databaseApi).DbContext); }
public TMongoDbContext GetDbContext() { var unitOfWork = _unitOfWorkManager.Current; if (unitOfWork == null) { throw new AbpException( $"A {nameof(IMongoDatabase)} instance can only be created inside a unit of work!"); } var connectionString = _connectionStringResolver.Resolve <TMongoDbContext>(); var dbContextKey = $"{typeof(TMongoDbContext).FullName}_{connectionString}"; var mongoUrl = new MongoUrl(connectionString); var databaseName = mongoUrl.DatabaseName; if (databaseName.IsNullOrWhiteSpace()) { databaseName = ConnectionStringNameAttribute.GetConnStringName <TMongoDbContext>(); } //TODO: Create only single MongoDbClient per connection string in an application (extract MongoClientCache for example). var databaseApi = unitOfWork.GetOrAddDatabaseApi( dbContextKey, () => new MongoDbDatabaseApi <TMongoDbContext>(CreateDbContext(unitOfWork, mongoUrl, databaseName))); return(((MongoDbDatabaseApi <TMongoDbContext>)databaseApi).DbContext); }
public IMongoDatabase GetDatabase() { var unitOfWork = _unitOfWorkManager.Current; if (unitOfWork == null) { throw new AbpException($"A {nameof(IMongoDatabase)} instance can only be created inside a unit of work!"); } var connectionString = _connectionStringResolver.Resolve <TMongoDbContext>(); var dbContextKey = $"{typeof(TMongoDbContext).FullName}_{connectionString}"; string databaseName; if (connectionString.Contains("|")) { var splitted = connectionString.Split('|'); connectionString = splitted[0]; databaseName = splitted[1]; } else { databaseName = ConnectionStringNameAttribute.GetConnStringName <TMongoDbContext>(); } //TODO: Create only single MongoDbClient per connection string in an application (extract MongoClientCache for example). var databaseApi = unitOfWork.GetOrAddDatabaseApi( dbContextKey, () => new MongoDbDatabaseApi( new MongoClient(connectionString).GetDatabase(databaseName) )); return(((MongoDbDatabaseApi)databaseApi).Database); }
public Dog3DapperRepository(IConnectionStringResolver connectionStringResolver) { string connectionString = connectionStringResolver.Resolve("DogStore"); //_dbConnection = new Microsoft.Data.SqlClient.SqlConnection(connectionString); _dbConnection = new MySqlConnection(connectionString); }
public TMongoDbContext GetDbContext() { var unitOfWork = _unitOfWorkManager.Current; if (unitOfWork == null) { throw new RocketException($"A {nameof(IMongoDatabase)} instance can only be created inside a unit of work!"); } var connectionString = _connectionStringResolver.Resolve <TMongoDbContext> (); var dbContextKey = $"{typeof(TMongoDbContext).FullName}_{connectionString}"; var mongoUrl = new MongoUrl(connectionString); var databaseName = mongoUrl.DatabaseName; if (databaseName.IsNullOrWhiteSpace()) { databaseName = ConnectionStringNameAttribute.GetConnStringName <TMongoDbContext> (); } //TODO: 考虑创建一个单例的客户端 MongoDbClient (除了作为示例 MongoClientCache). var databaseApi = unitOfWork.GetOrAddDatabaseApi( dbContextKey, () => { var database = new MongoClient(mongoUrl).GetDatabase(databaseName); var dbContext = unitOfWork.ServiceProvider.GetRequiredService <TMongoDbContext> (); dbContext.ToRocketMongoDbContext().InitializeDatabase(database); return(new MongoDbDatabaseApi <TMongoDbContext> (dbContext)); }); return(((MongoDbDatabaseApi <TMongoDbContext>)databaseApi).DbContext); }
public TMongoDbContext GetDbContext() { Logger.LogWarning( "UnitOfWorkDbContextProvider.GetDbContext is deprecated. Use GetDbContextAsync instead! " + "You are probably using LINQ (LINQ extensions) directly on a repository. In this case, use repository.GetQueryableAsync() method " + "to obtain an IQueryable<T> instance and use LINQ (LINQ extensions) on this object. " ); Logger.LogWarning(Environment.StackTrace.Truncate(2048)); var unitOfWork = _unitOfWorkManager.Current; if (unitOfWork == null) { throw new AbpException( $"A {nameof(IMongoDatabase)} instance can only be created inside a unit of work!"); } var connectionString = _connectionStringResolver.Resolve <TMongoDbContext>(); var dbContextKey = $"{typeof(TMongoDbContext).FullName}_{connectionString}"; var mongoUrl = new MongoUrl(connectionString); var databaseName = mongoUrl.DatabaseName; if (databaseName.IsNullOrWhiteSpace()) { databaseName = ConnectionStringNameAttribute.GetConnStringName <TMongoDbContext>(); } //TODO: Create only single MongoDbClient per connection string in an application (extract MongoClientCache for example). var databaseApi = unitOfWork.GetOrAddDatabaseApi( dbContextKey, () => new MongoDbDatabaseApi <TMongoDbContext>(CreateDbContext(unitOfWork, mongoUrl, databaseName))); return(((MongoDbDatabaseApi <TMongoDbContext>)databaseApi).DbContext); }
/// <summary> /// The core upsert implementation. /// </summary> /// <param name="event">The event to be upserted.</param> /// <returns>The updated event.</returns> /// <exception cref="Veritema.Data.ScheduleException"> /// The event must start in the future. /// or /// The event must end after it starts. /// or /// The event must be at least 30 minutes in duration. /// </exception> private async Task <Event> UpsertKernelAsync(Event @event) { string connectionString = _resolver.Resolve(ConnectionStringName) .Match( Some: v => v, None: () => { throw new ConfigurationErrorsException($"Cannot load the configuration string with name {{{ConnectionStringName}}}"); } ); if (@event.StartUtc < DateTime.UtcNow) { throw new ScheduleException("The event must start in the future."); } if (@event.EndUtc < @event.StartUtc) { throw new ScheduleException("The event must end after it starts."); } if (@event.EndUtc < @event.StartUtc.AddMinutes(30)) { throw new ScheduleException("The event must be at least 30 minutes in duration."); } string sql = LoadScript("UpsertEvent.Sql"); using (var connection = new SqlConnection(connectionString)) { var record = new EventRecord { Id = @event.Id > -1 ? @event.Id : 0, Title = @event.Title, Details = @event.Description, End = new DateTimeOffset(@event.EndUtc), Start = new DateTimeOffset(@event.StartUtc), Confirmed = @event.Confirmed, StyleId = @event.Style.HasValue ? (int)@event.Style.Value : new int?(), LocationId = @event.Location != null ? @event.Location.Id : new int?(), Updated = DateTimeOffset.Now, TypeId = (char)@event.Type }; record = await connection.QueryFirstAsync <EventRecord>(sql, record); @event = new Event { Id = record.Id, Title = record.Title, Description = record.Details, EndUtc = record.End.UtcDateTime, StartUtc = record.Start.UtcDateTime, Confirmed = record.Confirmed, Style = record.StyleId.HasValue ? (MartialArtStyle)record.StyleId.Value : new MartialArtStyle?(), Location = record.LocationId.HasValue ? await _locationLoader.GetAsync(record.LocationId.Value) : null, Updated = record.Updated, Type = (EventType)record.TypeId }; } return(@event); }
public TDbContext GetDbContext() { if (!(_unitOfWorkManager.Current is EfUnitOfWork uow)) { throw new NotSupportedException($"UnitOfWork is not type of {typeof(EfUnitOfWork).FullName}."); } var connectionString = _connectionStringResolver.Resolve <TDbContext>(); return(uow.GetOrCreateDbContext <TDbContext>(connectionString)); }
public IMemoryDatabase GetDatabase() { var unitOfWork = _unitOfWorkManager.Current; if (unitOfWork == null) { throw new AbpException($"A {nameof(IMemoryDatabase)} instance can only be created inside a unit of work!"); } var connectionString = _connectionStringResolver.Resolve <TMemoryDbContext>(); var dbContextKey = $"{typeof(TMemoryDbContext).FullName}_{connectionString}"; var databaseApi = unitOfWork.GetOrAddDatabaseApi( dbContextKey, () => new MemoryDbDatabaseApi( _memoryDatabaseManager.Get(connectionString) )); return(((MemoryDbDatabaseApi)databaseApi).Database); }
/// <summary> /// Gets the defined locations. /// </summary> /// <returns>The set of locations.</returns> public async Task <IEnumerable <Location> > GetAsync() { string connectionString = _resolver.Resolve(ConnectionStringName) .Match( Some: v => v, None: () => { throw new ConfigurationErrorsException($"Cannot load the configuration string with name {{{ConnectionStringName}}}"); } ); string sql = LoadScript("QueryLocations.sql"); IEnumerable <Location> locations; using (var connection = new SqlConnection(connectionString)) { var records = await connection.QueryAsync(sql); locations = records.Select(i => Map(i)).Cast <Location>().ToArray(); } return(locations); }
/// <summary> /// Deletes the event asynchronously. /// </summary> /// <param name="id">The event identifier.</param> public async Task DeleteAsync(long id) { string connectionString = _resolver.Resolve(ConnectionStringName) .Match( Some: v => v, None: () => { throw new ConfigurationErrorsException($"Cannot load the configuration string with name {{{ConnectionStringName}}}"); } ); using (var connection = new SqlConnection(connectionString)) { await connection.ExecuteAsync("DELETE from [v].[Event] where Id = @id", new { id = id }); } }
public Dfhv(IOptions <Option> options, IRazorLightEngine razorLightEngine, INameResolver nameResolver, IConnectionStringResolver connectionStringResolver) { _razorLightEngine = razorLightEngine; _nameResolver = nameResolver; _connectionStringResolver = connectionStringResolver; _option = options.Value; var connectionName = _option.AzureStorageConnectionStringName ?? ConnectionStringNames.Storage; var resolvedStorageConnectionString = _connectionStringResolver.Resolve(connectionName); var account = CloudStorageAccount.Parse(resolvedStorageConnectionString); _tableClient = account.CreateCloudTableClient(); _blobClient = account.CreateCloudBlobClient(); _handler = new HttpHandler(_tableClient, _option.HubName, _razorLightEngine, this); }
public RedisDurabilityProviderFactory(IOptions <DurableTaskOptions> options, IConnectionStringResolver connectionStringResolver) { this.defaultConnectionName = options.Value.StorageProvider["connectionName"] as string; string redisConnectionString = connectionStringResolver.Resolve(this.defaultConnectionName); this.defaultHubName = options.Value.HubName; this.connectionResolver = connectionStringResolver; var defaultTaskHubService = new RedisOrchestrationService(new RedisOrchestrationServiceSettings() { TaskHubName = this.defaultHubName, RedisConnectionString = redisConnectionString, }); this.defaultProvider = new DurabilityProvider("Redis", defaultTaskHubService, defaultTaskHubService, this.defaultConnectionName); }
internal SqlOrchestrationServiceSettings GetOrchestrationServiceSettings( DurableTaskOptions extensionOptions, IConnectionStringResolver connectionStringResolver) { if (connectionStringResolver == null) { throw new ArgumentNullException(nameof(connectionStringResolver)); } string?connectionString = connectionStringResolver.Resolve(this.ConnectionStringName); if (string.IsNullOrEmpty(connectionString)) { throw new InvalidOperationException( $"No SQL connection string configuration was found for the app setting or environment variable named '{this.ConnectionStringName}'."); } // Validate the connection string try { new SqlConnectionStringBuilder(connectionString); } catch (ArgumentException e) { throw new ArgumentException("The provided connection string is invalid.", e); } var settings = new SqlOrchestrationServiceSettings(connectionString, this.TaskHubName) { CreateDatabaseIfNotExists = this.CreateDatabaseIfNotExists, LoggerFactory = this.LoggerFactory, WorkItemBatchSize = this.TaskEventBatchSize, WorkItemLockTimeout = this.TaskEventLockTimeout, }; if (extensionOptions.MaxConcurrentActivityFunctions.HasValue) { settings.MaxConcurrentActivities = extensionOptions.MaxConcurrentActivityFunctions.Value; } if (extensionOptions.MaxConcurrentOrchestratorFunctions.HasValue) { settings.MaxActiveOrchestrations = extensionOptions.MaxConcurrentOrchestratorFunctions.Value; } return(settings); }
/// <summary> /// Issue the specified TSQL query against the backing store. /// </summary> /// <param name="tsql">The TSQL to be executed.</param> /// <param name="parameters">The request parameters.</param> /// <returns>The meterialized events.</returns> private async Task <IEnumerable <Person> > QueryAsync(string tsql, object parameters) { string connectionString = _resolver.Resolve(ConnectionStringName) .Match( Some: v => v, None: () => { throw new ConfigurationErrorsException($"Cannot load the configuration string with name {{{ConnectionStringName}}}"); } ); IEnumerable <Person> people; using (var connection = new SqlConnection(connectionString)) { var records = await connection.QueryAsync(tsql, parameters); people = records.Map(i => ToPerson(i)).Cast <Person>().ToArray(); } return(people); }
/// <summary> /// Issue the specified TSQL query against the backing store. /// </summary> /// <param name="tsql">The TSQL to be executed.</param> /// <param name="parameters">The request parameters.</param> /// <returns>The meterialized events.</returns> private async Task <IEnumerable <Event> > Query(string tsql, object parameters) { string connectionString = _resolver.Resolve(ConnectionStringName) .Match( Some: v => v, None: () => { throw new ConfigurationErrorsException($"Cannot load the configuration string with name {{{ConnectionStringName}}}"); } ); IEnumerable <Event> events; using (var connection = new SqlConnection(connectionString)) { var records = await connection.QueryAsync <EventRecord>(tsql, parameters); events = records.Select((async(i) => await MapAsync(i))).Select(i => i.Result).ToArray(); } return(events); }
public TDbContext GetDbContext() { var unitOfWork = _unitOfWorkManager.Current; if (unitOfWork == null) { throw new Exception("A DbContext can only be created inside a unit of work!"); } var connectionStringName = ConnectionStringNameAttribute.GetConnStringName <TDbContext>(); var connectionString = _connectionStringResolver.Resolve(connectionStringName); var dbContextKey = $"{typeof(TDbContext).FullName}_{connectionString}"; var databaseApi = unitOfWork.GetOrAddDatabaseApi(dbContextKey, () => new EfCoreDatabaseApi <TDbContext>(CreateDbContext(unitOfWork, connectionStringName, connectionString) )); return(((EfCoreDatabaseApi <TDbContext>)databaseApi).DbContext); }
private static StorageAccountDetails GetStorageAccountDetailsOrNull(IConnectionStringResolver connectionStringResolver, string connectionName) { if (string.IsNullOrEmpty(connectionName)) { return(null); } string resolvedStorageConnectionString = connectionStringResolver.Resolve(connectionName); if (string.IsNullOrEmpty(resolvedStorageConnectionString)) { throw new InvalidOperationException($"Unable to resolve the Azure Storage connection named '{connectionName}'."); } return(new StorageAccountDetails { ConnectionString = resolvedStorageConnectionString, }); }
public TDbContext GetDbContext <TDbContext>() where TDbContext : AbpDbContext { var unitOfWork = _unitOfWorkManager.Current; if (unitOfWork == null) { throw new AbpException("A DbContext can only be created inside a unit of work!"); } var connectionStringName = typeof(TDbContext).Name; var connectionString = _connectionStringResolver.Resolve <TDbContext>(); var dbContextKey = $"{typeof(TDbContext).FullName}:{unitOfWork.Options.IsTransactional}:{connectionString}"; var databaseProvider = _connectionStringResolver.GetDatabaseProvider(); var databaseApi = unitOfWork.GetOrAddDatabaseApi( dbContextKey, () => new EfCoreDatabaseApi <TDbContext>( CreateDbContext <TDbContext>(unitOfWork, connectionStringName, connectionString, databaseProvider) )); return(((EfCoreDatabaseApi <TDbContext>)databaseApi).DbContext); }
public TRavenDbContext GetDbContext() { IUnitOfWork unitOfWork; try { unitOfWork = _unitOfWorkManager.Current; } catch (Exception e) { Console.WriteLine(e); throw; } if (unitOfWork == null) { throw new AbpException($"A {nameof(IAsyncDocumentSession)} instance can only be created inside a unit of work!"); } var connectionString = _connectionStringResolver.Resolve <TRavenDbContext>(); var dbContextKey = $"{typeof(TRavenDbContext).FullName}_{connectionString}"; var databaseApi = unitOfWork.GetOrAddDatabaseApi( dbContextKey, () => { var dbContext = unitOfWork.ServiceProvider.GetRequiredService <TRavenDbContext>(); var session = RavenFactory.Store.OpenAsyncSession(); //dbContext.ToAbpMongoDbContext().InitializeDatabase(database); return(new RavenDbDatabaseApi <TRavenDbContext>(dbContext)); }); return(((RavenDbDatabaseApi <TRavenDbContext>)databaseApi).DbContext); }
/// <summary> /// 获取或创建数据库上下文 /// </summary> /// <param name="dbContextType">数据库上下文类型</param> /// <param name="name">名称</param> /// <returns>数据库上下文对象</returns> public virtual DbContext GetOrCreateDbContext() { // 获取连接字符串 var nameOrConnectionString = _connectionStringResolver.Resolve(this.GetConnectionStringName()); // 缓存键值 var dbContextKey = this.GetDbContextKey(nameOrConnectionString); DbContext dbContext; if (!ActiveDbContexts.TryGetValue(dbContextKey, out dbContext)) { if (Options.IsTransactional == true) { dbContext = _transactionStrategy.CreateDbContext(nameOrConnectionString, _dbContextResolver, this._dbContextProviderName); } else { dbContext = _dbContextResolver.Resolve(nameOrConnectionString, null, this.Options, this._dbContextProviderName); } if (Options.Timeout.HasValue && dbContext.Database.IsRelational() && !dbContext.Database.GetCommandTimeout().HasValue) { var commandTimeout = Convert.ToInt32(Options.Timeout.Value.TotalSeconds); //dbContext.Database.SetCommandTimeout(Options.Timeout.Value.TotalSeconds.To<int>()); dbContext.Database.SetCommandTimeout(commandTimeout); } //TODO: Object materialize event //TODO: Apply current filters to this dbcontext ActiveDbContexts[dbContextKey] = dbContext; } return(dbContext); }
public void All_Tests() { //No tenant in current context _connectionResolver.Resolve().ShouldBe("default-value"); _connectionResolver.Resolve("db1").ShouldBe("db1-default-value"); //Overrided connection strings for tenant1 using (_currentTenant.Change(_tenant1Id)) { _connectionResolver.Resolve().ShouldBe("tenant1-default-value"); _connectionResolver.Resolve("db1").ShouldBe("tenant1-db1-value"); } //No tenant in current context _connectionResolver.Resolve().ShouldBe("default-value"); _connectionResolver.Resolve("db1").ShouldBe("db1-default-value"); //Undefined connection strings for tenant2 using (_currentTenant.Change(_tenant2Id)) { _connectionResolver.Resolve().ShouldBe("default-value"); _connectionResolver.Resolve("db1").ShouldBe("db1-default-value"); } }
public TVfpContext GetDbContext() { var unitOfWork = _unitOfWorkManager.Current; if (unitOfWork == null) { throw new AbpException($"A {nameof(Database)} instance can only be created inside a unit of work!"); } var connectionString = _connectionStringResolver.Resolve <TVfpContext>(); var dbContextKey = $"{typeof(TVfpContext).FullName}_{connectionString}"; //var mongoUrl = new MongoUrl(connectionString); string databaseName = @"D:\GitHub\dados\SincaTeste.dbc"; //mongoUrl.DatabaseName; if (databaseName.IsNullOrWhiteSpace()) { databaseName = ConnectionStringNameAttribute.GetConnStringName <TVfpContext>(); } //TODO: Create only single MongoDbClient per connection string in an application (extract MongoClientCache for example). var databaseApi = unitOfWork.GetOrAddDatabaseApi( dbContextKey, () => { var database = new DbContext(new VfpConnection(@"D:\GitHub\dados\SincaTeste.dbc"), true); var dbContext = unitOfWork.ServiceProvider.GetRequiredService <TVfpContext>(); dbContext.ToAbpVfpContext().InitializeDatabase(database.Database); return(new VfpDatabaseApi <TVfpContext>(dbContext)); }); return(((VfpDatabaseApi <TVfpContext>)databaseApi).DbContext); }
public ConnectionContext GetCurrentConnectionContext() { return(new ConnectionContext(_connectionStringResolver.Resolve())); }
/// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="resolver"></param> /// <returns></returns> public static string Resolve <T>(this IConnectionStringResolver resolver) { return(resolver.Resolve(ConnectionStringNameAttribute.GetConnStringName <T>())); }
public static string Resolve <T>(this IConnectionStringResolver resolver) { return(resolver.Resolve(typeof(T))); }
public static string Resolve(this IConnectionStringResolver resolver, Type type) { return(resolver.Resolve(ConnectionStringNameAttribute.GetConnStringName(type))); }
/// <summary> /// 获取当前的连接和事务信息 /// </summary> /// <returns></returns> public virtual ActiveTransactionInfo GetActiveTransactionInfo() { var nameOrConnectionString = _connectionStringResolver.Resolve(this.GetConnectionStringName()); return(this._transactionStrategy.GetActiveTransactionInfo(nameOrConnectionString)); }