本文整理汇总了C#中Npgsql.NpgsqlConnection.OpenAsync方法的典型用法代码示例。如果您正苦于以下问题:C# NpgsqlConnection.OpenAsync方法的具体用法?C# NpgsqlConnection.OpenAsync怎么用?C# NpgsqlConnection.OpenAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Npgsql.NpgsqlConnection
的用法示例。
在下文中一共展示了NpgsqlConnection.OpenAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Create
private async Task<string> Create()
{
string sql;
var assembly = typeof(TestDatabase).GetTypeInfo().Assembly;
using (var reader = new StreamReader(assembly.GetManifestResourceStream(_sqlFile)))
{
sql = await reader.ReadToEndAsync();
}
var dbName = await CreateDatabase();
var connectionString = $"Server=localhost;Port=5432;Database={_databaseName};User Id=postgres;Password=s1mpl3;";
using (var connection = new NpgsqlConnection(connectionString))
{
await connection.OpenAsync();
using (var command = connection.CreateCommand())
{
foreach (
var statement in
Regex.Split(sql, @"^\s*GO\s*$", RegexOptions.Multiline)
.Where(s => !string.IsNullOrWhiteSpace(s)))
{
//_logger.LogDebug(sql);
command.CommandText = statement;
await command.ExecuteNonQueryAsync();
}
}
}
return _connectionString = connectionString;
}
示例2: AddSqlConnectionBuilder
public static IServiceCollection AddSqlConnectionBuilder(this IServiceCollection collection,
string configuration)
{
var connection = new NpgsqlConnection(configuration);
connection.OpenAsync();
collection.AddTransient(provider => connection);
return collection;
}
示例3: GetConnection
/// <summary>
/// Gets a fresh, open and ready-to-use connection wrapper
/// </summary>
public async Task<PostgresConnection> GetConnection()
{
var connection = new NpgsqlConnection(_connectionString);
await connection.OpenAsync();
var currentTransaction = connection.BeginTransaction(IsolationLevel.ReadCommitted);
return new PostgresConnection(connection, currentTransaction);
}
示例4: CheckConnection
public static async Task<bool> CheckConnection(string connectionString)
{
if (string.IsNullOrWhiteSpace(connectionString))
throw new ArgumentException("The argument may not be null or empty", nameof(connectionString));
using (var connection = new NpgsqlConnection(connectionString))
{
await connection.OpenAsync();
return connection.State == ConnectionState.Open;
}
}
示例5: OpenConnectionAsync
public async Task<DbConnection> OpenConnectionAsync()
{
if (string.IsNullOrWhiteSpace(_connectionString))
{
throw new InvalidOperationException("Connection to PostgreSQL MicroGarden Settings storage is not configured yet. Consider using UseMicroGardenSettingsPostgreSQLStore in Configure");
}
var connection = new NpgsqlConnection(_connectionString);
await connection.OpenAsync();
return connection;
}
示例6: GetLatestStreamCreated
public static async Task<EventStream> GetLatestStreamCreated()
{
using (var connection = new NpgsqlConnection(GetConnectionStringBuilder()))
{
await connection
.OpenAsync()
.ConfigureAwait(false);
var query = await connection
.QueryAsync<EventStream>(SelectLatestStreamSql)
.ConfigureAwait(false);
return query.Any()
? query.Single()
: default(EventStream);
}
}
示例7: ConfigureServices
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
var logger = Factory.CreateLogger("Web.Exception");
options.InputFormatters.Clear();
options.OutputFormatters.Clear();
options.Filters.Add(new ExceptionFilter(logger, new JsonExceptionPage()));
options.InputFormatters.Add(new JsonInputFormatter());
options.OutputFormatters.Add(new JsonStandardMediaTypeFormatter());
});
services.AddTransient<IEmailService, EmailService>(
provider => new EmailService(Configuration["Email:Host"], Configuration["Email:UserName"],
Configuration["Email:Password"], Configuration["Email:From"],
Int32.Parse(Configuration["Email:Port"])));
var connection = new NpgsqlConnection(Configuration["Data:Npgsql:ConnectionString"]);
connection.OpenAsync();
services.AddTransient<DbConnection>(provider => connection);
services.AddBasicAuthentication();
var repositoryConfig = new DefaultDapperRepositoryOptions<SigmaUser>(connection,
new SigmaPropertyStore(connection));
services
.StartAuthenticationConfiguration<SigmaUser>()
.AddRepositories(repositoryConfig)
.AddEmailProvider(Configuration["Email:Host"], Configuration["Email:UserName"],
Configuration["Email:Password"], Configuration["Email:From"],
int.Parse(Configuration["Email:Port"]))
.AddLoggers(Factory)
.ConfigureLoginOptions(new LoginManagerOptions<SigmaUser>
{
ClaimsProvider =
new ClaimsProvider<SigmaUser>(repositoryConfig.UserStore, repositoryConfig.UserRoleStore,
new ClaimTypesOptions())
})
.BuildManagers();
}
示例8: TestPostgres
private static async Task TestPostgres()
{
try
{
using (var cn = new NpgsqlConnection("Host=localhost;Username=postgres;Password=secretsquirrel"))
{
await cn.OpenAsync();
using (var cmd = new NpgsqlCommand("CREATE DATABASE simple", cn))
{
await cmd.ExecuteNonQueryAsync();
}
System.Console.WriteLine("Created database");
}
} catch {}
try
{
using (var cn = new NpgsqlConnection("Host=localhost;Username=postgres;Password=secretsquirrel;Database=simple"))
{
await cn.OpenAsync();
using (var cmd = new NpgsqlCommand("CREATE TABLE Starships (Id integer not null, Name varchar(100) not null)", cn))
{
await cmd.ExecuteNonQueryAsync();
}
using (var cmd = new NpgsqlCommand("INSERT INTO Starships VALUES (42, 'Heart of Gold')", cn))
{
await cmd.ExecuteNonQueryAsync();
}
System.Console.WriteLine("Created table");
}
} catch {}
var db = new SimpleData().Open(@"Host=localhost;Username=postgres;Password=secretsquirrel;Database=simple",
typeof(PostgresAdapter));
var starship = await db.Starships.GetById(42);
Console.WriteLine(starship.Name);
}
示例9: CreateDatabase
private async Task<string> CreateDatabase()
{
_databaseName = $"simple_{Guid.NewGuid():N}".ToLowerInvariant();
var connectionString = $"Server=localhost;Port=5432;Database=postgres;User Id=postgres;Password=s1mpl3;";
using (var connection = new NpgsqlConnection(connectionString))
{
await connection.OpenAsync();
using (var cmd = connection.CreateCommand())
{
cmd.CommandText = $"CREATE DATABASE {_databaseName} WITH OWNER = postgres ENCODING = 'UTF8' CONNECTION LIMIT = -1;";
_logger.LogDebug(cmd.CommandText);
try
{
await cmd.ExecuteNonQueryAsync();
}
catch (Exception ex)
{
_logger.LogError(42999, ex, "Failed to CREATE DATABASE");
}
}
}
return _databaseName;
}
示例10: ConnectionRefusedAsync
public void ConnectionRefusedAsync(bool pooled)
{
var csb = new NpgsqlConnectionStringBuilder(ConnectionString) { Port = 44444, Pooling = pooled };
using (var conn = new NpgsqlConnection(csb))
{
Assert.That(async () => await conn.OpenAsync(), Throws.Exception
.TypeOf<SocketException>()
.With.Property(nameof(SocketException.SocketErrorCode)).EqualTo(SocketError.ConnectionRefused)
);
Assert.That(conn.FullState, Is.EqualTo(ConnectionState.Closed));
}
}
示例11: CreateEventStream
public static async Task CreateEventStream(Guid streamId, string streamName)
{
using (var connection = new NpgsqlConnection(GetConnectionStringBuilder()))
{
await connection
.OpenAsync()
.ConfigureAwait(false);
using (var command = connection.CreateCommand())
{
command.CommandText = CreateEventStreamSql;
command.Parameters.AddWithValue("@streamId", streamId);
command.Parameters.AddWithValue("@streamName", streamName);
command.Parameters.AddWithValue("@createdOn", DateTime.UtcNow);
await command
.ExecuteNonQueryAsync()
.ConfigureAwait(false);
}
}
}
示例12: GetStreamEvents
public static async Task<IEnumerable<StoredEvent>> GetStreamEvents(Guid streamId)
{
using (var connection = new NpgsqlConnection(GetConnectionStringBuilder()))
{
await connection
.OpenAsync()
.ConfigureAwait(false);
var query = await connection
.QueryAsync<StoredEvent>(SelectStreamEventsSql)
.ConfigureAwait(false);
return query.ToList();
}
}
示例13: CreateConnectionAsync
private async Task<NpgsqlConnection> CreateConnectionAsync(CancellationToken cancellationToken = default(CancellationToken))
{
var con = new NpgsqlConnection(ConnectionString);
await con.OpenAsync(cancellationToken).ConfigureAwait(false);
//TODO: Research server settings.
return con;
}
示例14: OpenConnection
private async Task<NpgsqlConnection> OpenConnection()
{
var conn = new NpgsqlConnection(_connectionStringBuilder);
await conn
.OpenAsync()
.ConfigureAwait(false);
return conn;
}
示例15: ConnectTimeoutAsync
public void ConnectTimeoutAsync()
{
var unknownIp = Environment.GetEnvironmentVariable("NPGSQL_UNKNOWN_IP");
if (unknownIp == null)
TestUtil.IgnoreExceptOnBuildServer("NPGSQL_UNKNOWN_IP isn't defined and is required for connection timeout tests");
var csb = new NpgsqlConnectionStringBuilder(ConnectionString)
{
Host = unknownIp,
Pooling = false,
Timeout = 2
};
using (var conn = new NpgsqlConnection(csb))
{
Assert.That(async () => await conn.OpenAsync(), Throws.Exception.TypeOf<TimeoutException>());
Assert.That(conn.State, Is.EqualTo(ConnectionState.Closed));
}
}