Last active
October 15, 2020 12:49
-
-
Save Danthar/536330ea6ec94874b16a2880769f936a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[Test] | |
public void Can_Serialize_ICommandResult_With_Sql_Exception() | |
{ | |
SqlException exception; | |
try | |
{ | |
throw SqlExceptionCreator.NewSqlException(101); | |
} catch(SqlException ex) | |
{ | |
exception = ex; | |
} | |
var jsonSettings = new JsonSerializerSettings(); | |
jsonSettings.TypeNameHandling = TypeNameHandling.Auto; | |
string serializedResult = JsonConvert.SerializeObject(exception, Formatting.None, jsonSettings); | |
var deserializedresult = JsonConvert.DeserializeObject<SqlException>(serializedResult, jsonSettings); | |
Assert.AreEqual( exception.ToString(), deserializedresult.ToString()); | |
Assert.AreEqual(typeof(SqlException), deserializedresult.GetType()); | |
} | |
public class SqlExceptionCreator | |
{ | |
private static T Construct<T>(params object[] p) | |
{ | |
var ctors = typeof(T).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance); | |
return (T)ctors.First(ctor => ctor.GetParameters().Length == p.Length).Invoke(p); | |
} | |
internal static SqlException NewSqlException(int number = 1) | |
{ | |
SqlErrorCollection collection = Construct<SqlErrorCollection>(); | |
SqlError error = Construct<SqlError>(number, (byte)2, (byte)3, "server name", "error message", "proc", 100); | |
typeof(SqlErrorCollection) | |
.GetMethod("Add", BindingFlags.NonPublic | BindingFlags.Instance) | |
.Invoke(collection, new object[] { error }); | |
return typeof(SqlException) | |
.GetMethod("CreateException", BindingFlags.NonPublic | BindingFlags.Static, | |
null, | |
CallingConventions.ExplicitThis, | |
new[] { typeof(SqlErrorCollection), typeof(string) }, | |
new ParameterModifier[] { }) | |
.Invoke(null, new object[] { collection, "7.0.0" }) as SqlException; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment