I'm working with an application that allows the users to use a map, trace lines on it and set markers wherever they want, but I need to store any kind of data they might need in one of the marker's properties (which is byte[] type so i can store it in database as varbinary), but when I try to convert it back to the original type i'm getting an error.
Object to store:
public ColeccionPoints listOfData = new ColeccionPoints();
//Of course the list to store won't be empty, this is only an example.
Storing the list in the marker
foreach (RouteMarkers r in pictureBox1.Controls.OfType<RouteMarkers>())
{
MappingMarkerMap m = new MappingMarkerMap();
//Using binaryFormatter and MemoryStream to save the object of ColeccionPoints to byte array
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, listOfData );
//Storing the object into MarkerData
m.MarkerData = ms.ToArray();
m.MarkerDescription = r.Description;
m.MarkerId = r.Id;
m.MarkerType = (MappingMarkerMap.Type)r.Type;
m.Number = r.Number;
m.X = r.Location.X;
m.Y = r.Location.Y;
markers.Add(m);
}
Saving into database using a simple SQL statement and i pass the parameter which be stored in a varbinary(max) column
cmd.Parameters.AddWithValue("MarkerData", marker.MarkerData);
The problems start when I need to retrieve the data and convert it back to the original type.
I use a simple select*from table to obtain the fields i need and convert the varbinary to byte
m.MarkerData = (byte[])dr["markerData"];
From here is where I don't know how to convert the MarkerData byte array to CollectionPoints, I tried to Deserialize:
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Deserialize(ms, m.MarkerData);
But i get the next error: Error 15 Argument 2: cannot convert from 'byte[]' to 'System.Runtime.Remoting.Messaging.HeaderHandler'
I would appreciate any help to convert the data to CollectionPoints, also I apologize if my english is not very good, I did my best to explain the problem and I hope is clear, if not, please let me know.
Thanks in advance.
Well I managed to solve the problem thanks to the BradleyDotNET's comment which made me read about DataContractSerializer and then about XmlSerializer :)
I changed the type of the property m.MarkerData from byte[] to string and instead using BinaryFormatter, used XmlSerializer.
using (StringWriter writer = new StringWriter(CultureInfo.InvariantCulture))
{
XmlSerializer serializer = new XmlSerializer(typeof (Entities.Points));
serializer.Serialize(writer, r.Datos);
m.MarkerData = writer.ToString();
}
So after having saved the string in database I just retrieve it by deserializing:
XmlSerializer serializer = new XmlSerializer(typeof(Entities.Points));
using (StringReader reader = new StringReader(m.MarkerData))
{
r.Datos = (Entities.Points)serializer.Deserialize(reader);
}