Skip to content

Fix | Enable serialization of SqlException - #4622

Merged
mdaigle merged 2 commits into
dotnet:mainfrom
edwardneal:fix/sqlexception-serialization
Oct 29, 2026
Merged

mdaigle merged 2 commits into
dotnet:mainfrom
edwardneal:fix/sqlexception-serialization

Conversation

@edwardneal

@edwardneal edwardneal commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Description

This fixes two longstanding bugs when serializing a SqlException using .NET Framework's SerializableAttribute-based infrastructure - via DataContractSerializer, BinaryFormatter or SoapFormatter.

The underlying bug was simply that we weren't providing a value for the Errors collection in GetObjectData, or reading it back in the deserialization constructor. Since properties such as SqlException.Number just read from the first entry in Errors, populating that collection automatically lights up those property values.

The broader picture here is that there are a few separate requests for changes to SqlException - issues #648 and #649 request SqlState and IsTransient support, issue #35 requests a public-facing constructor. Before adding new fields, I want to be sure that the underlying type serializes and deserializes correctly.

Issues

Fixes #1940.
Fixes #2150.

Testing

New unit test added to highlight regressions.

This new test uses BinaryFormatter, which is a bad practice in user code: it's known to be insecure when used with untrusted payloads. The alternative (DataContractSerializer) doesn't exactly mimic the original use case of .NET Framework Remoting though - DataContractSerializer requires a list of known types. I don't believe that the test introduces a security bug (we've got full control of the payloads we serialize and deserialize) but I'm not sure whether it'll be flagged as a risk.

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
There may be pipelines that require an authorized user to comment /azp run to run.

paulmedynski
paulmedynski previously approved these changes Sep 29, 2026
@paulmedynski

Copy link
Copy Markdown
Contributor

/azp run

@paulmedynski
paulmedynski requested a balanced review from Copilot September 29, 2026 13:31
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 2 pipeline(s).
1 pipeline(s) were filtered out due to trigger conditions.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

The new test class and method lack required XML summary documentation.

Review effort: Balanced
Findings: 1 Low severity

Open (1)
What changed in this PR

Fixes SqlException serialization so SQL error details survive .NET Framework formatter round trips.

Changes:

  • Serializes and restores SqlErrorCollection.
  • Adds a BinaryFormatter regression test.
File Description
SqlException.cs Persists errors during serialization.
SqlExceptionTests.cs Tests serialized exception state.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@paulmedynski

Copy link
Copy Markdown
Contributor

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 2 pipeline(s).
1 pipeline(s) were filtered out due to trigger conditions.

@mdaigle

mdaigle commented Oct 20, 2026

Copy link
Copy Markdown
Contributor

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 2 pipeline(s).
1 pipeline(s) were filtered out due to trigger conditions.

@codecov

codecov Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 0% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 66.86%. Comparing base (7054399) to head (0d5c668).
⚠️ Report is 138 commits behind head on main.

Files with missing lines Patch % Lines
...lient/src/Microsoft/Data/SqlClient/SqlException.cs 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4622      +/-   ##
==========================================
+ Coverage   65.92%   66.86%   +0.94%     
==========================================
  Files         290      327      +37     
  Lines       44987    94686   +49699     
==========================================
+ Hits        29656    63313   +33657     
- Misses      15331    31373   +16042     
Flag Coverage Δ
CI-SqlClient ?
PR-SqlClient-Project 66.86% <0.00%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@priyankatiwari08

Copy link
Copy Markdown
Contributor

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 2 pipeline(s).
1 pipeline(s) were filtered out due to trigger conditions.

@priyankatiwari08

Copy link
Copy Markdown
Contributor

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 2 pipeline(s).
1 pipeline(s) were filtered out due to trigger conditions.

@mdaigle
mdaigle enabled auto-merge (squash) October 29, 2026 19:05
@mdaigle
mdaigle merged commit 8dab81c into dotnet:main Oct 29, 2026
249 of 261 checks passed
@github-project-automation github-project-automation Bot moved this from In review to Done in SqlClient Board Oct 29, 2026
@edwardneal
edwardneal deleted the fix/sqlexception-serialization branch October 29, 2026 19:32
priyankatiwari08 added a commit that referenced this pull request Nov 2, 2026
…taContract round trip

Since #4622, SqlException.GetObjectData writes the error collection, so
DataContractSerializer needs SqlErrorCollection, SqlError and List<object> as
known types.

