I want to save properties of controls that user change at runtime.(.Net windows form application)
I just using BinaryFormatter to serialize object, It's work but some properties not serialize, therefore i want to save object as binary
Note: I using third-party component without source code
Could you please help me?
Serializing the object is saving it "as binary". If you're looking for a straight memory dump, you're out of luck - that's just not realistic in .NET.
If serialization doesn't work out of the box, you may need to serialize what you can and then bolt on extra information about the properties that aren't currently being serialized. I would personally be slightly worried at how brittle this solution could be though - there may be very good reasons for the properties not being serialized. (.NET binary serialization is pretty brittle to start with...)
Why not contact the author of the component and ask for their advice? They're likely to know more about any quirks you might run into than we are.
Related
I have a complex model I want to persist to Mongo DB. This model has some circular reference I don't want to break.
Apparently I can't do that with the official Mongo C# driver.
Json.Net can serialize properly in Bson, and handle my model without any problem.
Can I change the mongo driver serializer ? Or do you have any other suggestion to handle this case (other than just avoid circular reference or ignore property) ?
Thank you.
Customized serialization/deserialization is a good solution, but it does not have to be painful. The simplest way may be for your model to use the ISupportInitialize interface, and implement the BeginInit() and EndInit() methods.
Sergio Costa has a good example of using this interface to deal with circular references on a web page titled Serializing circular references in MongoDb.
If you can't break the connections, there are a number of options for doing custom serialization.
I'd start here: http://docs.mongodb.org/ecosystem/tutorial/serialize-documents-with-the-csharp-driver/
In particular, the section entitled "Write a Custom Serializer." You'll need to decide whether the potential extra complexity is worth it.
Or, you could consider converting the objects to json, then to a BsonDocument.
BsonDocument document = BsonDocument.Parse(json);
If you do need this extensively, just note that you are doing a reasonably significant amount of busy work with the Object->JSON->BsonDocument->Bson path. It's something to consider if you need high throughput or are concerned about CPU/memory utilization.
I'm building a small app that needs to save an object to a file in order to save user data.
I have two questions about my serialization to this file :
The object I'm creating has some public properties and an event. I added the [Serializable] attribute to my object, and then realized I can't serialize an object with an event in it.
I then discovered that I can just add an attribute above my event [field:NonSerialized] and it will work. Is this the best way to do this, or should I try to build my Serializable objects without any events inside ?
The object I'm serializing saves some user settings about the app. These settings aren't sensitive enough to go about encrypting them in the file, but i still don't want them to be tampered with manually without opening my application. When i serialize my object to a file using a plain BinaryFormatter object, via the Serialize() method, I see readable names of .net object types in the file i'm saving this to. Is there a way for someone to reverse engineer this and see what's being saved without using my program ? Is there a way for someone to build a small application and find out how to DeSerialize the information in this file ? If so, how would i go about hiding the information in this file ?
Are there any other tips/suggestions/best practices i should stick to when going about serializing an object to a file in this kind of scenario ?
Thanks in advance!
If your object implements the ISerializable interface, you can control all the data that is stored/serialized yourself, and you can control the deserialization.
This is important if your project evolves in time. Because you might drop some properties, add others, or change the behaviour.
I always add a version to the serialization bag. That way I know what was the version of the object when it was stored, and I therefor know how to deserialize it.
[Serializable]
class Example : ISerializable {
private static const int VERSION = 3;
public Example(SerializationInfo info, StreamingContext context) {
var version = info.GetInt32("Example_Version", VERSION);
if (version == 0) {
// Restore properties for version 0
}
if (version == 1) {
// ....
}
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
info.AddValue("Example_Version", VERSION);
// Your data here
}
}
And if you do not encrypt, it will be very easy to "read" your data. Very easy meaning you might have to invest a couple of hours. If the data you store is worth a couple of days, this means it is easy, if it is only worth a couple of minutes it is hard. If you get the point.
A very easy way to encrypt your data is using the Windows DPAPI through the ProtectedData class.
1: with BinaryFormatter, yes - you need NonSerialized for events (unless you implement ISerializable, but that adds lots of work); however I'm pretty much on-record as saying that I simply wouldn't use BinaryFormatter here. It is not very forgivig for a range of changes to your type. I would use something less tied to the internals of your code; XmlSerializer; DataContractSerializer, JavaScriptSerializer. I can suggest binary alternatives too; NetDataContractSerializer, protobuf-net (my own), etc.
2: yes, with almost any implementation that doesnt involve proper encryption, if anyone cares they can reverse engineer and obtain the strings. So it depends how hidden it needs to be. Simply running your existing serialization through GZipStream may be enough obfuscation for your needs, BUT this is just a mask against casual inspection. It will not deter anyone with a reason to look for the data.
If the data needs to be secure, you'll need proper encryption using either a key the user enters at app startup, or something like a certificate securely stores against their user-profile.
I would remove the events from the objects. It's a little cleaner that way.
Anything can be reverse engineered. Just encrypt it when saving the file. It's pretty easy to do. Of course, the encryption key is going to have to be stored in the app somewhere, so unless you're obfuscating your code a determined hacker will be able to get to it.
I have a pretty complex web of objects I'd like to serialize and deserialize in an untrusted environment (web browser, using Unity 3D). Plain BinaryFormatter serialization is working fine, but deserialization crashes with "access to private field" errors. It works perfectly when I am running locally.
I would rather not make my codebase suck by making all my private fields public. What is the best way to get deserialization to work in an untrusted environment without doing this? I am open to changing serialization methods, BinaryFormatter was just the easiest to get started with.
UPDATE I don't want to prevent serialization from accessing my private data, I want to allow serialization to access my private data without having to make it public, compromising the encapsulation of my code.
Thanks.
Serializers like XmlSerializer and JavaScriptSerializer work against the public members, so they should (crosses fingers) work acceptably in terms of trust. You could also try protobuf-net if you want binary - but I haven't aggressively tested this scenario (it works in things like Silverlight, though, which has a fairly picky trust model).
If you want to stick with BinaryFormatter but don't want it touching your fields directly you could implement ISerializable, but doing it all manually is... painful.
None of the answers really answered my question (see the update for clarification). I ended up writing my own simple serialization format using BinaryWriter. In the end I realized what I did was equivalent to manually implementing the ISerializable interface for my classes. I had to manually implement the graph serializatoin code. While not hard, it's a bit subtle, and it has already been done for me. For future perople with this question, if there are no better answers, I recommend manually implementing ISerialzable.
Well, if you want to prevent the private field access by serialization, you may want to move over to Xml Serialization of perhaps even Json serialization.
You can prevent the private fields from serializing by placing NonSerializaed attributes on them, but you may run into problems when developers expect their fields to contain valid values and do not take into account the fact that those field values get lost when transferred to the Unity plugin.
We are building application that stores objects to isolated storage using .NET runtime serialization.
Problems occur when we update application by adding some new properties to the classes of objects we are serializing. So we want to do some kind of versioning of the objects in isolated storage so we can check if they are obsolete before they are deserialized.
Any advice and ideas how to do this on best possible way?
What do you think about custom formatter implementing IFormatter interface and can it help instead of vesioning objects?
I wrote about this issue on MS forum more detailed here.
You COULD have a serialization in the serialization. First a wrapper class telling the version, and holding the inner true class.
This however feels a bit bad smelly..
Here are a few options (at in any particular order).
Name the file based on the version
Place the file in a directory based on a version
Create a wrapper object that contains metadata about each serialized object such as the version number.
Add a property to each object that contains the persisting application's version number
If its binary serialization, you could read the bytes directly, and determine the assembly version from this. Byte number 22 onwards contains information on the assembly and object type, so you could write something that would read this, and then determine if your objects are obsolete.
Marc Gravell was propose in comment great idea to use version-tolerant serializer.
It enables enough control of deserialization for us even to make obsolete objects reusable.
More on msdn
Thanks to all for suggestions.
It's ok if the answer to this is "it's impossible." I won't be upset. But I'm wondering, in making a game using C#, if there's any way to mimic the functionality of the "save state" feature of console emulators. From what I understand, emulators have it somewhat easy, they just dump the entire contents of the virtualized memory, instruction pointers and all. So they can resume exactly the same way, in the exact same spot in the game code as before. I know I won't be able to resume from the same line of code, but is there any way I can maintain the entire state of the game without manually saving every single variable? I'd like a way that doesn't need to be extended or modified every single time I add something to my game.
I'm guessing that if there is any possible way to do this, it would use a p/invoke...
Well, in C# you can do the same, in principle. It's called serialization. Agreed, it's not the exact same thing as a memory dump but comes close enough.
To mark a class as serializable just add the Serializable attribute to it:
[Serializable]
class GameState
Additional information regarding classes that might change:
If new members are added to a serializable class, they can be tagged with the OptionalField attribute to allow previous versions of the object to be deserialized without error. This attribute affects only deserialization, and prevents the runtime from throwing an exception if a member is missing from the serialized stream. A member can also be marked with the NonSerialized attribute to indicate that it should not be serialized. This will allow the details of those members to be kept secret.
To modify the default deserialization (for example, to automatically initialize a member marked NonSerialized), the class must implement the IDeserializationCallback interface and define the IDeserializationCallback.OnDeserialization method.
Objects may be serialized in binary format for deserialization by other .NET applications. The framework also provides the SoapFormatter and XmlSerializer objects to support serialization in human-readable, cross-platform XML.
—Wikipedia: Serialization, .NET Framework
If you make every single one of your "state" classes Serializable then you can literally serialize the objects to a file. You can then load them all up again from this file when you need to resume.
See ISerializable
I agree with the other posters that making your game state classes Serializable is probably the way you want to go. Others have covered basic serialization; for a high end alternative you could look into NHibernate which will persist objects to a database. You can find some good info on NHibernate at these links:
http://www.codeproject.com/KB/database/Nhibernate_Made_Simple.aspx
http://nhibernate.info/doc/burrow/faq