Nekeniehl
Nekeniehl

Reputation: 1691

Binary serialize/deserialize via sockets TargetInvocationException

I have 3 projects, first is the client, second is the server and the last one is the BroadcastMessage:

In the client have this code to serialize and object (this = BroadcastMessage):

public MemoryStream SerializeObject()
{
     MemoryStream stream = new MemoryStream();

     BinaryFormatter formatter = new BinaryFormatter();

     formatter.Serialize(stream, this);

     return stream;
}

Then, I convert this stream into byte[] and send via sockets to the Server, there, I deserialize with this:

BinaryFormatter formatter = new BinaryFormatter();
Stream str = new MemoryStream(inMessage);
BroadcastMessage m = (BroadcastMessage) formatter.Deserialize(str);

The communication between client and server is correct, I receive the complete stream, but when I try to deserialize, simply doesn´t work, giving me an TargetInvocationException, cause is trying to find the project where the object (BroadcastMessage) was serialized. If I add this project to the Server the deserialization works without problems, but I cannot add a project of everyclass that uses this "BroadcastMessage".

Any suggestions? Is there a way to indicate the correct namespace when I serialize? Thanks in advance!

EDIT: Ok, the problem was caused because I was subscribed in a event of the class, getting out the listening of the event and works perfectly, Thanks all for the time.

Upvotes: 1

Views: 680

Answers (1)

JeffRSon
JeffRSon

Reputation: 11166

You shouldn't need to reference the whole project. An assembly with the specific types is sufficient. Hence you should put all types that need to be (de)serialized in their own assembly and reference this from both projects.

You need to define those types anyway, and such you'll get rid of putting the same code twice in your projects (DRY principle).

Upvotes: 1

Related Questions