当前位置: 首页>>代码示例>>C#>>正文


C# NpgsqlConnection.OpenAsync方法代码示例

本文整理汇总了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;
        }
开发者ID:RendleLabs,项目名称:Simple.Data.Core,代码行数:31,代码来源:TestDatabase.cs

示例2: AddSqlConnectionBuilder

 public static IServiceCollection AddSqlConnectionBuilder(this IServiceCollection collection,
     string configuration)
 {
     var connection = new NpgsqlConnection(configuration);
     connection.OpenAsync();
     collection.AddTransient(provider => connection);
     return collection;
 }
开发者ID:interopbyt,项目名称:InkySigma,代码行数:8,代码来源:SqlConnectionBuilder.cs

示例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);
        }
开发者ID:RichieYang,项目名称:Rebus,代码行数:13,代码来源:PostgresConnectionHelper.cs

示例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;
         }
      }
开发者ID:henrik-m,项目名称:linqpad-postgresql-driver,代码行数:11,代码来源:ConnectionHelper.cs

示例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;
        }
开发者ID:chaliy,项目名称:microgarden-settings,代码行数:12,代码来源:NpgsqlConnectionService.cs

示例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);
            }
        }
开发者ID:carlos-vicente,项目名称:Playground,代码行数:17,代码来源:DatabaseHelper.cs

示例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();
        }
开发者ID:inkysigma,项目名称:InkySigma,代码行数:45,代码来源:Startup.cs

示例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);
        }
开发者ID:RendleLabs,项目名称:Simple.Data.Core,代码行数:41,代码来源:Program.cs

示例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;
 }
开发者ID:RendleLabs,项目名称:Simple.Data.Core,代码行数:23,代码来源:TestDatabase.cs

示例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));
     }
 }
开发者ID:npgsql,项目名称:npgsql,代码行数:12,代码来源:ConnectionTests.cs

示例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);
                }
            }
        }
开发者ID:carlos-vicente,项目名称:Playground,代码行数:21,代码来源:DatabaseHelper.cs

示例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();
            }
        }
开发者ID:carlos-vicente,项目名称:Playground,代码行数:15,代码来源:DatabaseHelper.cs

示例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;
        }
开发者ID:docevaad,项目名称:Chain,代码行数:9,代码来源:PostgreSqlDataSource.cs

示例14: OpenConnection

 private async Task<NpgsqlConnection> OpenConnection()
 {
     var conn = new NpgsqlConnection(_connectionStringBuilder);
     await conn
         .OpenAsync()
         .ConfigureAwait(false);
     return conn;
 }
开发者ID:carlos-vicente,项目名称:Playground,代码行数:8,代码来源:EventRepository.cs

示例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));
            }
        }
开发者ID:npgsql,项目名称:npgsql,代码行数:18,代码来源:ConnectionTests.cs


注:本文中的Npgsql.NpgsqlConnection.OpenAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。