I need to serialize a collection, but I would like to know if there is any already serializable collection before taking code from third parts or write it by myself. I already implemented some serializable collection, but this is a stupid situation where I just need to pass an array of serializable classes to the clipboard and back from it (copy/paste).
Any suggestion on what should I use?
Any class in the System.Collections or System.Collections.Generic namespace should be serializable. However, this doesn't mean that the content (or in the case of generics, T is serializable). This is visible with Dictionary<K,V>, as KeyValuePair<K,V> isn't directly serializable.
I used List<T> before and it works great.
Related
Going on with my quest to bend protobuf-net to my own will..
I've seen a few questions around SO on how to add sub-classes dynamically
for the serializer to be able to encode the sub-class.., like this or this
My situation is bit different, I have a base class that might get sub-classed in late-bounded code, and I want to serialize is as the BASE class, and completely ignore the sub-class's fields/properties.
The reason I need this, is that later on, when I deserialize the data, the sub-class's code will not be even available, so constructing the sub-class will not be even possible.
Is there a way to limit/prohibit sub-class serializtion?
In my case I have a List where some items in the list are DerivedClass.
I would like to find a way to make protobuf-net serialize everything as BaseClass and to deserialize to BaseClass as well...
I've tried peering into code, but haven't found something too useful.
Normally, the library is very particular about spotting derived classes - and treating them differently from the base class. The only current exception to that is proxy classes, in particular Entity Framework and NHibernate. For a tidy solution, it would seem practical to add some kind of "ignore subclasses" switch. But while that doesn't exist, a very lazy (and hacky) approach would be to cheat using the existing handling for NHibernate, for example:
namespace NHibernate.Proxy {
interface INHibernateProxy {}
}
...
public class SomeDerivedType : BaseType, INHibernateProxy {}
this will then automatically be serialized as per BaseType. It does have a faint whiff of cheating about it, though.
What des it mean by the following sentence
DependencyObjects are not marked as serializable
To my knowledge, I can have a class which inherits from DependencyObject...and I can mark it as serializable. Anyway serialize property is not inheritable.
Could someone make me clear. Thanks in advance.
This means that a class that derives from DependencyObject cannot be serialized with standard serializers. As a workaround you could use XamlReader/XamlWriter as shown in this article.
DependencyObject exists to make use of the entire dependency property system. One side effect of this is that it really doesn't mesh with the approach to serialization taken in .NET.
Serialization, in .NET, serializes fields in a class. However, DependencyObjects don't actually use (instance) fields, but rather registered DependencyProperties, which are stored elsewhere (if at all). As such, they don't serialize properly, even if you mark them [Serializable].
Seeing as you can convert any document to a byte array and save it to disk, and then rebuild the file to its original form (as long as you have meta data for its filename etc.).
Why do you have to mark a class with [Serializable] etc? Is that just the same idea, "meta data" type information so when you cast the object to its class things are mapped properly?
Binary serialization is pretty powerful, it can create an instance of a class without running the constructor and can set fields in your class that you declared private. Regular code can of course not do this. By applying the [Serializable] attribute, you explicitly give it the go-ahead to mess with your private parts. And you implicitly give that permission to only the BinaryFormatter class.
XML serialization doesn't need this kind of okay, it only serializes members that are public.
DataContractSerializer can serialize private members as well. It therefore needs an explicit okay again, now with the [DataContract] attribute.
First off, you don't have to.
It is simply a marker interface that tells the serializer that the class is composed of items that it can serialize (which may or may not be true) and that is can use the default serialization.
The XMLSerializer has the additional requirement to have a zero parameter constructor to the class.
There are other serializers that use contracts for serialization (such as the DataContractSerializer) - they give you more control over serialization than simply marking a class as Serializable. You can also get more control by implementing the ISerializable interface.
It's basically metadata that indicates that a class can be serialized, nothing more.
It is required by a lot of framework serializers, which refuse to deal with types not having this attribute applied to them.
Serialization can create security holes and may be plagued by versioning problems. On top of that, for some classes, the very idea of serialization is outright nonsense.
For details, see the excellent answers to Why Java needs Serializable interface?, especially this one, this one, and this one. They make the case that serialization should be a feature you have to explicitly opt into.
For a counterpoint, the accepted answer to that question makes the case that classes should be serializable by default.
It indicates to the serializer that you want that class to be serialized as you may not want all properties or classes to be serialized.
I see it as a reminder that I will allow the class to be serialized. So you don't implicitly serialize something you shouldn't.
Don't know it that is designers' intention.
BTW, I just love BinaryFormatter and use it as much as I can. It handles pretty much of the stuff automatically (like rebuilding complex object graphs with recurring references spread throughout the graph).
I have a situation where I need to serialize an object but don't want to serialize any of its references. This is because I don't know in advance which dlls the object might be referencing and therefore can't ensure that they are serializable objects. This has arisen from needing to serialise plugins to preserve their state.
Am I right in thinking that this is the case with XML serialization (shallow)? But that this will ignore anything private in the object - which isn't what I want?
Is this somehow possible?
Xml Serialization will only work on things that are publicly accessible. Also, unless you mark a public property / field with the [XmlIgnore] attribute, it will be serialized.
If you're just looking at some method of serialization, then use binary serialization. It will serialize the internal state of the object (all fields, private or otherwise). You can use the [NonSerialized] attribute to ignore specific references if you want.
If you know at the type declaration time which references should not be serialized you can use binary serialization and filter out members with the [NonSerialized] attribute.
Put NonSerialized attribute in case of binary and XmlIgnore attribute in case of xml serialization to reference properties or fields
You do know which properties you can serialize, though, correct? Are these plugins implementing a common interface? If that is the case, you should be able to write a generic serializer that will only serialize the specific properties that you choose.
Here is a basic example that will give you the idea of what you need to do:
Object Serialization using C#
If you are just looking to serialize native types within your class instances, you should just be able to implement ISerializable, though, and decorate the properties that you do not want to be serialized.
You can try something like this:
Type myType = currentObject.GetType();
Then check to see if the object is serializable by using:
myType.IsSerializable; //returns a bool
That should tell you whether or not the object is serializable. If you really need to know whether every single object inside of a class is serializable, such as other nested classes or custom types, then you could probably use reflection to read each object, use the code above, and verify whether or not it is serializable. This, however, might be a more complicated approach, and may not be plausible, especially if you have overhead issues to deal with.
It may be useful for you to separate what you want to persist from how you persist it.
It seems like you want control over how you want to persist data, but obviously, cannot know what it is, because of your plugin model.
One scheme that may make sense to you is to give your plugins some sort of object or interface they can write to and read from when its time to save / load. Its fine to document these constraints.
For example, when persisting, allow your plugins to pass to you:
some arbitrary byte array which they are responsible for serializing / deserializing. Then it is a plugins responsibility to make sure they use objects that are appropriately serializable.
a dictionary of strings
an xml file
others...
Store this information per plugin (in whichever form you want), and loading up again, pass back the same information.
This is simply an approach around the fact that in the end, the plugin knows what it needs to save, and needs to own that piece of information.
I have a class that parses very large file (that can't fit in memory) and I'm currently utilizing the IEnumerable interface to use foreach so I can easily grab the parsed contents of the file line by line. Currently, I'm trying to write this to file using an XMLSerializer. It insists on enumerating the class and in my case, this means dumping large, parsed content of files to the XML. Is there anyway (hackish or elegant) to use this interface and still get the "expected" functionality out of a XMLSerializer?
(I only call this "expected" because this seems an expected outcome if I was implementing some collection interface rather than IEnumerable. Perhaps my concepts of IEnumerable and collections is all out of whack. :( )
Well, you could implement IXmlSerializable and seize full control. It isn't entirely clear (without pseudo code) what the setup is - sometimes [XmlIgnore] can help, but I'm not sure in this case without an example of what you have, and what you do/don't want.
I managed to fix this problem without having to change my design. None of my code was relying on the IEnumerable interface, just the implementation of IEnumerable GetEnumerator() (apparently foreach doesn't check to see if IEnumerable is implemented). Just commenting out the interface in the class declaration did the trick.
It seems to me that your problem could be solved by using tighter encapsulation.
It sounds as if you are using the same class to load your data from file, and to store the in-memory representation of that data. If this is the case, you could (and possibly should) move the functionality into two classes. Then only serialize the 'in-memory' class.