I watched Jason Jackson's answer, but it didn't make sense to me that I had problems with this, although System.Exception implements ISerializable. So I walked around the XmlSerializer by wrapping an exception in a class that uses BinaryFormatter instead. When the XmlSerialization of MS Message Queuing objects kicks in everything it sees, it is a class with an open byte array.
Here is what I came up with:
public class WrappedException { public byte[] Data; public WrappedException() { } public WrappedException(Exception e) { SetException(e); } public Exception GetException() { Exception result; BinaryFormatter bf = new BinaryFormatter(); MemoryStream stream = new MemoryStream(Data); result = (Exception)bf.Deserialize(stream); stream.Close(); return result; } public void SetException(Exception e) { MemoryStream stream = new MemoryStream(); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(stream, e); Data = stream.ToArray(); stream.Close(); } }
The first test worked fine, but user exceptions still bothered me. So I threw together my own exception. Then I just pressed a button on a blank form. Here is the code:
[Serializable] public class MyException : Exception, ISerializable { public int ErrorCode = 10; public MyException(SerializationInfo info, StreamingContext context) : base(info, context) { ErrorCode = info.GetInt32("ErrorCode"); } public MyException(string message) : base(message) { } #region ISerializable Members void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("ErrorCode", ErrorCode); } #endregion } private void button1_Click(object sender, EventArgs e) { MyException ex = new MyException("Hello, world!"); ex.ErrorCode = 20; WrappedException reply = new WrappedException(ex); XmlSerializer x = new XmlSerializer(reply.GetType()); MemoryStream stream = new MemoryStream(); x.Serialize(stream, reply); stream.Position = 0; WrappedException reply2 = (WrappedException)x.Deserialize(stream); MyException ex2 = (MyException)reply2.GetException(); stream.Close(); Text = ex2.ErrorCode.ToString(); // form shows 20 // throw ex2; }
Although it seemed like all the other types of exceptions I was looking for were marked with the SerializableAttribute symbol, I should be careful about custom exceptions that were not marked with the SerializableAttribute symbol.
EDIT: In front of me. I did not understand that BinaryFormatter is not implemented on CF.
EDIT: over the code snippets were in the desktop project. In the CF version, a WrappedException will basically look the same as I just have to implement my own BinaryFormater, but I am very open to suggestions on this.
CrashCodes Dec 23 '08 at 22:11 2008-12-23 22:11
source share