Copilot-Session: c47d6846-090b-4240-9f75-efa50beb8e34
Co-authored-by: Copilot App <[email protected]>
priyankatiwari08 added a commit that referenced this pull request Nov 4, 2026
…taContract round trip

Since #4622, SqlException.GetObjectData writes the error collection, so
DataContractSerializer needs SqlErrorCollection, SqlError and List<object> as
known types.

Copilot-Session: c47d6846-090b-4240-9f75-efa50beb8e34
Co-authored-by: Copilot App <[email protected]>
priyankatiwari08 added a commit that referenced this pull request Nov 10, 2026
…taContract round trip

Since #4622, SqlException.GetObjectData writes the error collection, so
DataContractSerializer needs SqlErrorCollection, SqlError and List<object> as
known types.

Copilot-Session: c47d6846-090b-4240-9f75-efa50beb8e34
Co-authored-by: Copilot App <[email protected]>
priyankatiwari08 added a commit that referenced this pull request Nov 11, 2026
…taContract round trip

Since #4622, SqlException.GetObjectData writes the error collection, so
DataContractSerializer needs SqlErrorCollection, SqlError and List<object> as
known types.

Copilot-Session: c47d6846-090b-4240-9f75-efa50beb8e34
Co-authored-by: Copilot App <[email protected]>
priyankatiwari08 added a commit that referenced this pull request Nov 11, 2026
* Add connection encryption info public API surface (Slice A)

Adds SqlConnectionEncryptionInfo, SqlConnectionEncryptionMode, and
SqlServerCertificateValidationErrors, plus SqlConnection.EncryptionInfo and
SqlException.EncryptionInfo getters. In this slice both getters always return
an empty snapshot; no TdsParser/SNI plumbing yet.

Related to #2353.

Co-authored-by: Copilot App <[email protected]>

* Use SHA-256 certificate hash in SqlConnectionEncryptionInfo; add design note

Replace PresentedServerCertificateThumbprint (string?) with
PresentedServerCertificateHash256 (ReadOnlyMemory<byte>?), per the API
agreed with the SSMS team. The internal constructor validates the hash is
32 bytes and keeps a private copy. Add doc/design-notes/2353 for reviewers.

Co-authored-by: Copilot App <[email protected]>

* Fix doc include path and slice plan in design note

Co-authored-by: Copilot App <[email protected]>

* Add NegotiatedCipherSuite to SqlConnectionEncryptionInfo

Adds int? NegotiatedCipherSuite (IANA TLS cipher suite identifier selected by the server) to the public snapshot, ref assembly, XML docs, design note and unit tests. Proposal pending API review.

Co-authored-by: Copilot App <[email protected]>

* Cipher suite: NegotiatedCipherSuiteId (int?) on all TFMs; TlsCipherSuite? on .NET (review feedback)

- Add NegotiatedCipherSuiteId (int?, CLS-compliant) on every target framework.
  It returns the IANA identifier unchanged, including unnamed/GREASE values.
- On .NET only, NegotiatedCipherSuite exposes the same value as
  System.Net.Security.TlsCipherSuite? and is marked [CLSCompliant(false)].
- No NegotiatedCipherSuite member on net462/netstandard2.0, so the only shared
  member has an identical signature across the netstandard2.0 ref and the
  net10.0 implementation.
- The internal constructor still takes int? (0..0xFFFF). The internal
  NegotiatedCipherSuiteValue is removed.
- Update ref, XML docs, design note and unit tests.

Copilot-Session: c47d6846-090b-4240-9f75-efa50beb8e34
Co-authored-by: Copilot App <[email protected]>

* Encryption info: replace certificate hash with GetServerCertificate() (threat model review)

Remove PresentedServerCertificateHash256 and expose the server-presented leaf
certificate via X509Certificate2? GetServerCertificate(). Each call returns a
new caller-owned instance parsed from a private DER copy, or null when no
certificate was captured or the bytes cannot be parsed. The internal ctor now
takes byte[]? presentedServerCertificate, and PresentedServerCertificateRawData
exposes the captured bytes internally. Update ref, XML docs, design note and
unit tests.

Copilot-Session: c47d6846-090b-4240-9f75-efa50beb8e34
Co-authored-by: Copilot App <[email protected]>

* Encryption info tests: register SqlErrorCollection known types for DataContract round trip

Since #4622, SqlException.GetObjectData writes the error collection, so
DataContractSerializer needs SqlErrorCollection, SqlError and List<object> as
known types.

