Exemple #1
0
        public TopicClient CreateTopicClient(string nsName, string topicName, string keyName, string key)
        {
            string           cs = _csp.GetConnectionString(nsName, keyName, key);
            MessagingFactory mf = MessagingFactory.CreateFromConnectionString(cs);

            return(mf.CreateTopicClient(topicName));
        }
Exemple #2
0
        public DataConnection Use(string connectionStringName = null)
        {
            var dbProvider = _providerSource.Provide(connectionStringName);
            var cs         = _connectionStringProvider.GetConnectionString(connectionStringName);

            return(new DataConnection(dbProvider, cs));
        }
Exemple #3
0
        public async Task <IStorageAccount> GetAccountAsync(string connectionStringName, CancellationToken cancellationToken)
        {
            IStorageAccount account   = null;
            var             isPrimary = true;

            if (connectionStringName == ConnectionStringNames.Dashboard)
            {
                account = DashboardAccount;
            }
            else if (connectionStringName == ConnectionStringNames.Storage)
            {
                account = StorageAccount;
            }
            else
            {
                // see if this is a user connnection string (i.e. for multi-account scenarios)
                string connectionString = _ambientConnectionStringProvider.GetConnectionString(connectionStringName);
                if (!string.IsNullOrEmpty(connectionString))
                {
                    account   = ParseAccount(connectionStringName, connectionString);
                    isPrimary = false;
                }
            }

            if (account != null)
            {
                // On the first attempt, this will make a network call to verify the credentials work.
                await _storageCredentialsValidator.ValidateCredentialsAsync(account, isPrimary, cancellationToken);
            }

            return(account);
        }
        public void ExecuteNonQuery(string query)
        {
            using (SqlConnection connection = new SqlConnection(_connectionStringProvider.GetConnectionString()))
            {
                SqlCommand command = new SqlCommand(query)
                {
                    Connection = connection
                };

                connection.Open();
                command.ExecuteNonQuery();
                connection.Close();
            }
        }
Exemple #5
0
        public IDbConnection GetInstance()
        {
            var cn = new SqlConnection(_connectionStringProvider.GetConnectionString());

            cn.Open();
            return(cn);
        }
        public async Task <UserDto> GetAsync(string id)
        {
            _logger.LogDebug("Getting user with id '{0}'.", id);

            var connectionString = await _connectionStringProvider.GetConnectionString();

            await using var connection = new SqlConnection(connectionString);

            var parameters = new Dictionary <string, object>
            {
                { "@Id", id }
            };
            var user = await connection.QuerySingleOrDefaultAsync <UserDto>("GetUser", parameters);

            if (user == null)
            {
                _logger.LogDebug("No user was found with id '{0}'", id);

                throw new NotFoundException(ErrorMessages.UserNotFound);
            }

            _logger.LogDebug("Successfully retrieved user by id '{0}'", id);

            return(user);
        }
