public async Task using_ISqlConnectionController_extension_methods_asynchronous() { string tableName = "CK.t" + Guid.NewGuid().ToString( "N" ); var create = new SqlCommand( $"create table {tableName} ( id int, name varchar(10) ); insert into {tableName}(id,name) values (1,'One'), (2,'Two'), (3,'Three');" ); var scalar = new SqlCommand( $"select name from {tableName} where id=@Id;" ); scalar.Parameters.AddWithValue( "@Id", 3 ); var row = new SqlCommand( $"select top 1 id, name from {tableName} order by id;" ); var reader = new SqlCommand( $"select id, name from {tableName} order by id;" ); var clean = new SqlCommand( $"drop table {tableName};" ); using( var ctx = new SqlStandardCallContext( TestHelper.Monitor ) ) { ISqlConnectionController c = ctx[TestHelper.GetConnectionString()]; c.Connection.State.Should().Be( ConnectionState.Closed ); await c.ExecuteNonQueryAsync( create ); (await c.ExecuteScalarAsync( scalar )).Should().Be( "Three" ); var rowResult = await c.ExecuteSingleRowAsync( row, r => Tuple.Create( r.GetInt32( 0 ), r.GetString( 1 ) ) ); rowResult.Item1.Should().Be( 1 ); rowResult.Item2.Should().Be( "One" ); var readerResult = await c.ExecuteReaderAsync( reader, r => Tuple.Create( r.GetInt32( 0 ), r.GetString( 1 ) ) ); readerResult.Should().HaveCount( 3 ); readerResult[0].Item1.Should().Be( 1 ); readerResult[1].Item2.Should().Be( "Two" ); readerResult[2].Item2.Should().Be( "Three" ); await c.ExecuteNonQueryAsync( clean ); } }
void AsyncCallCatch <TException>(string cmd, string connectionString = null) { using (IDisposableSqlCallContext c = new SqlStandardCallContext(TestHelper.Monitor)) using (var command = new SqlCommand(cmd)) { ISqlConnectionController con = c[connectionString ?? TestHelper.GetConnectionString()]; try { // If the asynchronous process is lost (if the exception is not correctly managed), // this test will fail with a task Cancelled exception after: // - 30 second when testing for connection string.... because when trying to resolve a bad server name it takes a loooooooong time. // - 1 second in other cases. CancellationTokenSource source = new CancellationTokenSource(); source.CancelAfter(connectionString == null ? 1000 : 30 * 1000); con.ExecuteNonQueryAsync(command, source.Token) .Wait(); } catch (AggregateException ex) { Assert.That(ex.GetBaseException(), Is.InstanceOf <TException>()); } } }