XmlDeserialization after renaming the classes involved - c#

I have a bunch of xml serialized objects in a database.
But, I refactored and renamed the classes involved, so deserializing from the db is difficult.
I thought that by adding the term [XmlRoot("DB_Class_Name")] atop the renamed classes would fix the issue, but it doesn't appear to.
Is there a way to fix the issue using labels like [XmlRoot], [XmlElement] etc., without renaming my classes to their old classnames, and without writing a special deserialize function?
Also, are there any good sources on what is happening under the hood when using xmldeserializaiton and labels like [XmlRoot]?

First of all, [XmlRoot] etc. aren't labels, they're attributes.
Second, [XmlRoot] only affects the class when that class is used as the root element of the document. It has no affect when an instance of that class is used as a child or other descendant.
Use [XmlType] on the class, or [XmlElement] on a property that is of the type of the class.

Related

Reacting on serialize and deserialize of an instance

I have a class which i am serializing. I annotated it with [Serializable] and i am using binary serializer. Everything works fine.
But later i introduced new properties, which cannot be serialized (lets say they contain a lot of mess about GUI which does not need to be rembered). I can compute these properties based on other properties of class.
I need to do it two times, when I serialize - clean mess and enter stabile state ready for serialization. And deserialization - again compute all needed properties.
I need to react on 'events' instance is being serialized/deserialized.
However I can't find these events because I am not implementing the interface ISerializable or abstract class Aserializable but only class atribute [Serializable].
I do not know when class is being serialized because it is not the concern of this class; it is serialized as a field of another class.
Is there a way I can react on those events?
You can use OnDeserializedAttribute and its related attributes (OnSerializing, OnSerialized, OnDeserializing) to create special methods that are called during the serialization/deserialization process.
Build Custome Serialization by Implementing ISerializable. Use OnSerializingAttribute, to manipulate object before serilazation and OnDeserializingAttribute, to manipulate before deserialization.
Have you considered per chance the [XmlIgnoreAttribute] attribute? It will prevent a property to be serialized. No need to tamper withe the serialization workflow.
My bad, didn't realize you wanted to reload some property on deserialization. So why not serialize these? In an optional subObject, or whatever?

Limiting protobuf-net inheritance "tree"

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.

Using Nested Classes with Entity Framework

I've tried to do this in the designer, but I wasn't able to figure it out. Is it possible to persist nested classes using Entity Framework?
Note: I am just curious whether this is possible or not. I can't think, at this point, if there would ever be a reason to do this, but it might be nice to know how if it is possible.
Example:
public class NormalClass
{
public class NestedClass { }
}
Update:
Danny Varod had a good idea for how to accomplish this. When I have some spare time, I'm going to try it out, and I'll post the results on here, unless someone else gets to it first.
EF classes are declared partial, so you can add whatever you want to them.
Note that the inner-class's properties won't be persisted to the DB, if you want that, use a navigation property instead.
A nested class in .NET is basically the same as a class within another level of namespace (accept for the fact the inner class can access private parts of outer class, as Ladislav Mrnka pointed out - you could use internal instead of private to get around this), there is no change in behaviour (unlike in Java), so there is not much point in using nested classes.
You can define sub objects using complex properties or using a navigation properties, however, complex properties have limited capabilities (no navigation properties or keys in them) and neither are created as nested classes.
To force EF to use nested classes, you could try creating the classes yourself, then mapping them either with a Code-First approach or by cancelling the auto-creation of the class and writing them yourself (or changing the .tt file to created classes nested) and then editing the .emdx as an xml to map entity to a different class.

Why do you have to mark a class with the attribute [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).

Having DataContractSerializer serialize the same class in two different ways?

I'm using the DataContractSerializer to serialize an objects properties and fields marked with DataMember attributes to xml.
Now a have another use case for the same class, where I need to serialize other properties and other fields.
Are there a way to add "another DataMemberAttribute" that can be used for my other serialization scenario?
No, basically.
If you want to use the existing DataContractSerializer, you'll have to maintain a second version of the DTO class and convert the data between them.
Options if you are writing your own serialization code:
declare your own [DataMember]-style attribute(s) and interpret them at runtime in your own serialization code
use a "buddy class"
use external metadata (such as a file)
use code-based configuration (i.e. via a DSL)
In reality, I expect the first will be the simplest choice.
In a similar scenario in the past, we've taken an Object Oriented approach, and created a new class that extends from the main class.
To help you achieve inhertience with the DataContractSerializer, check out KnownTypeAttribute
In one of your comments to your question,
If the same class is implementing multiple interfaces, certain data elements may be relevant to only one of the interfaces.
If that is the case in your scenario, then perhaps your Data Service Contracts should be exposing just the Interfaces, and not the Class?
For example, if you have a class like:
[DataContract]
public class DataObject : IRed, IBlue
then rather than have your operation contract expose DataObject, you have two operation contracts one for IRed and one for IBlue.
This eliminates the need for custom serialization code.
There is a way to do it, but it's an ugly hack.
The DataContractSerializer can serialize objects that implement the IXmlSerializable interface. You could implement the interface and create your own ReadXml(XmlReader reader) and WriteXml(XmlWriter writer) methods that could serialize the object in different ways.
Note that you'd have to have a flag embedded within the class itself to determine which way to serialize the object. (There's no way to tell the DataContractSerializer which mode to use, so the flag has to be contained in the object itself.)
A second version of the DTO class, as #Marc suggests, would be much cleaner.

Categories