Exemple #7
0
        public async Task <IDbConnection> GetConnection()
        {
            var conn = new NpgsqlConnection(ConnectionString.GetConnectionString());
            await conn.OpenAsync();

            return(conn);
        }
        public StrategyRepository(IConnectionStringProvider connectionStringProvider)
        {
            var client   = new MongoClient(connectionStringProvider.GetConnectionString());
            var database = client.GetDatabase(connectionStringProvider.GetDatabase());

            _strategies = database.GetCollection <Strategy>(connectionStringProvider.GetStrategyCollectionName());
        }
        public async Task <IReadOnlyList <RoleListItemDto> > GetListAsync(string term)
        {
            var connectionString = await _connectionStringProvider.GetConnectionString();

            await using var connection = new SqlConnection(connectionString);

            var parameters = new Dictionary <string, object> {
                { "@SearchTerm", $"%{term}%" }
            };
            var roles = (await connection.QueryAsync <RoleListItemDto>("GetRoles", parameters,
                                                                       commandType: CommandType.StoredProcedure)).ToList();

            _logger.LogDebug("Found {0} roles with search term '{1}'", roles.Count, term);

            return(roles);
        }
 public IDbConnection GetDbConnection()
 {
     using (var conn = new SqlConnection(_provider.GetConnectionString()))
     {
         return(conn);
     }
 }
        //--open conection---
        public SqlConnection GetOpenConnection()
        {
            var connection = new SqlConnection(_connectionStringProvider.GetConnectionString());

            connection.Open();
            return(connection);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="args">[repository] [source collection name] [target collection name]</param>
        /// <returns></returns>
        public async Task RunAsync(string[] args)
        {
            var repository = args[0];

            var sourceCollectionName = args[1];

            var targetCollectionName = args[2];

            var client = new MongoClient(_connectionStringProvider.GetConnectionString(repository));

            IMongoDatabase _database = client.GetDatabase(repository);

            IMongoCollection <BsonDocument> targetCollection = _database.GetCollection <BsonDocument>(targetCollectionName);

            IMongoCollection <BsonDocument> sourceCollection = _database.GetCollection <BsonDocument>(sourceCollectionName);

            await sourceCollection.Find(new BsonDocument()).ForEachAsync(async(thread) => {
                foreach (var user in thread.GetElement(targetCollectionName).Value.AsBsonArray)
                {
                    var filter = Builders <BsonDocument> .Filter.Eq("id", user.ToBsonDocument().GetElement("id").Value);

                    var count = await targetCollection.Find(filter).CountAsync();

                    if (count == 0)
                    {
                        await targetCollection.InsertOneAsync(user.ToBsonDocument());
                    }
                }
            });
        }
Exemple #13
0
        public ItemRepository(IConnectionStringProvider connectionStringProvider)
        {
            var databaseUrl = MongoUrl.Create(connectionStringProvider.GetConnectionString());
            var database    = new MongoClient(databaseUrl).GetDatabase(databaseUrl.DatabaseName);

            _itemsCollection = database.GetCollection <Item>("Items");
        }
Exemple #14
0
        protected IDbConnection GetConnection()
        {
            var connection = new SqlConnection(_connectionStringProvider.GetConnectionString());

            connection.Open();
            return(connection);
        }
Exemple #15
0
        public ApiRepositoryContext Build()
        {
            var connection = new SqliteConnection(_connectionStringProvider.GetConnectionString());
            var context    = new ApiRepositoryContext(new DbContextOptionsBuilder <ApiRepositoryContext>().UseSqlite(connection).Options);

            return(context);
        }
 public GCloudContext(IConnectionStringProvider connStringProvider)
     : base(connStringProvider.GetConnectionString())
 {
     // Disable proxy creation and lazy loading; not wanted in this service context.
     Configuration.LazyLoadingEnabled   = false;
     Configuration.ProxyCreationEnabled = false;
 }
Exemple #17
0
        public SimulationRepository(IConnectionStringProvider connectionStringProvider)
        {
            var client   = new MongoClient(connectionStringProvider.GetConnectionString());
            var database = client.GetDatabase(connectionStringProvider.GetDatabase());

            _simulations = database.GetCollection <Simulation>(connectionStringProvider.GetSimulaionCollectionName());
        }
        public void Configure(String targetDir)
        {
            String errMsg = "Not empty";

            while (!String.IsNullOrEmpty(errMsg))
            {
                String connStr = _ConnectionStringProvider.GetConnectionString();
                errMsg = _ConnectionStringValidator.Validate(connStr);

                if (String.IsNullOrEmpty(errMsg))
                {
                    String[] configFiles = Directory.GetFiles(targetDir, "*.config");
                    IConfigurationTextUpdater configUpdater = new ConfigurationTextUpdater();

                    DbType dbType = _ConnectionStringValidator.GetDbType(connStr);
                    IDictionary <String, String> configTerms = new Dictionary <String, String>();

                    String dbTypeString, dbNameString;
                    DbConnectionStringBuilder connStrBldr;

                    if (dbType == DbType.Vfp)
                    {
                        connStrBldr = new OleDbConnectionStringBuilder(connStr);
                        configTerms.Add(new KeyValuePair <String, String>(Constants.ConfigTokenNames.HostDirectory, connStrBldr[Constants.ConnectionStringDetails.DataSourcePropertyName].ToString()));

                        dbTypeString = Constants.ConfigTokenValues.DbTypeVfp;
                        dbNameString = Constants.ConfigTokenValues.DbNameVfp;
                    }
                    else
                    {
                        connStrBldr = new SqlConnectionStringBuilder(connStr);
                        configTerms.Add(new KeyValuePair <String, String>(Constants.ConfigTokenNames.SqlServerName, connStrBldr[Constants.ConnectionStringDetails.DataSourcePropertyName].ToString()));
                        configTerms.Add(new KeyValuePair <String, String>(Constants.ConfigTokenNames.SqlDbName, connStrBldr[Constants.ConnectionStringDetails.InitialCatalogPropertyName].ToString()));

                        dbTypeString = Constants.ConfigTokenValues.DbTypeSql;
                        dbNameString = Constants.ConfigTokenValues.DbNameSql;
                    }

                    configTerms.Add(new KeyValuePair <String, String>(Constants.ConfigTokenNames.DbType, dbTypeString));
                    configTerms.Add(new KeyValuePair <String, String>(Constants.ConfigTokenNames.DbName, dbNameString));

                    foreach (String fileName in configFiles)
                    {
                        IEnumerable <String> configIn  = File.ReadAllLines(fileName);
                        IEnumerable <String> configOut = configUpdater.Update(configIn, configTerms);
                        if (configOut != null)
                        {
                            File.WriteAllLines(fileName, configOut);
                        }
                    }
                }

                else

                {
                    MessageBox.Show(errMsg);
                }
            }
        }
Exemple #19
0
        public IDbConnection GetConnection(string csName = null)
        {
            var conn = new SqlConnection(_connectionStringProvider.GetConnectionString(csName));

            conn.Open();

            return(conn);
        }
Exemple #20
0
 public ImsDbContext(IConnectionStringProvider connectionStringProvider)
     : base(connectionStringProvider.GetConnectionString())
 {
     // This is a hack to ensure that Entity Framework SQL Provider is copied across to the output folder.
     // As it is installed in the GAC, Copy Local does not work. It is required for probing.
     // Fixed "Provider not loaded" error
     var ensureDLLIsCopied = SqlProviderServices.Instance;
 }
Exemple #21
0
 UpgradeEngine GetDbUpEngine()
 {
     return(DeployChanges
            .To
            .SQLiteDatabase(connectionStringProvider.GetConnectionString())
            .WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly())
            .Build());
 }
        public IDbConnection GetDbConnection()
        {
            var conn = new NpgsqlConnection(_connectionStringProvider.GetConnectionString());

            conn.Open();

            return(conn);
        }
