using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
public class FooException : Exception{
public FooException(string message, int fooValue, Exception innerException = null) : base(message, innerException) {
protected FooException(SerializationInfo info, StreamingContext context) : base(info, context) {
m_fooValue = info.GetInt32("m_fooValue");
public override void GetObjectData(SerializationInfo info, StreamingContext context) {
if (info == null) throw new ArgumentNullException("info");
info.AddValue("m_fooValue", m_fooValue);
base.GetObjectData(info, context);
public int FooValue { get { return m_fooValue; } }
public static partial class BinaryFormatterHelper
public static byte[] ToBinary<T>(T obj)
using (var stream = new MemoryStream())
new BinaryFormatter().Serialize(stream, obj);
public static T FromBinary<T>(byte[] data)
using (var stream = new MemoryStream(data))
var formatter = new BinaryFormatter();
var obj = formatter.Deserialize(stream);
public static void Test()
throw new FooException("my message", 101);
var bytes = BinaryFormatterHelper.ToBinary(ex);
var ex2 = BinaryFormatterHelper.FromBinary<FooException>(bytes);
Assert.IsTrue(ex.FooValue == ex2.FooValue);
public static void Main()
Console.WriteLine("Environment version: " + Environment.Version);
Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine("Failed with unhandled exception: ");