I'm using a custom implementation of a Stream
that will stream an IEnumerable<T>
into a stream. I'm using this EnumerableStream implementation to perform the conversion.
I'm using it to perform streaming over WCF in streaming mode. I'm able to convert the IEnumerable
to a stream without problem. Once, I'm in the client side, I can deserialize and get all the data, however I'm not able to find the condition to stop looping over my stream. I'm getting:
System.Runtime.Serialization.SerializationException: End of Stream encountered before parsing was completed.
Here's sample example of what I'm trying to achieve:
class Program
{
public static void Main()
{
var ListToSend = new List<List<string>>();
var ListToReceive = new List<List<string>>();
ListToSend = SimulateData().ToList();
using (Stream stream = GetStream(ListToSend))
{
var formatter = new BinaryFormatter();
while (stream.CanRead || 1 == 1 || true...) // What should I put in here to stop once I read everything???
{
List<string> row = formatter.Deserialize(stream) as List<string>;
ListToReceive.Add(row);
}
Printer(ListToReceive);
Console.WriteLine("Done");
}
}
private static void Printer(List<List<string>> data)
{
Console.WriteLine("Printing");
foreach (var row in data)
{
foreach (var cell in row)
{
Console.Write(cell + "\t");
}
Console.WriteLine("-------------------------------------------------------------------------------");
}
}
private static Stream GetStream(IEnumerable<List<string>> data)
{
return EnumerableStream.Create(data, DeserializerCallback);
}
private static List<byte> DeserializerCallback(object obj)
{
var binFormatter = new BinaryFormatter();
var mStream = new MemoryStream();
binFormatter.Serialize(mStream, obj);
return mStream.ToArray().ToList();
}
private static IEnumerable<List<string>> SimulateData()
{
Random randomizer = new Random();
for (var i = 0; i < 10; i++)
{
var row = new List<string>();
for (var j = 0; j < 1000; j++)
{
row.Add((randomizer.Next(100)).ToString());
}
yield return row;
}
}
}
I did not include the custom stream. I created a fiddle for those that want to see the entire code.
- Do I need to add something in the custom stream itself to notify that all the data have been read?
- Is it because the format of the deserializer and serialiser are not the same (I don't think so).
- I also want to know why when I put a break point in the read function, the buffer size is changing randomly.
- I would prefer not to wrap the code with a try and catch, I want a clean solution that does not crash.
BinaryFormatter
is not recommended for use for inter machine communication or for persisted data. It is extremely intolerant of assembly version changes, if one side has updates the other does not they won't be able to talk to each other. – Verdieverdigrisprotobuf-net
? – Overcash