Copilot-Session: c47d6846-090b-4240-9f75-efa50beb8e34
Co-authored-by: Copilot App <[email protected]>

* Encryption info: address Slice A review feedback

- Sort SqlConnectionEncryptionInfo public members alphabetically in the
  implementation, reference assembly, XML doc snippets and design note.
- Document how each SqlConnectionEncryptionMode value is negotiated and
  how much of the connection TLS covers.
- Clarify that the internal PresentedServerCertificateRawData wraps the
  snapshot's private copy and must not be mutated.
- Add XML docs to the test constants and helpers.

Copilot-Session: c47d6846-090b-4240-9f75-efa50beb8e34
Co-authored-by: Copilot App <[email protected]>

* Docs: make SqlConnectionEncryptionInfo type remarks release-neutral

Remove the statement that the driver never populates the snapshot; it becomes inaccurate once capture lands in later slices. Point to the getter remarks for when values are captured.

Copilot-Session: c47d6846-090b-4240-9f75-efa50beb8e34

Co-authored-by: Copilot App <[email protected]>

* Docs: clarify negotiated protocol availability on failure

Describe null as unavailable, not proof that no TLS handshake completed, and document that a protocol observed before a later handshake or connection failure is retained.

Copilot-Session: c47d6846-090b-4240-9f75-efa50beb8e34

Co-authored-by: Copilot App <[email protected]>

* Docs: mark encryption info API approved

Update the design note to show the approved API and remove outdated review caveats. Replace Slice A-only empty-snapshot wording in the getter remarks with the stable connection and exception snapshot contracts.

Copilot-Session: c47d6846-090b-4240-9f75-efa50beb8e34

Co-authored-by: Copilot App <[email protected]>

