From 518869e249af65abbfda2dcb3d60c094b86f14cc Mon Sep 17 00:00:00 2001 From: Wraith Date: Mon, 30 Jan 2023 21:24:22 +0000 Subject: [PATCH] Fix NullReferenceException in GetBytesAsync (#1906) --- .../Microsoft/Data/SqlClient/SqlDataReader.cs | 2 +- .../DataReaderTest/DataReaderStreamsTest.cs | 32 +++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDataReader.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDataReader.cs index 8d43d72685..965803f993 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDataReader.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDataReader.cs @@ -5285,7 +5285,7 @@ protected override void DisposeCore() { TDisposable copy = _disposable; _disposable = default; - copy.Dispose(); + copy?.Dispose(); } } diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DataReaderTest/DataReaderStreamsTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DataReaderTest/DataReaderStreamsTest.cs index f008d6b2fa..3f16a3a138 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DataReaderTest/DataReaderStreamsTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DataReaderTest/DataReaderStreamsTest.cs @@ -9,6 +9,7 @@ using System.Text; using System.Threading.Tasks; using System.Xml; +using System.Xml.Linq; using Xunit; namespace Microsoft.Data.SqlClient.ManualTesting.Tests @@ -471,6 +472,37 @@ public static void InvalidCastExceptionStream(CommandBehavior behavior, Accessor } } +#if NETCOREAPP + [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] + public static async void ReadAsyncContentsCompletes() + { + string expectedXml = "This is a test string"; + string query = $"SELECT CAST('{expectedXml}' AS NVARCHAR(MAX))"; + + string returnedXml = null; + using (SqlConnection connection = new SqlConnection(DataTestUtility.TCPConnectionString)) + using (SqlCommand command = new SqlCommand(query, connection)) + { + connection.Open(); + + await using (SqlDataReader reader = await command.ExecuteReaderAsync(CommandBehavior.SequentialAccess).ConfigureAwait(false)) + { + while (await reader.ReadAsync().ConfigureAwait(false)) + { + using (TextReader textReader = reader.GetTextReader(0)) + using (XmlReader xmlReader = XmlReader.Create(textReader, new XmlReaderSettings() { Async = true })) + { + XDocument xdoc = await XDocument.LoadAsync(xmlReader, LoadOptions.None, default).ConfigureAwait(false); + returnedXml = xdoc.ToString(); + } + } + } + } + + Assert.Equal(expectedXml, returnedXml, StringComparer.Ordinal); + } +#endif + private static async Task ExecuteReader(SqlCommand command, CommandBehavior behavior, bool isExecuteAsync) => isExecuteAsync ? await command.ExecuteReaderAsync(behavior) : command.ExecuteReader(behavior);