Exemple #23
0
            public string GetValue(string value)
            {
                var dbProvider = _providerSource.Provide(null);
                var cs         = _connectionStringProvider.GetConnectionString();

                using var c = new DataConnection(dbProvider, cs);

                return(c.Query <string>($"select \"{value}\";").First());
            }
Exemple #24
0
        public IActionResult Initialize()
        {
            var initialize = new Initialize()
                             .With(connectionStringProvider.GetConnectionString("ConnectionString"))
                             .CreateDatabase()
                             .PopulateDatabase();

            return(RedirectToAction("Index"));
        }
        private void CreateTopicAndSubscriber()
        {
            NamespaceManager nsm = NamespaceManager.CreateFromConnectionString(_csp.GetConnectionString(nsName, nsKeyName, nsKey));

            CreateTopic(nsm);
            initialized = true;

            Task.Run(() => SubscriberTask <string>());
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SqlCommandCacheDependencyEnlister"/> class.
        /// </summary>
        /// <param name="command">The command.</param>
        /// <param name="isStoredProcedure">if set to <c>true</c> [is stored procedure].</param>
        /// <param name="connectionName">Name of the connection.</param>
        /// <param name="connectionStringProvider">The <see cref="IConnectionStringProvider"/> to use 
        ///		to retrieve the connection string to connect to the underlying data store and enlist in query notifications</param>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="command"/> or 
        ///		<paramref name="connectionStringProvider"/> is null or empty.</exception>
        public SqlCommandCacheDependencyEnlister(string command, bool isStoredProcedure, string connectionName,
            IConnectionStringProvider connectionStringProvider)
        {
            //validate the parameters
            if (String.IsNullOrEmpty(command))
            {
                throw new ArgumentNullException("command");
            }

            if (connectionStringProvider == null)
            {
                throw new ArgumentNullException("connectionStringProvider");
            }

            this.command = command;
            this.isStoredProcedure = isStoredProcedure;
            this.connectionName = connectionName;

            connectionString = String.IsNullOrEmpty(this.connectionName) ? connectionStringProvider.GetConnectionString() : connectionStringProvider.GetConnectionString(this.connectionName);
        }
        protected virtual void ConfigureDatabase(Configuration config)
        {
            var connectionString = connectionStringProvider.GetConnectionString();

            config.DataBaseIntegration(x => {
                x.Driver <MonoSafeSQLite20Driver>();
                x.Dialect <SQLiteDialect>();
                x.ConnectionString      = connectionString;
                x.ConnectionReleaseMode = ConnectionReleaseMode.OnClose;
            });
        }
        public DatabaseFactory(IConnectionStringProvider connectionStringProvider, IMappingProvider mappingProvider)
        {
            DatabaseFactoryConfigOptions options = new DatabaseFactoryConfigOptions();

            var connectionString = connectionStringProvider.GetConnectionString();
            var mappings         = mappingProvider.GetMappings();

            options.Database        = () => new LoggingDatabase(connectionString);
            options.PocoDataFactory = FluentMappingConfiguration.Configure(mappings);

            databaseFactory = new NPoco.DatabaseFactory(options);
        }
        public DatabaseFactory(IConnectionStringProvider connectionStringProvider, IMappingProvider mappingProvider)
        {
            DatabaseFactoryConfigOptions options = new DatabaseFactoryConfigOptions();

            var connectionString = connectionStringProvider.GetConnectionString();
            var mappings = mappingProvider.GetMappings();

            options.Database = () => new LoggingDatabase(connectionString);
            options.PocoDataFactory = FluentMappingConfiguration.Configure(mappings);

            databaseFactory = new NPoco.DatabaseFactory(options);
        }
Exemple #30
0
        public DapperUnitOfWork(IConnectionStringProvider connectionStringProvider)
        {
            var        connectionString = connectionStringProvider.GetConnectionString();
            IDbFactory dbFactory        = new SqlDbFactory(connectionString);

            Db = dbFactory;
            if (Db.Context().State != ConnectionState.Open)
            {
                Db.Context().Open();
            }
            DbTransaction = Db.Context().BeginTransaction();
        }
Exemple #31
0
        /// <summary>
        /// 构建<see cref="DbContextOptionsBuilder"/>,附加必要的扩展属性
        /// </summary>
        public static DbContextOptionsBuilder BuildDbContextOptionsBuilder <TDbContext>(this IServiceProvider provider, DbContextOptionsBuilder builder)
            where TDbContext : DbContext
        {
            Type                   dbContextType          = typeof(TDbContext);
            OsharpOptions          osharpOptions          = provider.GetOSharpOptions();
            OsharpDbContextOptions osharpDbContextOptions = osharpOptions?.GetDbContextOptions(dbContextType);

            if (osharpDbContextOptions == null)
            {
                throw new OsharpException($"无法找到数据上下文 {dbContextType.DisplayName()} 的配置信息");
            }

            ILogger logger = provider.GetLogger(typeof(ServiceExtensions));

            //启用延迟加载
            if (osharpDbContextOptions.LazyLoadingProxiesEnabled)
            {
                builder = builder.UseLazyLoadingProxies();
                logger.LogDebug($"数据上下文类型 {dbContextType} 应用延迟加载代理");
            }
            DatabaseType databaseType = osharpDbContextOptions.DatabaseType;

            //处理数据库驱动差异处理
            IDbContextOptionsBuilderDriveHandler driveHandler = provider.GetServices <IDbContextOptionsBuilderDriveHandler>()
                                                                .LastOrDefault(m => m.Type == databaseType);

            if (driveHandler == null)
            {
                throw new OsharpException($"无法解析类型为 {databaseType} 的 {typeof(IDbContextOptionsBuilderDriveHandler).DisplayName()} 实例,是否未在Startup执行AddPack<{databaseType}DefaultDbContextMigrationPack>()");
            }

            //选择主/从数据库连接串
            IConnectionStringProvider connectionStringProvider = provider.GetRequiredService <IConnectionStringProvider>();
            string connectionString = connectionStringProvider.GetConnectionString(typeof(TDbContext));

            ScopedDictionary scopedDictionary = provider.GetRequiredService <ScopedDictionary>();
            string           key = $"DbConnection_{connectionString}";
            DbConnection     existingDbConnection = scopedDictionary.GetValue <DbConnection>(key);

            builder = driveHandler.Handle(builder, connectionString, existingDbConnection);

            //使用模型缓存
            DbContextModelCache modelCache = provider.GetService <DbContextModelCache>();
            IModel model = modelCache?.Get(dbContextType);

            if (model != null)
            {
                builder = builder.UseModel(model);
            }

            return(builder);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="args">[repository] [user collection name] [thread collection name] [target collection name]</param>
        /// <returns></returns>
        public async Task RunAsync(string[] args)
        {
            var repository = args[0];

            var threadCollectionName = args[1];

            var client = new MongoClient(_connectionStringProvider.GetConnectionString(string.Format("mongo:{0}", repository)));

            var database = client.GetDatabase(repository);

            var threadCollection = database.GetCollection <BsonDocument>(threadCollectionName);

            var list = await threadCollection.Find("{}").ToListAsync();

            using (var scope = new EmitScope(new SqlConnection(_connectionStringProvider.GetConnectionString("EasIndexConnection"))))
            {
                list.ForEach(item =>
                {
                    ExtractInThread(item, scope);
                });
            }
        }
 public SqlConnectionProvider(IConnectionStringProvider connectionStringProvider, string connectionName)
 {
     _connectionString = connectionStringProvider.GetConnectionString(connectionName);
 }
 public MSSQLDatabaseEngine(IConnectionStringProvider provider)
 {
     _connectionString = provider.GetConnectionString();
 }