Getting error deserializing with DataContractSerializer - c#

When I am deserializing my object back to it's original type my object is always null.
Here is my code:
ProjectSetup obj = new ProjectSetup();
if (System.Web.HttpContext.Current.Session["ProjectSetup"] == null)
setBookProjectSetup();
string toDeserialise = System.Web.HttpContext.Current.
Session["ProjectSetup"].ToString();
DataContractSerializer dcs = new DataContractSerializer(typeof(ProjectSetup));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(toDeserialise));
obj = (ProjectSetup) dcs.ReadObject(ms, true);
return obj;

I'm going to assume that the call to setBookProjectSetup places an instance of ProjectSetup in the HttpSessionState with a key of ProjectSetup.
The issue here starts with this:
string toDeserialise = System.Web.HttpContext.Current.
Session["ProjectSetup"].ToString();
You subsequently use the contents of the toDeserialize string as the source of the deserialization.
Unless you've overloaded ToString to return a byte stream that the DataContractSerializer would be able to deserialize (it's highly unlikely) chances are you are using the implementation of ToString on Object, which will just return the type's name.
Then, you are trying to deserialize that string into your object, which isn't going to work.
What you need to do is properly serialize your object into a byte array/MemoryStream, like so:
using (var ms = new MemoryStream())
{
// Create the serializer.
var dcs = new DataContractSerializer(typeof(ProjectSetup));
// Serialize to the stream.
dcs.WriteObject(ms, System.Web.HttpContext.Current.Session["ProjectSetup"]);
At this point, the MemoryStream will be populated with a series of bytes representing your serialized object. You can then get the object back using the same MemoryStream:
// Reset the position of the stream so the read occurs in the right place.
ms.Position = 0;
// Read the object.
var obj = (ProjectSetup) dcs.ReadObject(ms);
}

Related

Why does XmlSerializer work on my singleton but not BinaryFormatter?

I'm pulling my hair out trying to get my game save files converted from XML based to binary based. My GameManager class is a singleton. Loading and saving its instance variable using XmlSerializer works flawlessly, but when I try to use BinaryFormatter, I get an error that 'instance' isn't set to a reference of an object. 'instance' can't be null after a call to GameManager.Instance.LoadGame, since it's a singleton. If it was null, it would have been created when the method was called, right?
Here is the Xml version, that works fine:
if (newText != null) {
XmlSerializer xmlSerializer = new XmlSerializer(typeof(GameManager));
using (XmlReader reader = XmlReader.Create(new StringReader(newText)))
{
if (xmlSerializer.CanDeserialize(reader))
GameManager.instance = (GameManager)xmlSerializer.Deserialize(reader);
}
}
Here is the Binary version that doesn't, I get an object not set to a reference on 'GameManager.instance':
FileStream stream = new FileStream(fileName, FileMode.Open);
BinaryFormatter formatter = new BinaryFormatter();
GameManager.instance = (GameManager)formatter.Deserialize( stream );
stream.Close();
I tried creating a setter for my Instance, which creates a new 'instance' if it doesn't exist, and the code will work without crashing, but the data isn't populated correctly, it's all empty when other parts of the game try to access it. If I create an entirely new GameManager object and populate that one, the data is populated correctly so I know it is getting serialized right, but my game doesn't work obviously because the data isn't where it needs to be.

Serialize an object in C# and get byte stream

I have an object, instance of a Serializable class. I was wondering how can you get this object as a byte stream?
I know I can use BinaryFormatter and then use the Serialize method, but this method takes a serializationStream where it writes the serialized object. I want to be able to write it in a file/stream in a specific position so I would like to do something like:
obj = new Something(); // obj is serializable
byte[] serialized = obj.serialize(); [*]
file.write(position, serialized)
Is there any way I can do the [*], to take the bytes of the serialization of an object?
MemoryStream m = new MemoryStream();
var formatter = new BinaryFormatter();
formatter.Serialize(m, new MyClass() {Name="SO"});
byte[] buf = m.ToArray(); //or File.WriteAllBytes(filename, m.ToArray())
[Serializable]
public class MyClass
{
public string Name;
}

Binary deserialization: get object data

Is it possible to get data of the binary serialized object ( or list of othe same objects ) as it can be done in XML or soap. Please note, I have no idea about object structure ( private and public fields,etc)? By data of the binary serialized object I mean the values of all fields.
Lets say you have a stream.
object yourData;
var SerializeBinaryFileName = #"C:\Temp\binary.bf";
using (Stream stream = File.Open(SerializeBinaryFileName, FileMode.Open))
{
BinaryFormatter bformatter = new BinaryFormatter();
yourData = bformatter.Deserialize(stream);
stream.Close();
}
Then you have your object graph in the yourData variable.
You can read it as any other object graph can be read.

How to save a serializable object using File.WriteAllBytes?, C#

I need to save an object, its serializable but I donot want to use XML.
Is it possible to write the raw bytes of the object and then read it off the disk to create the object again?
Thanks for the help!
Use a BinaryFormatter:
var formatter = new BinaryFormatter();
// Serialize
using (var stream = File.OpenWrite(path))
{
formatter.Serialize(stream, yourObject);
}
...
// Deserialize
using (var stream = File.OpenRead(path))
{
YourType yourObject = (YourType)formatter.Deserialize(stream);
}
Yes, it is called binary serialization. There are some good examples on the MSDN site:
http://msdn.microsoft.com/en-us/library/4abbf6k0(v=vs.100).aspx

How to pass through the soap memory stream?

I create memory stream.
var memoryStream = new MemoryStream();
var binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, list.ToArray());
And I need to pass through the soap to java server and insert to database.
And how create webService method ?
#WebMethod(operationName = "CreateObject")
public String CreateTopology(
#WebParam(name = "session")int id_session,
#WebParam(name = "title") String title,
#WebParam(name = "content") Object content,
#WebParam(name = "access") Integer access) {
EDIT:
Problem. I have serialized object in C #. I need to pass it on to the server via SOAP Java, after that save it in MySQL database in field of type Blob (may not be the blob)
Have a look here:
//build a Call object
Call call = new Call();
call.setTargetObjectURI("urn:greetingService");
call.setMethodName("sayGreeting");
call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);
//creating a parameter list
Vector params = new Vector();
params.addElement(new Parameter("name", String.class, name,null));
//adding the parameter(s) to the Call object
call.setParams(params);
You are setting the method-name "sayGreeting" and in a vector params you specify the parameters which the method will be called with. This parameter-vector is what you need!
The code-sample is taken from page 2 of this tutorial which i very much recommend: http://javaboutique.internet.com/tutorials/SOAP/
base64String - to pass as string
var memoryStream = new MemoryStream();
var binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, m_workspace.ListPlatforms.ToArray());
String base64String = Convert.ToBase64String(memoryStream.ToArray());

Categories