I would like to control object creation of a type that is not usually serializable during deserialization using a NetDataContractSerializer (or any serializer I guess). Using a custom SerializationBinder I can control the type that is constructed and using a custom ISurrogateSelector and ISerializationSurrogate to control how state is set on the object.
What I cannot do is actually create the object myself to allow the use of dependency injection or something. The object that is causing problems is inside the object graph so I cannot edit it before serialization.
Is there a way to allow my code to construct the deserialized object?
(For background, I am writing a custom WF4 persistence instance store based upon the XmlWorkflowInstanceStore in the WF samples. I want to author workflows that have variables that are interfaces... and the concrete types cannot be constructed directly. The XmlWorkflowInstanceStore is the only example I can find of custom persistence and it uses a NetDataContractSerializer to serialize the workflow state.)
I run into this problem all the time. I normaly implement ISerializable myself and set all the dependencies with an method (named for example SetDependencies) - this is not truly the way you might want (because you have to call it after deserialization) but I didn't find a better way yet (tried AOP but it went to nasty)
I know this question is old, but were you looking for GetSafeUninitializedObject?
Related
I have long held the believe that your domain model should not be responsible for serializing itself to XML. I have used the IXmlSerializable interface in the past to control how my objects are serialized but ideally I'd prefer the nuts and bolts of the serialization to live outside the object.
However I've never been able to actually implement this in a clean manner and I was wondering if there was any patterns I was overlooking to make this happen. Basically I want my object model to do it's thing and be oblivious to XML serialization (or any other serialization for that matter) and then handed off to some service that spiders the object and serializes it.
I've tried doing this with extension methods but this falls short when you want to serialize a collection of type object. I've looked at doing it with object wrappers and DTO's that then serialize but then you've got the overhead of maintaining another set of objects and having to create these objects when you want to serialize which again can get messy when you have collections of type object.
The only other thing is using reflection but I'd worry about the processing overheads.
Is there a sane way to do what I'm asking or should I just bite the bullet and make my objects xml aware?
Using the System.Xml.Serialization Attributes is putting the nuts and bolts outside of your code. You are defining metadata and with the exception of optional parameters, no extra code is required. Implementing IXmlSerializable and doing the serialization by hand is error prone and should be avoided. Why? You are defining your data 3 times.
XML Schema
Class
Serialization code
Using attributes, you can scrub step 3.
XML and C# has an impedance mismatch. Like it or not, at some point, you will need to define the serialization to create the right document model.
Arguably, the classes you are serializing should not be performing any work. They are just a data store. Try abstracting your logic away from serialized objects - it may give you a warmer feeling.
Update
If you really, really hate attributes, try using the adapter pattern to serialize your model. The XML code will be in a separate class or assembly and you can work with your model across storage mediums. You will suffer the consequence of having to update the serialization separately when you update your model.
I'm trying to create a function that will save the current state of my application to a file, and another function to load a saved file. Currently, all the information is contained within a single object, which in turn refers to other objects. I recently heard that C# has some built-in classes that help you serialize and deserialize your objects, so I did a little research and learned about DataContracts, mostly from this page: http://msdn.microsoft.com/en-us/library/ms731073.aspx
Most of it works, except for the classes that implement built-in classes. For example, I have an object that inherits System.Windows.DependencyObject, and when I try to serialize it, it complains that my class inherits a class that does not have the DataContract attribute.
It makes sense to me why that would be a problem. When an object is being deserialized, its constructor is not called. If it inherits something that is not serializable, that might leave it in an invalid state.
I was wondering if this was possible: can I somehow tell the deserializer to call the base class's default constructor before deserializing my object? And then I would have to tell the serializer not to freak out.
Can you create a data transer object that has all the properties you want to store, then populate that object with data from the framework object? Mark it as serialized, fire up the serialization class of your choice - and now you have all the info you need. You just need to re-populate the appropriate class after deserialization.
You may want to look into using a binary serializer or xml serializer instead of a data contract serializer for this one. If you're saving it to a file and don't need the file human-readable binary serialization nearly always works.
See Binary Serialization, and in particular the Basic Serialization topic.
Also take a look at the XmlSerializer Class which will sometimes work where a DataContractSerializer doesn't.
CustomLineCap does not have the SerializableAttribute applied to it.
I want to add a property of this type to an object graph that is currently being serialized/deserialized with a BinaryFormatter.
I tried switching to XML serialization but it has a bunch of extra requirements and I don't want to fool with that esp. since it's not my code; it's some open source I downloaded.
If there's a way to get BinaryFormatter to ignore the property, that might work.
I'd rather subclass it; I just don't know if that will work either.
You aren't going to be able to serialize an instance of the CustomLineCap class directly. It derives from the MarshalByRefObject class, and while that's not an indicator that it can't be serialized, it's almost always the case.
The reason being that the MarshalByRefObject class is usually an indicator that the object that derives from it only has context in the application domain in which the instance lives. In this case, you the CustomLineCap instance is a GDI object which only has any meaning in the process that it lives in (it's tied explicitly to a handle).
That said, I'd recommend using the adapter pattern to create a wrapper that captures the properties of the CustomLineCap instance that you wish to serialize and then expose and serialize that.
This is generally the approach you'd want to take with any class that has a context that is tied to a specific domain that when serialized to be persisted outside of that domain, doesn't make sense anymore.
Note that subclassing won't work in this scenario either, in that applying the SerializableAttribute to your subclass means that all of the fields (even the private ones that you don't have access to) will be serialized, including any handles which only have context in the application domain they are created in.
I have 3-rd party dll. From that I receive an object of some type (I know its interface, but not all the object). That object is not marked as serializable and I'm not related to that libruary development at all.
I want to serialize it to some storage and then receive it from storage with the same state later (public/private, references etc.). I got here one option - make my own serialization mechanism that will act the same as .NET serializers with the only difference - it won't revise serialization attributes.
Is that the best way?
Thanks.
You can use XmlSerializer or DataContractSerializer to serialize types not marked with SerializableAttribute.
There may be other options. And can always go ahead with custom implementation if nothing works for you.
You can make your own class inheriting from that object and serialize it.
OR you can make your own replica of that class and make some explicit (or implicit, but not recommended) conversion methods.
.NET provides the JavaScriptSerializer class in the
System.Web.Script.Serialization namespace. (provided in System.Web.Extensions.dll)
It was originally intended to support AJAX web server apps, but the class can be used by any application (client, server, hybrid, anything) that serializes and deserializes .NET classes to JSON. I have a desktop app that captures screenshots and uploads to Facebook, and uses this class to deserialize the response.
would I ever want to look elsewhere for JSON deserialization from within .NET?
If so, why? and where would I Look?
If not, then why does JSON.Net exist? Is it strictly for historical purposes? (ie, because it was created by the community before the JavaScriptSerializer).
In my case there are various reasons that prevent me to use JavaScriptSerializer. Here are some of them.
1) Ugly deserialization when dealing with anonymous types
While the usage is fairly straight forward for serialization:
JavaScriptSerializer serializer = new JavaScriptSerializer();
String json = serializer.Serialize(data);
For deserialization however, there is a minor annoyance in that the deserializer accepts a generic type along with the content:
serializer.Deserialize<T>(String s)
this can be a problem if the type T is not known at compile time and needs to be dynamic. The work around is a bit ugly as I learnt because it uses reflection to create a generic method (but it works)
var result = typeof(JavaScriptSerializer).GetMethod("Deserialize")
.MakeGenericMethod(JsonDataType)
.Invoke(serializer, new object[] { inputContent });
Please note: according to Dave Ward comment on this answer there's a DeserializeObject() that can be used to prevent this.
2) Cannot handle circular references
I have seen this using Entity Framework, Linq to SQL, NHibernate, NetTiers and even when using Castle's proxy.
According to MS Connect the circular reference exception will be raised when a navigable relation is double-sided (can access both sides of the relation), so the first thing to do is disable one side of the relation. The exception will also be thrown when you use 1:1 relations (or 1:0..1 or any relation causing the creation of an EntityReference type property), in this case the exception will be of type System.Data.Metadata.Edm.AssociationType.
The solution to this is to make the serializer ignore the properties of type EntityReference, using an empty implementation of a class deriving from JavaScriptConverter and registering it using the RegisterConverters method of the JavaScriptSerializer object.
3) Useful features that leads to less testable code
A useful feature of the JavaScriptSerializer is that you can also implement a custom JavaScriptConverter and pass that in to JavaScriptSerializer for fine-grained control over the serialization/deserialization. However, for it to be really useful you need to know the types at compile time and have references to those types. This really limits the usefulness of this feature because by referencing those classes your code becomes tightly coupled so you cannot easily use it in something like an MVC filter.
For these reasons I have often ended up using Json.NET.
Hope this helps!
I use the JavaScriptSerializer on a wide variety of scenarios, it never let me down, and never needed to look elsewhere for other solutions... :)
...but i do know that JSON.net has some added values like LINQ to JSON, which i never needed, and nice JSON formatting but as Serializing goes JavaScriptSerializer does the work fine.