---------

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: c47d6846-090b-4240-9f75-efa50beb8e34
paulmedynski pushed a commit that referenced this pull request Nov 12, 2026
…surface (#5037)

* Connection encryption info – Slice A: public API surface (#4830)

* Add connection encryption info public API surface (Slice A)

Adds SqlConnectionEncryptionInfo, SqlConnectionEncryptionMode, and
SqlServerCertificateValidationErrors, plus SqlConnection.EncryptionInfo and
SqlException.EncryptionInfo getters. In this slice both getters always return
an empty snapshot; no TdsParser/SNI plumbing yet.

Related to #2353.

Co-authored-by: Copilot App <[email protected]>

* Use SHA-256 certificate hash in SqlConnectionEncryptionInfo; add design note

Replace PresentedServerCertificateThumbprint (string?) with
PresentedServerCertificateHash256 (ReadOnlyMemory<byte>?), per the API
agreed with the SSMS team. The internal constructor validates the hash is
32 bytes and keeps a private copy. Add doc/design-notes/2353 for reviewers.

Co-authored-by: Copilot App <[email protected]>

* Fix doc include path and slice plan in design note

Co-authored-by: Copilot App <[email protected]>

* Add NegotiatedCipherSuite to SqlConnectionEncryptionInfo

Adds int? NegotiatedCipherSuite (IANA TLS cipher suite identifier selected by the server) to the public snapshot, ref assembly, XML docs, design note and unit tests. Proposal pending API review.

Co-authored-by: Copilot App <[email protected]>

* Cipher suite: NegotiatedCipherSuiteId (int?) on all TFMs; TlsCipherSuite? on .NET (review feedback)

- Add NegotiatedCipherSuiteId (int?, CLS-compliant) on every target framework.
  It returns the IANA identifier unchanged, including unnamed/GREASE values.
- On .NET only, NegotiatedCipherSuite exposes the same value as
  System.Net.Security.TlsCipherSuite? and is marked [CLSCompliant(false)].
- No NegotiatedCipherSuite member on net462/netstandard2.0, so the only shared
  member has an identical signature across the netstandard2.0 ref and the
  net10.0 implementation.
- The internal constructor still takes int? (0..0xFFFF). The internal
  NegotiatedCipherSuiteValue is removed.
- Update ref, XML docs, design note and unit tests.

Copilot-Session: c47d6846-090b-4240-9f75-efa50beb8e34
Co-authored-by: Copilot App <[email protected]>

* Encryption info: replace certificate hash with GetServerCertificate() (threat model review)

Remove PresentedServerCertificateHash256 and expose the server-presented leaf
certificate via X509Certificate2? GetServerCertificate(). Each call returns a
new caller-owned instance parsed from a private DER copy, or null when no
certificate was captured or the bytes cannot be parsed. The internal ctor now
takes byte[]? presentedServerCertificate, and PresentedServerCertificateRawData
exposes the captured bytes internally. Update ref, XML docs, design note and
unit tests.

Copilot-Session: c47d6846-090b-4240-9f75-efa50beb8e34
Co-authored-by: Copilot App <[email protected]>

* Encryption info tests: register SqlErrorCollection known types for DataContract round trip

Since #4622, SqlException.GetObjectData writes the error collection, so
DataContractSerializer needs SqlErrorCollection, SqlError and List<object> as
known types.

Copilot-Session: c47d6846-090b-4240-9f75-efa50beb8e34
Co-authored-by: Copilot App <[email protected]>

* Encryption info: address Slice A review feedback

- Sort SqlConnectionEncryptionInfo public members alphabetically in the
  implementation, reference assembly, XML doc snippets and design note.
- Document how each SqlConnectionEncryptionMode value is negotiated and
  how much of the connection TLS covers.
- Clarify that the internal PresentedServerCertificateRawData wraps the
  snapshot's private copy and must not be mutated.
- Add XML docs to the test constants and helpers.

Copilot-Session: c47d6846-090b-4240-9f75-efa50beb8e34
Co-authored-by: Copilot App <[email protected]>

* Docs: make SqlConnectionEncryptionInfo type remarks release-neutral

Remove the statement that the driver never populates the snapshot; it becomes inaccurate once capture lands in later slices. Point to the getter remarks for when values are captured.

Copilot-Session: c47d6846-090b-4240-9f75-efa50beb8e34

Co-authored-by: Copilot App <[email protected]>

* Docs: clarify negotiated protocol availability on failure

Describe null as unavailable, not proof that no TLS handshake completed, and document that a protocol observed before a later handshake or connection failure is retained.

Copilot-Session: c47d6846-090b-4240-9f75-efa50beb8e34

Co-authored-by: Copilot App <[email protected]>

* Docs: mark encryption info API approved

Update the design note to show the approved API and remove outdated review caveats. Replace Slice A-only empty-snapshot wording in the getter remarks with the stable connection and exception snapshot contracts.

Copilot-Session: c47d6846-090b-4240-9f75-efa50beb8e34

Co-authored-by: Copilot App <[email protected]>

---------

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: c47d6846-090b-4240-9f75-efa50beb8e34

* Address Slice A review feedback for connection encryption info

Follow-up to #4830 addressing review feedback on the release/8.0
cherry-pick (#5037).

- Carry TlsCipherSuite end-to-end on .NET: the internal constructor takes
  TlsCipherSuite? and NegotiatedCipherSuite is an auto-property; .NET
  Framework keeps the range-checked int? identifier.
- Make SqlConnectionEncryptionMode byte-backed.
- Catch only CryptographicException in GetServerCertificate.
- Annotate GetServerCertificate as returning X509Certificate2? in the ref.
- Clarify null semantics and validation/decoding behavior in the docs and
  drop implementation details.
- Move SqlConnection and SqlException tests into SqlConnectionTests and
  SqlExceptionTests, share helpers via EncryptionInfoTestData, and tighten
  assertions.

Co-authored-by: Copilot App <[email protected]>
(cherry picked from commit 4114d5c)

* Fix notsupported build for nullable-annotated ref members

GenAPI reproduces the '?' on SqlConnectionEncryptionInfo.GetServerCertificate()
but emitted no '#nullable' context into the auto-generated source (CS8669) and
copied the compiler-reserved NullableContextAttribute on net10.0 (CS8335).

Pass a header file that adds '#nullable enable annotations', matching the ref
assembly, and exclude the Nullable/NullableContext attributes from the output.

Co-authored-by: Copilot App <[email protected]>
(cherry picked from commit b172dc5)

* Address second-round review feedback on Slice A follow-up

- Take ushort in the cipher suite identifier theories so InlineData cannot
  exceed 16 bits.
- Document why the BinaryFormatter SqlException tests are .NET Framework only.

Co-authored-by: Copilot App <[email protected]>
(cherry picked from commit ce8508d)

---------

Co-authored-by: priyankatiwari08 <[email protected]>
Co-authored-by: Copilot App <[email protected]>
Copilot-Session: c47d6846-090b-4240-9f75-efa50beb8e34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

Error info is lost during serialization SqlException.Number is always 0 when using .NET framework remoting

6 participants