a question about serialization - c#

What is a better approach to serialize custom class: using XMLSerializer or BinarryFormatter and [Serializable] attribute on class?

It's not possible to answer this, without knowing how you will use the resulting file, and the lifetime of it.
The decision is based on the fact that it is harder to "upgrade" the binary format. If your object model changes, it won't deserialise correctly. But if you've implemented a custom XML serialisation/deserialisation, then you can handle the "new" cases appropriately, and life will be good.
So decide more about how you will use it, who you are sharing information with, and what the possible changes to the model are.
FWIW, I sometimes use both types of serialisation in a given project.

That really depends on how you use the serialized class. If you want to pass it to other programs or want to easily debug it, use XML (but mind that XMLSerializer might produce non-compliant XML output, like multiple root elements).
In all other cases, you can use the binary formatter. But note that XML is more suitable if you change the class later - you can use XMLIgnore and the like to keep the XML format intact.

The decision will sometimes also be made for you based on what the serialized output will be used for - while you could expose a WebService to take a binary array that is a binary serialized item, you couldn't utilize the web service easily from anything but .Net (and the end client would probably need a reference to the type).
Using XML means that the service could be exposed to any end client regardless of the platform/environment on the end client

Related

Version control a protobuf-net serialised C# object

I have serialized a C# class using protobuf-net. The resultant byte array is stored in a database. This is for performance reasons and I probably won't be able to change this design. The C# language doesn't make it possible to prevent classes being modified, and the class structure being passed in for deserialization with time may require changes that will not match that used for serialization, causing retrieval to fail.
Other than the wrapper technique suggested here, is there a pattern or technique for handling this kind of problem?
The only othe technique that comes to my mind is to version the classes that need to be deserialized in order to not loose anything when you need to make some changes. When you serialize an instance of those classes, you have to serialize also the version of the class (it could be a field of the the class itself).
I don't think this is the best solution but a solution.
The versioning strategy could become very difficult to manage when the changes (and the versions) start to grow.

JSON Serialization Output Contains Count Property

I'm trying to serialize an array of objects into JSON in C#. By array I mean something like Object[] (not Array<Object>), I'm using a JsonMediaTypeFormatter as part of MVC (the serialization is happening automatically as part of the framework but I can override it). The output contains {"count":2,"value":[{...},{...},...]}" where the ... is the json representation of the object. I've looked around and haven't found much information about suppressing this behavior. I want the output to just be the [{...},{...},...] rather than the object with count and values properties. Does anyone know how to achieve this without manually writing the code to do the serialization?
You could consider an alternative framework like the JSON.NET framework. I don't know how much you can customize if you are using an in-built .NET object since there are public properties that are not being ignored. Not using the JSONMediaTypeFormatter much, if it allows you to ignore properties, consider overriding List or ArrayList to hide certain attributes.
I would recommend not returning an array directly as there is a security flaw that could be compromised in a client browser (if that is the consumer). See this reference to find out more.

Is it possible to make [XmlAttribute] as default for a class?

I have a lot of properties to serialize using XmlSerializer. I need to tag each (simple) property with [XmlAttribute] to make the output a little shorter. I'm wondering if there is an easier way to do it. Is there a way to make it as a default for a class, so that all simple type properties will be serialized as attribute instead of element?
No, basically. Well, you could do the work at runtime using XmlAttributeOverrides, inspecting your types in code and setting the attributes appropriately, then making sure you cache the serializer (if you don't cache when using XmlAttributeOverrides you leak memory, as the generated assemblies aren't collected). But that sounds like more work.
Re making the output shorter; xml compresses with GZip or Deflate very nicely...
Of course, if you don't need xml, but just need the data serialized somehow, there are other options.
You can create code snippets.
Create one for properties with the attribute already set, and use it when writing them.

What XML serialization method should I use for a public API?

I'm writing a program that builds up a tree structure made up of classes that inherit from an abstract Node class. There are a number of different type of nodes built into my program. However, I also want to allow more advanced users to be able to reference my library and write their own derivations of Node. These plug-in libraries are then loaded when my app starts up through Assembly.Load(). Thus all the potential Node types used by my application will not be known until run time.
In addition, I want to be able to serialize and deserialize these trees to and from XML files. I have some experience with XMLSerializer, DataContractSerializer, and implementing IXmlSerializable. Typically, I go with DataContractSerializer as it usually requires less code then implementing IXmlSerializable, and can serialize private fields where XmlSerializer can not.
Yet with this project I also have to consider that other users will be creating classes that derive from my class, and will also have to add whatever code or attributes are required to serialize them as well.
Considering this are there reasons I should go with one serialization mechanism over another?
If the serialization and deserialization will only occur within your application, and if there is no requirement that anyone else be able to read the serialized data, then the serialization format doesn't impact the API: as far as a user of the API is concerned, you will serialize into an opaque file and deserialize from the same.
In this case, use DataContractSerializer, as it can serialize into binary if necessary.

Serialize in memory object with C#

I've got a program that picks up some code from script files and compiles it.
And It works fine.
The problem is: in the scripts I declare a couple of classes and I want to serialize them.
Obviously the C# serializer (xml and binary) doesn't like to serialize and the de-serialize object defined in a in-memory assembly.
I prefer to don't leave the in-memory assembly so i'm looking for another way of serializing, but in case, is possible to build assembly in memory and eventually write it on file ?
You could always write your own ToXml function using reflection to write out your property data to a string. Then your object would deserialize itself.
Just a thought.
If you want to create assemblies dynamically look into IL emitting via reflection. Here is a good article to get you started.
So just to clarify, are you asking how you can serialize a type if it hasn't got the [Serializable] attribute applied?
One solution is to use the WCF Data Contract Serializer: http://msdn.microsoft.com/en-us/library/ms731923.aspx.
Obviously this will only work if you can target .Net 3.0 or higher.
Alternately you can implement an ISerializationSurrogate. Jeffrey Richter has a great introduction at http://msdn.microsoft.com/en-us/magazine/cc188950.aspx.
I would avoid all built-in serialization whenever possible, both are badly broken. For example, XML serialization doesn't support dictionaries and normal serialization/SOAP doesn't support generics. And both have versioning issues.
It is time consuming, but createing ToXML and FromXML methods is probably to most effective way to go.
Hava a look at here for custom serialisers, which is a sample for dictionary XML serializing
I'm slightly confused by the statement that the XmlSerializer can't serialize dynamically generated types. The XmlSerializer generates it's own serialization code dynamically as well during construction so there should be no issue with it serializing your type.
You may need to decorate your dynamic classes with the appropriate attributes, depending on what you are generating (like derived classes), but there shouldn't be any issue with using the XmlSerializer in the situation you described.
If you could post details about the issues the XmlSerializer is giving you I can help you work out what the problem is.
Also, I'm of the belief that auto-generating code is in general a blessing. All to often have I had to go back into a class to fix one or all of the copy/paste/save/load functions, just because someone forgot to update them when adding a new variable. Save/Load code is boiler plate code. Let the computers write it.

Categories