/// <summary> /// Opens the component. /// </summary> /// <param name="correlationId">(optional) transaction id to trace execution through call chain.</param> public virtual async Task OpenAsync(string correlationId) { if (_sshEnabled) { await MsSqlWithSshOpenAsync(correlationId); } else { var connectionString = await _connectionResolver.ResolveAsync(correlationId); _logger.Trace(correlationId, "Connecting to sqlserver..."); try { var settings = ComposeSettings(); var connString = connectionString.TrimEnd(';') + ";" + JoinParams(settings); _connection = new SqlConnection(connString); _databaseName = _connection.Database; // Try to connect await _connection.OpenAsync(); _logger.Debug(correlationId, "Connected to sqlserver database {0}", _databaseName); } catch (Exception ex) { throw new ConnectionException(correlationId, "CONNECT_FAILED", "Connection to sqlserver failed", ex); } } }
protected async Task CreateSchemaAsync(string correlationId) { if (_schemaStatements == null || _schemaStatements.Count == 0) { return; } // If table already exists then exit if (await TableExistAsync(correlationId, _tableName)) { return; } _logger.Debug(correlationId, "Table {0} does not exist. Creating database objects...", _tableName); // Run all DML commands try { foreach (var dml in _schemaStatements) { await ExecuteNonQuery(correlationId, dml); } } catch (Exception ex) { _logger.Error(correlationId, ex, "Failed to autocreate database object"); throw; } }
/// <summary> /// Opens the component. /// </summary> /// <param name="correlationId">(optional) transaction id to trace execution through call chain.</param> public async virtual Task OpenAsync(string correlationId) { var uri = await _connectionResolver.ResolveAsync(correlationId); _logger.Trace(correlationId, "Connecting to mongodb..."); try { _connection = new MongoClient(uri); _databaseName = MongoUrl.Create(uri).DatabaseName; _database = _connection.GetDatabase(_databaseName); // Check if connection is alive if (_areSessionsSupported) { await _connection.StartSessionAsync(); } _logger.Debug(correlationId, "Connected to mongodb database {0}", _databaseName); } catch (Exception ex) { throw new ConnectionException(correlationId, "ConnectFailed", "Connection to mongodb failed", ex); } await Task.Delay(0); }
/// <summary> /// Opens the component. /// </summary> /// <param name="correlationId">(optional) transaction id to trace execution through call chain.</param> public async Task OpenAsync(string correlationId) { var options = await _connectionResolver.ResolveAsync(correlationId); var opts = ConnectionFactory.GetDefaultOptions(); opts.AllowReconnect = _retryConnect; opts.MaxReconnect = _maxReconnect; opts.ReconnectWait = _reconnectTimeout; var uri = options.GetAsString("uri"); opts.Servers = uri.Split(','); var username = options.GetAsString("username"); if (!string.IsNullOrEmpty(username)) { opts.User = username; var password = options.GetAsString("password"); opts.Password = password; } var token = options.GetAsString("token"); if (!string.IsNullOrEmpty(token)) { opts.Token = token; } try { var connection = new ConnectionFactory().CreateConnection(opts); _connection = connection; } catch (Exception ex) { _logger.Error(correlationId, ex, "Failed to connect to NATS broker at " + uri); throw ex; } _logger.Debug(correlationId, "Connected to NATS broker at " + uri); }
/// <summary> /// Closes component and frees used resources. /// </summary> /// <param name="correlationId">(optional) transaction id to trace execution through call chain.</param> public virtual Task CloseAsync(string correlationId) { if (IsOpen()) { _logger.Debug(correlationId, "Closed Direct client {0}", this.GetType().Name); } _opened = false; return(Task.Delay(0)); }
/// <summary> /// Opens the component. /// </summary> /// <param name="correlationId">(optional) transaction id to trace execution through call chain.</param> public async virtual Task OpenAsync(string correlationId) { var connection = await _connectionResolver.ResolveAsync(correlationId); var protocol = connection.Protocol; var host = connection.Host; var port = connection.Port; _address = protocol + "://" + host + ":" + port; _client?.Dispose(); _client = new HttpClient(new HttpClientHandler { CookieContainer = new CookieContainer(), AllowAutoRedirect = true, UseCookies = true }); _client.DefaultRequestHeaders.ConnectionClose = true; _logger.Debug(correlationId, "Connected via REST to {0}", _address); }
public void All_loggers_should_receive_call_with_injected_caller_info() { var logger1 = Substitute.For <ILogger>(); var logger2 = Substitute.For <ILogger>(); var compositeLogger = new CompositeLogger(logger1, logger2); var className = "CompositeLoggerTest.cs"; var methodName = "All_loggers_should_receive_call_with_injected_caller_info"; var invokationLineNumber = 22; var message = "TestMessage"; compositeLogger.Debug(message); logger1.Received().Debug(message, methodName, Arg.Is <string>(x => x.EndsWith(className)), invokationLineNumber); logger2.Received().Debug(message, methodName, Arg.Is <string>(x => x.EndsWith(className)), invokationLineNumber); }
protected async virtual Task <NpgsqlConnection> CreateAndOpenConnectionAsync(string correlationId) { _logger.Trace(correlationId, "Connecting to postgres..."); try { var connection = new NpgsqlConnection(_connectionString); // Try to connect await connection.OpenAsync(); _logger.Debug(correlationId, "Connected to postgres database {0}", connection.Database); return(connection); } catch (Exception ex) { throw new ConnectionException(correlationId, "CONNECT_FAILED", "Connection to postgres failed", ex); } }
/// <summary> /// Opens the component. /// </summary> /// <param name="correlationId">(optional) transaction id to trace execution through call chain.</param> public async virtual Task OpenAsync(string correlationId) { var uri = await _connectionResolver.ResolveAsync(correlationId); _logger.Trace(correlationId, "Connecting to mongodb"); try { _connection = new MongoClient(uri); var databaseName = MongoUrl.Create(uri).DatabaseName; _database = _connection.GetDatabase(databaseName); _collection = _database.GetCollection <T>(_collectionName); _logger.Debug(correlationId, "Connected to mongodb database {0}, collection {1}", databaseName, _collectionName); } catch (Exception ex) { throw new ConnectionException(correlationId, "ConnectFailed", "Connection to mongodb failed", ex); } await Task.Delay(0); }
public async Task OpenAsync(string correlationId, ConnectionParams connection, CredentialParams credential) { if (connection == null) { throw new ConfigException(correlationId, "NO_CONNECTION", "Database connection is not set"); } var uri = connection.Uri; var host = connection.Host; var port = connection.Port; var databaseName = connection.GetAsNullableString("database"); if (uri != null) { databaseName = MongoUrl.Create(uri).DatabaseName; } else { if (host == null) { throw new ConfigException(correlationId, "NO_HOST", "Connection host is not set"); } if (port == 0) { throw new ConfigException(correlationId, "NO_PORT", "Connection port is not set"); } if (databaseName == null) { throw new ConfigException(correlationId, "NO_DATABASE", "Connection database is not set"); } } _logger.Trace(correlationId, "Connecting to mongodb database {0}, collection {1}", databaseName, _collectionName); try { if (uri != null) { _connection = new MongoClient(uri); } else { var settings = new MongoClientSettings { Server = new MongoServerAddress(host, port), MaxConnectionPoolSize = _options.GetAsInteger("poll_size"), ConnectTimeout = _options.GetAsTimeSpan("connect_timeout"), //SocketTimeout = // new TimeSpan(options.GetInteger("server.socketOptions.socketTimeoutMS")* // TimeSpan.TicksPerMillisecond) }; if (credential.Username != null) { settings.Credential = MongoCredential.CreateCredential(databaseName, credential.Username, credential.Password); } _connection = new MongoClient(settings); } _database = _connection.GetDatabase(databaseName); _collection = _database.GetCollection <T>(_collectionName); _logger.Debug(correlationId, "Connected to mongodb database {0}, collection {1}", databaseName, _collectionName); } catch (Exception ex) { throw new ConnectionException(correlationId, "ConnectFailed", "Connection to mongodb failed", ex); } await Task.Delay(0); }
/// <summary> /// Opens the component. /// </summary> /// <param name="correlationId">(optional) transaction id to trace execution through call chain.</param> public async Task OpenAsync(string correlationId) { var options = await _connectionResolver.ResolveAsync(correlationId); var opts = new MqttClientOptionsBuilder() .WithClientId(_clientId); if (_keepAliveTimeout > 0) { opts.WithKeepAlivePeriod(TimeSpan.FromMilliseconds(_keepAliveTimeout)); } else { opts.WithNoKeepAlive(); } var uri = options.GetAsString("servers") ?? ""; var servers = uri.Split(','); foreach (var server in servers) { var host = server; var port = 1883; var pos = server.IndexOf(":"); if (pos > 0) { host = server.Substring(0, pos); Int32.TryParse(server.Substring(pos + 1), out port); } opts.WithTcpServer(host, port); } var username = options.GetAsString("username"); if (!string.IsNullOrEmpty(username)) { var password = options.GetAsString("password"); opts.WithCredentials(username, password); } //opts.SetAutoReconnect(c.retryConnect) //opts.SetConnectTimeout(time.Millisecond * time.Duration(c.connectTimeout)) //opts.SetConnectRetryInterval(time.Millisecond * time.Duration(c.reconnectTimeout)) var client = new MqttFactory().CreateMqttClient(); client.UseDisconnectedHandler(DisconnectedHandlerAsync); client.UseApplicationMessageReceivedHandler(MessageReceiveHandlerAsync); try { await client.ConnectAsync(opts.Build()); } catch (Exception ex) { _logger.Error(correlationId, ex, "Failed to connect to MQTT broker at " + uri); throw ex; } _connection = client; _clientOptions = opts.Build(); _logger.Debug(correlationId, "Connected to MQTT broker at " + uri); }