Skip to content

Commit 9d71471

Browse files
Midhunnnkmidhun
andauthored
Fix crash when Data Source starts with a comma (#3250)
* Fix crash when Data Source starts with a comma * Refine test to expect SqlException --------- Co-authored-by: midhun <midhun@bakedev>
1 parent f0d51e8 commit 9d71471

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

src/Microsoft.Data.SqlClient/src/Microsoft/Data/Common/AdapterUtil.cs

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -792,8 +792,19 @@ private static bool IsEndpoint(string dataSource, string prefix)
792792
length = foundIndex;
793793
}
794794

795-
// check for the instance name
796-
foundIndex = dataSource.LastIndexOf('\\', length - 1, length - 1);
795+
// Safeguard LastIndexOf call to avoid ArgumentOutOfRangeException when length is 0
796+
if (length > 0)
797+
{
798+
// check for the instance name
799+
foundIndex = dataSource.LastIndexOf('\\', length - 1, length - 1);
800+
}
801+
else
802+
{
803+
foundIndex = -1;
804+
}
805+
806+
807+
797808
if (foundIndex > 0)
798809
{
799810
length = foundIndex;

src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlConnectionTest.cs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1082,6 +1082,20 @@ public void ConnectionRetryForNonAzureEndpoints()
10821082
Assert.Equal(1, (int)field.GetValue(cn));
10831083
}
10841084

1085+
1086+
1087+
[Fact]
1088+
public void ConnectionString_WithOnlyComma()
1089+
{
1090+
// Test Case for https://github.com/dotnet/SqlClient/issues/3110
1091+
// Validates that a single-comma Data Source (e.g., "Data Source=,") no longer causes ArgumentOutOfRangeException
1092+
// Instead, it should throw a SqlException indicating a connection failure
1093+
1094+
SqlConnection cn = new SqlConnection("Data Source=,;Initial Catalog=master;Integrated Security=True");
1095+
Assert.Throws<SqlException>(() => { cn.Open(); });
1096+
1097+
}
1098+
10851099
[Theory]
10861100
[InlineData("myserver.database.windows.net")]
10871101
[InlineData("myserver.database.cloudapi.de")]

0 commit comments

Comments
 (0)