I am trying to serialize a class to be sent to a server where the server will use that object. I am using Microsoft's example of an asynchronous client/server setup for this: http://msdn.microsoft.com/en-us/library/bew39x2a.aspx I am using the binary formatter.
To test this, I am using this class:
[Serializable]
class Class1
{
public int x = 10;
public string banana = "banana";
}
and attempting to serialize it with:
Class1 example = new Class1();
IFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream();
formatter.Serialize(stream, example);
in order to send it to the server, I need to send a string:
StreamReader reader = new StreamReader( stream );
string text = reader.ReadToEnd();
server.Send(text);
stream.Close();
but this doesn't work. I have tried converting the stream to a byte[] as seen here but I keep getting a Stream was unreadable exception when testing this in the debugger.
Try
Class1 example = new Class1();
IFormatter formatter = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
formatter.Serialize(ms, example);
ms.Position = 0;
StreamReader sr = new StreamReader(ms);
String text = sr.ReadToEnd();
server.Send(text);
}
I think that the part that got missed is resetting the position of MemoryStream to be able to read (think of it as rewinding for playback after recording)
Related
Right now I'm using XmlTextWriter to convert a MemoryStream object into string. But I wan't to know whether there is a faster method to serialize a memorystream to string.
I follow the code given here for serialization - http://www.eggheadcafe.com/articles/system.xml.xmlserialization.asp
Edited
Stream to String
ms.Position = 0;
using (StreamReader sr = new StreamReader(ms))
{
string content = sr.ReadToEnd();
SaveInDB(ms);
}
String to Stream
string content = GetFromContentDB();
byte[] byteArray = Encoding.ASCII.GetBytes(content);
MemoryStream ms = new MemoryStream(byteArray);
byte[] outBuf = ms.GetBuffer(); //error here
using(MemoryStream stream = new MemoryStream()) {
stream.Position = 0;
var sr = new StreamReader(stream);
string myStr = sr.ReadToEnd();
}
You cant use GetBuffer when you use MemoryStream(byte[]) constructor.
MSDN quote:
This constructor does not expose the
underlying stream. GetBuffer throws
UnauthorizedAccessException.
You must use this constructor and set publiclyVisible = true in order to use GetBuffer
In VB.net i used this
Dim TempText = System.Text.Encoding.UTF8.GetString(TempMemoryStream.ToArray())
in C# may apply
I have a class that serializes and deserializes objects for a given type. I am trying to serialize a Custom file object containing the file name, the data in the file and a few other details like created time, modified time etc associated with the file. Additionally the custome class includes some properties or flags I would need at my receiver end (where I deserialize).
When I try to serialize around 30K of such file objects, it does the serialization successfully for a large majority, but throws back an outofmemoryexception for some files.
Below is my serialization class code:
public static string SerializeToByteArray(Type T, object request)
{
DataContractSerializer serializer = new DataContractSerializer(T);
using (MemoryStream memStream = new MemoryStream())
{
using (StreamReader reader = new StreamReader(memStream))
{
serializer.WriteObject(memStream, request);
memStream.Position = 0;
return reader.ReadToEnd();
}
}
}
public static T DeserializeFromByteArray<T>(string xml)
{
DataContractSerializer deserializer = new DataContractSerializer(typeof(T));
using (MemoryStream memStream = new MemoryStream())
{
byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);
memStream.Write(data, 0, data.Length);
memStream.Position = 0;
var newobj = (T)deserializer.ReadObject(memStream);
return newobj;
}
}
I am new to stocks in C#, I wish to send a Object in C#. Have been using BinaryWriter to send data (works fine for string), but it doesn't seem to have a method like
writer.Writer(new SerliaizedObject());
How do we achieve this using BinaryReader/BinaryWriter
UPDATE:
I used the following functions to convert by object to byte and send it across to the client
public static byte[] SerializeToBytes<T>(T item)
{
var formatter = new BinaryFormatter();
using (var stream = new MemoryStream())
{
formatter.Serialize(stream, item);
stream.Seek(0, SeekOrigin.Begin);
return stream.ToArray();
}
}
public static object DeserializeFromBytes(byte[] bytes)
{
var formatter = new BinaryFormatter();
using (var stream = new MemoryStream(bytes))
{
return formatter.Deserialize(stream);
}
}
To send the data is used:
formatter = new BinaryFormatter();
MessageBox.Show(SerializeToBytes<mydata>(new mydata()).Length+"");
writer.Write(SerializeToBytes<mydata>(new mydata()));
ChatBox.AppendText("Client Says :" + UserMessage.Text + "\r\n");
And to read the data I used:
while (true)
{
byte[] bytes = reader.ReadBytes(120);
mydata temp = DeserializeFromBytes(bytes) as mydata;
ChatBox.AppendText("Server Says " + temp + "\r\n");
}
But the reader doesn't seem to work, Any Ideas?
Use BinaryFormatter to write serializable objects to streams in binary format:
FileStream fs = new FileStream("DataFile.dat", FileMode.Create);
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, mySerializable);
You should use the first 4 bytes as length header, and in the receive loop you add a variable bytesReadSoFar. Then you know when everything is received.
I'm using XMLSerializer to serialize a class into a XML. There are plenty of examples to this and save the XML into a file. However what I want is to put the XML into a string rather than save it to a file.
I'm experimenting with the code below, but it's not working:
public static void Main(string[] args)
{
XmlSerializer ser = new XmlSerializer(typeof(TestClass));
MemoryStream m = new MemoryStream();
ser.Serialize(m, new TestClass());
string xml = new StreamReader(m).ReadToEnd();
Console.WriteLine(xml);
Console.ReadLine();
}
public class TestClass
{
public int Legs = 4;
public int NoOfKills = 100;
}
Any ideas on how to fix this ?
Thanks.
You have to position your memory stream back to the beginning prior to reading like this:
XmlSerializer ser = new XmlSerializer(typeof(TestClass));
MemoryStream m = new MemoryStream();
ser.Serialize(m, new TestClass());
// reset to 0 so we start reading from the beginning of the stream
m.Position = 0;
string xml = new StreamReader(m).ReadToEnd();
On top of that, it's always important to close resources by either calling dispose or close. Your full code should be something like this:
XmlSerializer ser = new XmlSerializer(typeof(TestClass));
string xml;
using (MemoryStream m = new MemoryStream())
{
ser.Serialize(m, new TestClass());
// reset to 0
m.Position = 0;
xml = new StreamReader(m).ReadToEnd();
}
Console.WriteLine(xml);
Console.ReadLine();
There's the [Serializabe] attribute missing on class TestClass and you have to set the position of the memory stream to the beginning:
XmlSerializer ser = new XmlSerializer(typeof(TestClass));
MemoryStream m = new MemoryStream();
ser.Serialize(m, new TestClass());
m.Position = 0;
string xml = new StreamReader(m).ReadToEnd();
Console.WriteLine(xml);
Console.ReadLine();
Your memory stream is not closed, and is positioned at the end (next available location to write in). My guess is that you must Close it, or Seek to its beginning. The way you do you don't read anything because you are already at the end of stream. So add Seek() after you serialize objects. Like this:
XmlSerializer ser = new XmlSerializer(typeof(TestClass));
MemoryStream m = new MemoryStream();
ser.Serialize(m, new TestClass());
m.Seek(0, SeekOrigin.Begin); //<-- ADD THIS!
string xml = new StreamReader(m).ReadToEnd();
Console.WriteLine(xml);
Console.ReadLine();
I have a simple 2D array of strings and I would like to stuff it into an SPFieldMultiLineText in MOSS. This maps to an ntext database field.
I know I can serialize to XML and store to the file system, but I would like to serialize without touching the filesystem.
public override void ItemAdding(SPItemEventProperties properties)
{
// build the array
List<List<string>> matrix = new List<List<string>>();
/*
* populating the array is snipped, works fine
*/
// now stick this matrix into the field in my list item
properties.AfterProperties["myNoteField"] = matrix; // throws an error
}
Looks like I should be able to do something like this:
XmlSerializer s = new XmlSerializer(typeof(List<List<string>>));
properties.AfterProperties["myNoteField"] = s.Serialize.ToString();
but that doesn't work. All the examples I've found demonstrate writing to a text file.
StringWriter outStream = new StringWriter();
XmlSerializer s = new XmlSerializer(typeof(List<List<string>>));
s.Serialize(outStream, myObj);
properties.AfterProperties["myNoteField"] = outStream.ToString();
Here's a Generic serializer (C#):
public string SerializeObject<T>(T objectToSerialize)
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream memStr = new MemoryStream();
try
{
bf.Serialize(memStr, objectToSerialize);
memStr.Position = 0;
return Convert.ToBase64String(memStr.ToArray());
}
finally
{
memStr.Close();
}
}
In your case you could call with:
SerializeObject<List<string>>(matrix);
Use the TextWriter and TextReader classes with the StringWriter.
To Wit:
XmlSerializer s = new XmlSerializer(typeof(whatever));
TextWriter w = new StringWriter();
s.Serialize(w, whatever);
yourstring = w.ToString();
IN VB.NET
Public Shared Function SerializeToByteArray(ByVal object2Serialize As Object) As Byte()
Using stream As New MemoryStream
Dim xmlSerializer As New XmlSerializer(object2Serialize.GetType())
xmlSerializer.Serialize(stream, object2Serialize)
Return stream.ToArray()
End Using
End Function
Public Shared Function SerializeToString(ByVal object2Serialize As Object) As String
Dim bytes As Bytes() = SerializeToByteArray(object2Serialize)
Return Text.UTF8Encoding.GetString(bytes)
End Function
IN C#
public byte[] SerializeToByteArray(object object2Serialize) {
using(MemoryStream stream = new MemoryStream()) {
XmlSerializer xmlSerializer = new XmlSerializer(object2Serialize.GetType());
xmlSerializer.Serialize(stream, object2Serialize);
return stream.ToArray();
}
}
public string SerializeToString(object object2Serialize) {
byte[] bytes = SerializeToByteArray(object2Serialize);
return Text.UTF8Encoding.GetString(bytes);
}