forked from dotnet/SqlClient
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApiShould.cs
3240 lines (2700 loc) · 164 KB
/
ApiShould.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.SqlClient.AlwaysEncrypted.AzureKeyVaultProvider;
using Microsoft.Data.SqlClient.ManualTesting.Tests.AlwaysEncrypted.Setup;
using Microsoft.Data.SqlClient.ManualTesting.Tests.SystemDataInternals;
using Xunit;
namespace Microsoft.Data.SqlClient.ManualTesting.Tests.AlwaysEncrypted
{
/// <summary>
/// Always Encrypted public API Manual tests.
/// </summary>
public sealed class ApiShould : IClassFixture<PlatformSpecificTestContext>, IDisposable
{
private SQLSetupStrategy _fixture;
private readonly string _tableName;
private Dictionary<string, SqlColumnEncryptionKeyStoreProvider> _requiredProvider = new()
{
{ DummyKeyStoreProvider.Name, new DummyKeyStoreProvider() }
};
private const string NotRequiredProviderName = "DummyProvider2";
private Dictionary<string, SqlColumnEncryptionKeyStoreProvider> _notRequiredProvider = new()
{
{ NotRequiredProviderName, new DummyKeyStoreProvider() }
};
private string _failedToDecryptMessage;
private string _providerNotFoundMessage = string.Format(
SystemDataResourceManager.Instance.TCE_UnrecognizedKeyStoreProviderName,
DummyKeyStoreProvider.Name,
"'MSSQL_CERTIFICATE_STORE', 'MSSQL_CNG_STORE', 'MSSQL_CSP_PROVIDER'",
$"'{NotRequiredProviderName}'");
public ApiShould(PlatformSpecificTestContext context)
{
_fixture = context.Fixture;
_tableName = _fixture.ApiTestTable.Name;
ApiTestTable _customKeyStoreProviderTable = _fixture.CustomKeyStoreProviderTestTable as ApiTestTable;
byte[] encryptedCek = _customKeyStoreProviderTable.columnEncryptionKey1.EncryptedValue;
string _lastTenBytesCek = BitConverter.ToString(encryptedCek, encryptedCek.Length - 10, 10);
_failedToDecryptMessage = string.Format(SystemDataResourceManager.Instance.TCE_KeyDecryptionFailed,
DummyKeyStoreProvider.Name, _lastTenBytesCek);
}
[ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringSetupForAE))]
[ClassData(typeof(AEConnectionStringProviderWithBooleanVariable))]
public void TestSqlTransactionCommitRollbackWithTransparentInsert(string connection, bool isCommitted)
{
CleanUpTable(connection, _tableName);
using SqlConnection sqlConnection = new(connection);
sqlConnection.Open();
Customer customer = new Customer(40, "Microsoft", "Corporation");
// Start a transaction and either commit or rollback based on the test variation.
using (SqlTransaction sqlTransaction = sqlConnection.BeginTransaction())
{
DatabaseHelper.InsertCustomerData(sqlConnection, sqlTransaction, _tableName, customer);
if (isCommitted)
{
sqlTransaction.Commit();
}
else
{
sqlTransaction.Rollback();
}
}
// Data should be available on select if committed else, data should not be available.
if (isCommitted)
{
DatabaseHelper.VerifyRecordPresent(sqlConnection, customer, _tableName);
}
else
{
DatabaseHelper.VerifyRecordAbsent(sqlConnection, customer, _tableName);
}
}
[ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringSetupForAE))]
[ClassData(typeof(AEConnectionStringProvider))]
public void TestSqlTransactionRollbackToSavePoint(string connection)
{
CleanUpTable(connection, _tableName);
using (SqlConnection sqlConnection = new SqlConnection(connection))
{
sqlConnection.Open();
// Start a new transaction, with isolation level as read uncommitted, so we will be able to read the inserted records without committing.
using (SqlTransaction sqlTransaction = sqlConnection.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted))
{
// Insert row no:1 and Save the state of the transaction to a named check point.
Customer customer1 = new(50, "Microsoft2", "Corporation2");
DatabaseHelper.InsertCustomerData(sqlConnection, sqlTransaction, _tableName, customer1);
sqlTransaction.Save(@"checkpoint");
// Insert row no:2
Customer customer2 = new(60, "Microsoft3", "Corporation3");
DatabaseHelper.InsertCustomerData(sqlConnection, sqlTransaction, _tableName, customer2);
// Read the data that was just inserted, both Row no:2 and Row no:1 should be available.
DatabaseHelper.VerifyRecordPresent(sqlConnection, customer1, _tableName, sqlTransaction);
// Try to read the just inserted record under read-uncommitted mode.
DatabaseHelper.VerifyRecordPresent(sqlConnection, customer2, _tableName, sqlTransaction);
// Rollback the transaction to the saved checkpoint, to lose the row no:2.
sqlTransaction.Rollback(@"checkpoint");
// Row no:2 should not be available.
DatabaseHelper.VerifyRecordAbsent(sqlConnection, customer2, _tableName, sqlTransaction);
// Row no:1 should still be available.
DatabaseHelper.VerifyRecordPresent(sqlConnection, customer1, _tableName, sqlTransaction);
// Completely rollback the transaction.
sqlTransaction.Rollback();
// Now even row no:1 should not be available.
DatabaseHelper.VerifyRecordAbsent(sqlConnection, customer1, _tableName, sqlTransaction);
}
}
}
[ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringSetupForAE))]
[ClassData(typeof(AEConnectionStringProvider))]
public void SqlParameterProperties(string connection)
{
string tableName = _fixture.SqlParameterPropertiesTable.Name;
const string firstColumnName = @"firstColumn";
const string secondColumnName = @"secondColumn";
const string thirdColumnName = @"thirdColumn";
string inputProcedureName = DataTestUtility.GetUniqueName("InputProc").ToString();
string outputProcedureName = DataTestUtility.GetUniqueName("OutputProc").ToString();
const int charColumnSize = 100;
const int decimalColumnPrecision = 10;
const int decimalColumnScale = 4;
const int timeColumnScale = 5;
CleanUpTable(connection, tableName);
using (SqlConnection sqlConnection = new SqlConnection(connection))
{
try
{
sqlConnection.Open();
// Create a procedure that gets input parameters that have smaller data types than the actual columns types.
// Decimal precision and scale need to match exactly.
int charInputParamSize = charColumnSize - 20;
int decimalInputParamPrecision = decimalColumnPrecision;
int decimalInputParamScale = decimalColumnScale;
int timeInputParamScale = timeColumnScale - 1;
using (SqlCommand sqlCmd = new SqlCommand(string.Format(
@"CREATE PROCEDURE {0} (@p1 nvarchar({5}), @p2 decimal ({6}, {7}), @p3 time ({8})) AS
SELECT * FROM [{1}] WHERE {2} = @p1 AND {3} = @p2 AND {4} = @p3",
inputProcedureName, tableName, firstColumnName, secondColumnName, thirdColumnName, charInputParamSize, decimalInputParamPrecision, decimalInputParamScale, timeInputParamScale), sqlConnection))
{
sqlCmd.ExecuteNonQuery();
}
// Create a procedure that returns output parameters that have larger data type than the actual column types.
// Decimal precision and scale need to match exactly.
int charOutputParamSize = charColumnSize + 20;
int decimalOutputParamPrecision = decimalColumnPrecision;
int decimalOutputParamScale = decimalColumnScale;
int timeOutputParamScale = timeColumnScale + 1;
using (SqlCommand sqlCmd = new SqlCommand(string.Format(
@"CREATE PROCEDURE {0} (@p1 nvarchar({5}) OUTPUT, @p2 decimal ({6}, {7}) OUTPUT, @p3 time ({8}) OUTPUT) AS
SELECT @p1={2}, @p2={3}, @p3={4} FROM [{1}]",
outputProcedureName, tableName, firstColumnName, secondColumnName, thirdColumnName, charOutputParamSize, decimalOutputParamPrecision, decimalOutputParamScale, timeOutputParamScale), sqlConnection))
{
sqlCmd.ExecuteNonQuery();
}
// Insert a row.
using (SqlCommand sqlCmd = new SqlCommand(
cmdText: $"INSERT INTO [{tableName}] VALUES (@p1, @p2, @p3)",
connection: sqlConnection,
transaction: null,
columnEncryptionSetting: SqlCommandColumnEncryptionSetting.Enabled))
{
SqlParameter param1 = new SqlParameter("@p1", SqlDbType.NVarChar)
{
Size = charColumnSize,
Value = "ColumnValue"
};
sqlCmd.Parameters.Add(param1);
SqlParameter param2 = new SqlParameter("@p2", SqlDbType.Decimal)
{
Precision = decimalColumnPrecision,
Scale = decimalColumnScale,
Value = 400.21
};
sqlCmd.Parameters.Add(param2);
SqlParameter param3 = new SqlParameter("@p3", SqlDbType.Time)
{
Scale = timeColumnScale,
Value = TimeSpan.Parse("1:01:01.001")
};
sqlCmd.Parameters.Add(param3);
sqlCmd.ExecuteNonQuery();
}
// Now execute the procedure with input params and make sure the parameter properties stays as set.
using (SqlCommand sqlCmd = new SqlCommand(inputProcedureName, sqlConnection, null, SqlCommandColumnEncryptionSetting.Enabled))
{
sqlCmd.CommandType = CommandType.StoredProcedure;
// Set the actual parameter size to even smaller than the proc size. This is allowed since we assign from these values into the params.
// Decimal precision and scale need to match exactly.
int charParamSize = charInputParamSize - 20;
int decimalParamPrecision = decimalInputParamPrecision;
int decimalParamScale = decimalInputParamScale;
int timeParamScale = timeInputParamScale - 1;
SqlParameter param1 = new SqlParameter("@p1", SqlDbType.NVarChar)
{
Size = charParamSize,
Value = "ColumnValue"
};
sqlCmd.Parameters.Add(param1);
SqlParameter param2 = new SqlParameter("@p2", SqlDbType.Decimal)
{
Precision = (byte)decimalParamPrecision,
Scale = (byte)decimalParamScale,
Value = 400.21
};
sqlCmd.Parameters.Add(param2);
SqlParameter param3 = new SqlParameter("@p3", SqlDbType.Time)
{
Scale = (byte)timeParamScale,
Value = TimeSpan.Parse("1:01:01.001")
};
sqlCmd.Parameters.Add(param3);
using (SqlDataReader reader = sqlCmd.ExecuteReader())
{
Assert.True(reader.Read(), "We should have found one row.");
Assert.False(reader.Read(), "We shouldn't have found a second row.");
}
// Validate that all properties have stayed the same for all parameters.
Assert.Equal(SqlDbType.NVarChar, param1.SqlDbType);
Assert.Equal(DbType.String, param1.DbType);
Assert.Equal(0, param1.Scale);
Assert.Equal(0, param1.Precision);
Assert.Equal(charParamSize, param1.Size);
Assert.Equal(SqlDbType.Decimal, param2.SqlDbType);
Assert.Equal(DbType.Decimal, param2.DbType);
Assert.Equal(decimalParamScale, param2.Scale);
Assert.Equal(decimalParamPrecision, param2.Precision);
Assert.Equal(0, param2.Size);
Assert.Equal(SqlDbType.Time, param3.SqlDbType);
Assert.Equal(DbType.Time, param3.DbType);
Assert.Equal(timeParamScale, param3.Scale);
Assert.Equal(0, param3.Precision);
Assert.Equal(0, param3.Size);
}
// Now execute the procedure with output params and make sure the parameter properties stays as set.
using (SqlCommand sqlCmd = new SqlCommand(outputProcedureName, sqlConnection, null, SqlCommandColumnEncryptionSetting.Enabled))
{
sqlCmd.CommandType = CommandType.StoredProcedure;
// For output params the type needs to be identical with the actual procedure parameter since we will assign in both directions.
int charParamSize = charOutputParamSize;
int decimalParamPrecision = decimalOutputParamPrecision;
int decimalParamScale = decimalOutputParamScale;
int timeParamScale = timeOutputParamScale;
SqlParameter param1 = new SqlParameter("@p1", SqlDbType.NVarChar)
{
Direction = ParameterDirection.Output,
Size = charParamSize,
Value = "DifferentColumnValue"
};
sqlCmd.Parameters.Add(param1);
SqlParameter param2 = new SqlParameter("@p2", SqlDbType.Decimal)
{
Direction = ParameterDirection.Output,
Precision = (byte)decimalParamPrecision,
Scale = (byte)decimalParamScale,
Value = 4000.21
};
sqlCmd.Parameters.Add(param2);
SqlParameter param3 = new SqlParameter("@p3", SqlDbType.Time)
{
Direction = ParameterDirection.Output,
Scale = (byte)timeParamScale,
Value = TimeSpan.Parse("1:01:01.01")
};
sqlCmd.Parameters.Add(param3);
sqlCmd.ExecuteNonQuery();
// Validate that all properties have stayed the same for all parameters.
Assert.Equal(SqlDbType.NVarChar, param1.SqlDbType);
Assert.Equal(DbType.String, param1.DbType);
Assert.Equal(0, param1.Scale);
Assert.Equal(0, param1.Precision);
Assert.Equal(charParamSize, param1.Size);
Assert.Equal(SqlDbType.Decimal, param2.SqlDbType);
Assert.Equal(DbType.Decimal, param2.DbType);
Assert.Equal(decimalParamScale, param2.Scale);
Assert.Equal(decimalParamPrecision, param2.Precision);
Assert.Equal(0, param2.Size);
Assert.Equal(SqlDbType.Time, param3.SqlDbType);
Assert.Equal(DbType.Time, param3.DbType);
Assert.Equal(timeParamScale, param3.Scale);
Assert.Equal(0, param3.Precision);
Assert.Equal(0, param3.Size);
}
}
finally
{
DropHelperProcedures(new string[] { inputProcedureName, outputProcedureName }, connection);
}
}
}
[ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringSetupForAE))]
[ClassData(typeof(AEConnectionStringProvider))]
public void TestSqlDataAdapterFillDataTable(string connection)
{
CleanUpTable(connection, _tableName);
const string DummyParamName = "@dummyParam";
int numberOfRows = 100;
IList<object> values = GetValues(dataHint: 71);
InsertRows(tableName: _tableName, numberofRows: numberOfRows, values: values, connection: connection);
var encryptionEnabledConnectionString = new SqlConnectionStringBuilder(connection)
{
ColumnEncryptionSetting = SqlConnectionColumnEncryptionSetting.Enabled
}.ConnectionString;
using (var sqlConnection = new SqlConnection(encryptionEnabledConnectionString))
{
sqlConnection.Open();
// Create a command with an encrypted parameter to confirm that parameters work ocrrectly for Fill.
using (SqlCommand cmd = new SqlCommand(
cmdText: $"select * from [{_tableName}] where FirstName != {DummyParamName} and CustomerId = @CustomerId",
connection: sqlConnection))
{
if (DataTestUtility.EnclaveEnabled)
{
//Increase Time out for enclave-enabled server.
cmd.CommandTimeout = 90;
}
SqlParameter dummyParam = new SqlParameter(DummyParamName, SqlDbType.NVarChar, 150)
{
Value = "a"
};
cmd.Parameters.Add(dummyParam);
cmd.Parameters.AddWithValue(@"CustomerId", values[0]);
// Fill the data table from the results of select statement.
using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(cmd))
{
DataTable dataTable = new DataTable();
sqlDataAdapter.Fill(dataTable);
TestDataAdapterFillResults(dataTable, values);
// Try refilling another table with the same adapter to make sure that reusing the command works correctly.
dataTable = new DataTable();
sqlDataAdapter.Fill(dataTable);
TestDataAdapterFillResults(dataTable, values);
Assert.Equal(numberOfRows, dataTable.Rows.Count);
// Use the Fill overload which fills in a dataset.
DataSet dataSet = new DataSet();
sqlDataAdapter.Fill(dataSet, _tableName);
Assert.Single(dataSet.Tables);
Assert.Equal(numberOfRows, dataSet.Tables[0].Rows.Count);
TestDataAdapterFillResults(dataSet.Tables[0], values);
// Use the Fill overload which lets you specify the max number of records to be fetched.
dataSet = new DataSet();
sqlDataAdapter.Fill(dataSet, 0, 1, _tableName);
Assert.Single(dataSet.Tables);
Assert.Single(dataSet.Tables[0].Rows);
TestDataAdapterFillResults(dataSet.Tables[0], values);
}
}
}
}
[ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringSetupForAE))]
[ClassData(typeof(AEConnectionStringProviderWithSchemaType))]
public void TestSqlDataAdapterFillSchema(string connection, SchemaType schemaType)
{
CleanUpTable(connection, _tableName);
IList<object> values = GetValues(dataHint: 44);
int numberOfRows = 42;
// Insert a bunch of rows in to the table.
int rowsAffected = InsertRows(tableName: _tableName, numberofRows: numberOfRows, values: values, connection: connection);
using (SqlConnection sqlConnection = new SqlConnection(connection))
{
sqlConnection.Open();
SqlDataAdapter adapter = CreateSqlDataAdapter(sqlConnection);
DataTable dataTable = new DataTable();
DataTable dataTable2 = adapter.FillSchema(dataTable, schemaType);
DataColumnCollection dataColumns = dataTable2.Columns;
ValidateSchema(dataTable2.Columns);
ValidateSchema(dataTable.Columns);
// Test the FillSchema overload that takes in a dataset with SchemaType = Source.
DataSet dataSet = new DataSet();
DataTable[] dataSet2 = adapter.FillSchema(dataSet, schemaType);
Assert.Single(dataSet2);
ValidateSchema(dataSet2[0].Columns);
ValidateSchema(dataSet.Tables[0].Columns);
}
}
/// <summary>
/// Validate the schema obtained SqlDataAdapter.FillSchema
/// </summary>
/// <param name="dataColumns"></param>
private void ValidateSchema(DataColumnCollection dataColumns)
{
Assert.Equal(@"CustomerId", dataColumns[0].ColumnName);
Assert.Equal(@"FirstName", dataColumns[1].ColumnName);
Assert.Equal(@"LastName", dataColumns[2].ColumnName);
Assert.Equal(typeof(int), dataColumns[0].DataType);
Assert.Equal(typeof(string), dataColumns[1].DataType);
Assert.Equal(typeof(string), dataColumns[2].DataType);
}
[ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringSetupForAE))]
[ClassData(typeof(AEConnectionStringProviderWithBooleanVariable))]
public void TestExecuteNonQuery(string connection, bool isAsync)
{
CleanUpTable(connection, _tableName);
Parallel.For(0, 10, i =>
{
bool tryagain = false;
do
{
IList<object> values = GetValues(dataHint: 45 + i + 1);
int numberOfRows = 10 + i;
// Insert a bunch of rows in to the table.
int rowsAffected = InsertRows(tableName: _tableName, numberofRows: numberOfRows, values: values, connection: connection);
Assert.Equal(numberOfRows, rowsAffected);
rowsAffected = -1;
using (SqlConnection sqlConnection = new SqlConnection(connection))
{
try
{
sqlConnection.Open();
// Update the set of rows that were inserted just now. And verify the rows affected as returned by ExecuteNonQuery.
using (SqlCommand sqlCommand = new SqlCommand(
cmdText: $"UPDATE [{_tableName}] SET FirstName = @FirstName WHERE CustomerId = @CustomerId",
connection: sqlConnection,
transaction: null,
columnEncryptionSetting: SqlCommandColumnEncryptionSetting.Enabled))
{
if (DataTestUtility.EnclaveEnabled)
{
//Increase Time out for enclave-enabled server.
sqlCommand.CommandTimeout = 90;
}
sqlCommand.Parameters.AddWithValue(@"FirstName", string.Format(@"Microsoft{0}", i + 100));
sqlCommand.Parameters.AddWithValue(@"CustomerId", values[0]);
if (isAsync)
{
Task<int> executeTask = VerifyExecuteNonQueryAsync(sqlCommand);
rowsAffected = executeTask.Result;
}
else
{
rowsAffected = sqlCommand.ExecuteNonQuery();
}
}
}
catch (SqlException sqle)
{
// SQL Server deadlocks are possible if test executes multiple parallel threads. We will try again.
if (sqle.ErrorCode.Equals(1205))
{
tryagain = true;
break;
}
}
Assert.Equal(numberOfRows, rowsAffected);
tryagain = false;
}
} while (tryagain);
});
}
[ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringSetupForAE))]
[ClassData(typeof(AEConnectionStringProviderWithBooleanVariable))]
public void TestExecuteScalar(string connection, bool isAsync)
{
CleanUpTable(connection, _tableName);
Parallel.For(0, 10, i =>
{
IList<object> values = GetValues(dataHint: 42);
int numberOfRows = 10 + i;
// Insert a bunch of rows in to the table.
int rowsAffected = InsertRows(tableName: _tableName, numberofRows: numberOfRows, values: values, connection: connection);
using (SqlConnection sqlConnection = new SqlConnection(connection))
{
sqlConnection.Open();
// Do a select * from the table and check on the first column of the first row for the expected value.
using (SqlCommand sqlCommand = new SqlCommand
(
cmdText: $"select CustomerId, FirstName, LastName from [{_tableName}] where CustomerId = @CustomerId",
connection: sqlConnection,
transaction: null,
columnEncryptionSetting: SqlCommandColumnEncryptionSetting.Enabled))
{
if (DataTestUtility.EnclaveEnabled)
{
// Increase timeout for enclave-enabled server
sqlCommand.CommandTimeout = 60;
}
sqlCommand.Parameters.AddWithValue(@"CustomerId", values[0]);
int customerId = -1;
if (isAsync)
{
Task<object> result = VerifyExecuteScalarAsync(sqlCommand);
customerId = (int)result.Result;
}
else
{
customerId = (int)sqlCommand.ExecuteScalar();
}
Assert.Equal((int)values[0], customerId);
}
}
});
}
[ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringSetupForAE))]
[ClassData(typeof(AEConnectionStringProviderWithIntegers))]
public void TestSqlDataAdapterBatchUpdate(string connection, int numberofRows)
{
CleanUpTable(connection, _tableName);
DataTable dataTable = CreateDataTable(tableName: _tableName, numberofRows: numberofRows);
using (SqlConnection sqlConnection = new SqlConnection(connection))
{
sqlConnection.Open();
// Create a SqlDataAdapter.
SqlDataAdapter adapter = CreateSqlDataAdapter(sqlConnection);
// Execute the update.
int rowsAffected = adapter.Update(dataTable);
Assert.Equal(numberofRows, rowsAffected);
if (numberofRows == 100)
{
// Delete a row, add two new ones and update the table again to make sure reusing the commands is working properly.
int lastRowId = dataTable.Rows.Count;
lastRowId++;
dataTable.Rows.RemoveAt(1);
DataRow row = dataTable.NewRow();
row["CustomerId"] = 45 + lastRowId;
row["FirstName"] = string.Format(@"Microsoft{0}", lastRowId);
row["LastName"] = string.Format(@"Corporation{0}", lastRowId);
dataTable.Rows.Add(row);
lastRowId++;
row = dataTable.NewRow();
row["CustomerId"] = 45 + lastRowId;
row["FirstName"] = string.Format(@"Microsoft{0}", lastRowId);
row["LastName"] = string.Format(@"Corporation{0}", lastRowId);
dataTable.Rows.Add(row);
rowsAffected = adapter.Update(dataTable);
}
}
}
[ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringSetupForAE))]
[ClassData(typeof(AEConnectionStringProvider))]
public void TestExecuteReader(string connection)
{
CleanUpTable(connection, _tableName);
Parallel.For(0, 10, i =>
{
IList<object> values = GetValues(dataHint: 45 + i + 1);
int numberOfRows = 10 + i;
// Insert a bunch of rows in to the table.
int rowsAffected = InsertRows(tableName: _tableName, numberofRows: numberOfRows, values: values, connection: connection);
Assert.True(numberOfRows == rowsAffected, "Two values failed");
using (SqlConnection sqlConnection = new SqlConnection(connection))
{
sqlConnection.Open();
// Update the set of rows that were inserted just now. And verify the rows affected as returned by ExecuteNonQuery.
using (SqlCommand sqlCommand = new SqlCommand(
cmdText: $"SELECT CustomerId, FirstName, LastName FROM [{_tableName}] WHERE FirstName=@FirstName AND CustomerId=@CustomerId ",
connection: sqlConnection,
transaction: null,
columnEncryptionSetting: SqlCommandColumnEncryptionSetting.Enabled))
{
if (DataTestUtility.EnclaveEnabled)
{
//Increas command time out to a minute for enclave-enabled server.
sqlCommand.CommandTimeout = 60;
}
sqlCommand.Parameters.AddWithValue(@"FirstName", string.Format(@"Microsoft{0}", i + 100));
sqlCommand.Parameters.AddWithValue(@"CustomerId", values[0]);
IAsyncResult asyncResult = sqlCommand.BeginExecuteReader();
Assert.True(asyncResult != null, "asyncResult should not be null");
using (SqlDataReader sqlDataReader = sqlCommand.EndExecuteReader(asyncResult))
{
while (sqlDataReader.Read())
{
Assert.Equal(sqlDataReader.GetInt32(0), (int)values[0]);
Assert.Equal(sqlDataReader.GetInt32(1), (int)values[1]);
Assert.Equal(sqlDataReader.GetInt32(2), (int)values[2]);
}
Assert.True(rowsAffected == numberOfRows, "no: of rows returned by EndExecuteReader is unexpected.");
Assert.True(3 == sqlDataReader.VisibleFieldCount);
Assert.True(3 == sqlDataReader.FieldCount);
}
}
}
});
}
[ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringSetupForAE))]
[ClassData(typeof(AEConnectionStringProvider))]
public async void TestExecuteReaderAsyncWithLargeQuery(string connectionString)
{
string randomName = DataTestUtility.GetUniqueName(Guid.NewGuid().ToString().Replace("-", ""), false);
if (randomName.Length > 50)
{
randomName = randomName.Substring(0, 50);
}
string tableName = $"VeryLong_{randomName}_TestTableName";
int columnsCount = 50;
// Arrange - drops the table with long name and re-creates it with 52 columns (ID, name, ColumnName0..49)
try
{
CreateTable(connectionString, tableName, columnsCount);
string name = "nobody";
using (SqlConnection connection = new SqlConnection(connectionString))
{
await connection.OpenAsync();
// This creates a "select top 100" query that has over 40k characters
using (SqlCommand sqlCommand = new SqlCommand(GenerateSelectQuery(tableName, columnsCount, 10, "WHERE Name = @FirstName AND ID = @CustomerId"),
connection,
transaction: null,
columnEncryptionSetting: SqlCommandColumnEncryptionSetting.Enabled))
{
sqlCommand.Parameters.Add(@"CustomerId", SqlDbType.Int);
sqlCommand.Parameters.Add(@"FirstName", SqlDbType.VarChar, name.Length);
sqlCommand.Parameters[0].Value = 0;
sqlCommand.Parameters[1].Value = name;
// Act and Assert
// Test that execute reader async does not throw an exception.
// The table is empty so there should be no results; however, the bug previously found is that it causes a TDS RPC exception on enclave.
using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync())
{
Assert.False(sqlDataReader.HasRows, "The table should be empty");
}
}
}
}
catch
{
throw;
}
finally
{
DropTableIfExists(connectionString, tableName);
}
}
[ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringSetupForAE))]
[ClassData(typeof(AEConnectionStringProviderWithCommandBehaviorSet1))]
public void TestExecuteReaderWithCommandBehavior(string connection, CommandBehavior commandBehavior)
{
string[] columnNames = new string[3] { "CustomerId", "FirstName", "LastName" };
string[] columnOrdinals = new string[3] { @"0", @"1", @"2" };
string[] dataTypeName = new string[3] { @"int", @"nvarchar", @"nvarchar" };
string[] providerType = new string[3] { @"8", @"12", @"12" };
string[] providerSpecificDataType = new string[3] { @"System.Data.SqlTypes.SqlInt32", @"System.Data.SqlTypes.SqlString", @"System.Data.SqlTypes.SqlString" };
string[] dataType = new string[3] { @"System.Int32", @"System.String", @"System.String" };
string[] columnSizes = new string[3] { @"4", @"50", @"50" };
CleanUpTable(connection, _tableName);
Parallel.For(0, 1, i =>
{
IList<object> values = GetValues(dataHint: 16 + i);
Assert.False(values == null || values.Count < 3, @"values should not be null and count should be >= 3.");
int numberOfRows = 10 + i;
// Insert a bunch of rows in to the table.
int rowsAffected = InsertRows(tableName: _tableName, numberofRows: numberOfRows, values: values, connection: connection);
Assert.Equal(rowsAffected, numberOfRows);
using (SqlConnection sqlConnection = new SqlConnection(connection))
{
sqlConnection.Open();
// select the set of rows that were inserted just now.
using (SqlCommand sqlCommand = new SqlCommand(
cmdText: $"SELECT CustomerId, FirstName, LastName FROM [{_tableName}] WHERE FirstName = @FirstName AND CustomerId = @CustomerId",
connection: sqlConnection,
transaction: null,
columnEncryptionSetting: SqlCommandColumnEncryptionSetting.Enabled))
{
sqlCommand.Parameters.AddWithValue(@"FirstName", values[1]);
sqlCommand.Parameters.AddWithValue(@"CustomerId", values[0]);
IAsyncResult asyncResult = sqlCommand.BeginExecuteReader(commandBehavior);
Assert.False(asyncResult == null, "asyncResult should not be null.");
rowsAffected = 0;
using (SqlDataReader sqlDataReader = sqlCommand.EndExecuteReader(asyncResult))
{
if (commandBehavior == CommandBehavior.KeyInfo || commandBehavior == CommandBehavior.SchemaOnly)
{
DataTable dataTable = sqlDataReader.GetSchemaTable();
Assert.False(dataTable != null, "dataTable should not be null.");
int j = 0;
foreach (DataRow dataRow in dataTable.Rows)
{
Assert.True(dataRow[dataTable.Columns[0]].ToString() == columnNames[j], "column name mismatch.");
Assert.True(dataRow[dataTable.Columns[1]].ToString() == columnOrdinals[j], "column ordinal mismatch.");
Assert.True(dataRow[dataTable.Columns[2]].ToString() == columnSizes[j], "column sizes mismatch.");
Assert.True(dataRow[dataTable.Columns[12]].ToString() == dataType[j], "data type mismatch.");
Assert.True(dataRow[dataTable.Columns[14]].ToString() == providerType[j], "provider type mismatch.");
Assert.True(dataRow[dataTable.Columns[23]].ToString() == providerSpecificDataType[j], "provider specific data type mismatch.");
Assert.True(dataRow[dataTable.Columns[24]].ToString() == dataTypeName[j], "data type name mismatch.");
j++;
}
}
while (sqlDataReader.Read())
{
rowsAffected++;
Assert.True(sqlDataReader.GetInt32(0) == (int)values[0], "CustomerId value read from the table was incorrect.");
if (commandBehavior != CommandBehavior.SequentialAccess)
{
Assert.True(sqlDataReader.GetString(1) == (string)values[1], "FirstName value read from the table was incorrect.");
Assert.True(sqlDataReader.GetString(2) == (string)values[2], "LastName value read from the table was incorrect.");
}
else
{
char[] textValue = new char[((string)values[1]).Length];
sqlDataReader.GetChars(1, 0, textValue, 0, textValue.Length);
Assert.True(new string(textValue) == (string)values[1], @"Value returned by GetChars is unexpected.");
textValue = new char[((string)values[2]).Length];
sqlDataReader.GetChars(2, 0, textValue, 0, textValue.Length);
Assert.True(new string(textValue) == (string)values[2], @"Value returned by GetChars is unexpected.");
}
}
Assert.True(3 == sqlDataReader.VisibleFieldCount, "value returned by sqlDataReader.VisibleFieldCount is unexpected.");
Assert.True(3 == sqlDataReader.FieldCount, "value returned by sqlDataReader.FieldCount is unexpected.");
}
}
// Based on the command behavior, verify the appropriate outcome.
switch (commandBehavior)
{
case CommandBehavior.CloseConnection:
Assert.True(sqlConnection.State.Equals(ConnectionState.Closed),
"CommandBehavior.CloseConnection did not close the connection after command execution.");
break;
case CommandBehavior.SingleResult:
case CommandBehavior.SequentialAccess:
//Assert.True(rowsAffected == 1, "rowsAffected did not match the expected number of rows.");
Assert.True(sqlConnection.State.Equals(ConnectionState.Open),
"CommandBehavior.SingleResult or SequentialAccess closed the connection after command execution.");
break;
case CommandBehavior.SingleRow:
// Assert.True(rowsAffected == 1, "rowsAffected did not match the expected number of rows.");
Assert.True(sqlConnection.State == ConnectionState.Open,
"CommandBehavior.SingleRow closed the connection after command execution.");
break;
case CommandBehavior.SchemaOnly:
case CommandBehavior.KeyInfo:
Assert.True(rowsAffected == 0, "rowsAffected did not match the expected number of rows.");
Assert.True(sqlConnection.State == ConnectionState.Open,
"CommandBehavior.KeyInfo or CommandBehavior.SchemaOnly closed the connection after command execution.");
break;
default:
break;
}
}
});
}
[ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringSetupForAE))]
[ClassData(typeof(AEConnectionStringProvider))]
public void TestEnclaveStoredProceduresWithAndWithoutParameters(string connectionString)
{
using SqlConnection sqlConnection = new(connectionString);
sqlConnection.Open();
using SqlCommand sqlCommand = new("", sqlConnection, transaction: null,
columnEncryptionSetting: SqlCommandColumnEncryptionSetting.Enabled);
string procWithoutParams = DataTestUtility.GetUniqueName("EnclaveWithoutParams", withBracket: false);
string procWithParam = DataTestUtility.GetUniqueName("EnclaveWithParams", withBracket: false);
try
{
sqlCommand.CommandText = $"CREATE PROCEDURE {procWithoutParams} AS SELECT FirstName, LastName FROM [{_tableName}];";
sqlCommand.ExecuteNonQuery();
sqlCommand.CommandText = $"CREATE PROCEDURE {procWithParam} @id INT AS SELECT FirstName, LastName FROM [{_tableName}] WHERE CustomerId = @id";
sqlCommand.ExecuteNonQuery();
int expectedFields = 2;
sqlCommand.CommandText = procWithoutParams;
sqlCommand.CommandType = CommandType.StoredProcedure;
using (SqlDataReader reader = sqlCommand.ExecuteReader())
{
Assert.Equal(expectedFields, reader.VisibleFieldCount);
}
sqlCommand.CommandText = procWithParam;
sqlCommand.CommandType = CommandType.StoredProcedure;
Exception ex = Assert.Throws<SqlException>(() => sqlCommand.ExecuteReader());
string expectedMsg = $"Procedure or function '{procWithParam}' expects parameter '@id', which was not supplied.";
Assert.Equal(expectedMsg, ex.Message);
sqlCommand.Parameters.AddWithValue("@id", 0);
using (SqlDataReader reader = sqlCommand.ExecuteReader())
{
Assert.Equal(expectedFields, reader.VisibleFieldCount);
}
}
finally
{
DropHelperProcedures(new[] { procWithoutParams, procWithParam }, connectionString);
}
}
[ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringSetupForAE))]
[ClassData(typeof(AEConnectionStringProvider))]
public void TestPrepareWithExecuteNonQuery(string connection)
{
CleanUpTable(connection, _tableName);
IList<object> values = GetValues(dataHint: 52);
Assert.True(values != null && values.Count >= 3, @"values should not be null and count should be >= 3.");
int numberOfRows = 10;
// Insert a bunch of rows in to the table.
int rowsAffected = InsertRows(tableName: _tableName, numberofRows: numberOfRows, values: values, connection: connection);
Assert.True(rowsAffected == numberOfRows, "number of rows affected is unexpected.");
using (SqlConnection sqlConnection = new SqlConnection(connection))
{
sqlConnection.Open();
using (SqlCommand sqlCommand =
new SqlCommand($"UPDATE [{_tableName}] SET LastName = @LastName WHERE FirstName = @FirstName AND CustomerId = @CustomerId",
sqlConnection,
transaction: null,
columnEncryptionSetting: SqlCommandColumnEncryptionSetting.Enabled))
{
sqlCommand.Parameters.Add(@"CustomerId", SqlDbType.Int);
sqlCommand.Parameters.Add(@"FirstName", SqlDbType.NVarChar, ((string)values[1]).Length);
sqlCommand.Parameters.Add(@"LastName", SqlDbType.NVarChar, ((string)values[2]).Length);
sqlCommand.Parameters[0].Value = values[0];
sqlCommand.Parameters[1].Value = values[1];
sqlCommand.Parameters[2].Value = values[2];
sqlCommand.Prepare();
rowsAffected = -1;
rowsAffected = sqlCommand.ExecuteNonQuery();
sqlCommand.Parameters[0].Value = (int)values[0] + 1;
sqlCommand.Parameters[1].Value = values[1];
sqlCommand.Parameters[2].Value = values[2];
rowsAffected = -1;
rowsAffected = sqlCommand.ExecuteNonQuery();
}
}
}
[ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringSetupForAE))]
[ClassData(typeof(AEConnectionStringProvider))]
public void TestAsyncWriteDelayWithExecuteNonQueryAsync(string connection)
{
CleanUpTable(connection, _tableName);
IList<object> values = GetValues(dataHint: 53);
Assert.True(values != null && values.Count >= 3, @"values should not be null and count should be >= 3.");
int numberOfRows = 10;
// Insert a bunch of rows in to the table.
int rowsAffected = InsertRows(tableName: _tableName, numberofRows: numberOfRows, values: values, connection: connection);
using (SqlConnection sqlconnection = new SqlConnection(connection))
{
sqlconnection.Open();
using (SqlCommand sqlCommand = new SqlCommand($"UPDATE [{_tableName}] SET LastName = @LastName WHERE FirstName = @FirstName AND CustomerId = @CustomerId",
sqlconnection,
transaction: null,
columnEncryptionSetting: SqlCommandColumnEncryptionSetting.Enabled))
{
sqlCommand.Parameters.Add(@"CustomerId", SqlDbType.Int);
sqlCommand.Parameters.Add(@"FirstName", SqlDbType.NVarChar, ((string)values[1]).Length);
sqlCommand.Parameters.Add(@"LastName", SqlDbType.NVarChar, ((string)values[2]).Length);
sqlCommand.Parameters[0].Value = values[0];
sqlCommand.Parameters[1].Value = values[1];
sqlCommand.Parameters[2].Value = values[2];
sqlCommand.Prepare();
rowsAffected = -1;