270 likes | 846 Views
Serialization What is Serialization. Serialization is the process of converting an object, or a connected graph of objects, stored within computer memory, into a linear sequence of bytes Use the sequence of bytes in several ways: Send it to another process
E N D
SerializationWhat is Serialization • Serialization is the process of converting an object, or a connected graph of objects, stored within computer memory, into a linear sequence of bytes • Use the sequence of bytes in several ways: • Send it to another process • Send it to the clipboard, to be browsed or used by another application • Send it to another machine • Send it to a file on disk
SerializationObject Graph • What is an object graph? • An object graph is a set of objects with some set of references to each other • The most obvious problem is how to represent the links between the objects in the Serialized stream 3 Dog Cat Cat 1 Mouse 4 7 2 Duck 9 Horse
SerializationHow Serialization Works • Because run-time metadata 'knows' about each object's layout in memory, and its field and property definitions, you can serialize objects automatically, without having to write code to serialize each field • The serialized stream might be encoded using XML, or a compact binary representation • The format is decided by the the Formatter object that you call: • Binary • SOAP • Custom
using System; namespaceVideoLibrary { [Serializable] publicenumGenre { Drama, Comedy, Western, ScienceFiction, Horror, Family }; [Serializable] publicclassVideoInfo { publicstring Title { get; set; } publicGenre Category { get; set; } publicstring Director { get; set; } publicint Year { get; set; } publicTimeSpan Duration { get; set; } publicstring Review { get; set; } } } Serializaiton Example - VideoLibrary Worksheet 4 from http://www.cse.ohio-state.edu/~crawfis/cse459_CSharp/index.html
namespaceVideoLibrary { publicpartialclassMyVideoLibraryForm : Form { List<VideoInfo> videoLib = newList<VideoInfo>(); … privatevoidsaveLibraryToolStripMenuItem_Click(object sender, EventArgs e) { if (this.saveLibraryDialog.ShowDialog() == DialogResult.OK) { XmlSerializer s = newXmlSerializer(videoLib.GetType()); using (TextWriter w = newStreamWriter(saveLibraryDialog.FileName)) { s.Serialize(w, videoLib); } } } Serializaiton Example - VideoLibrary File->Save menu Worksheet 4 from http://www.cse.ohio-state.edu/~crawfis/cse459_CSharp/index.html
privatevoidopenToolStripMenuItem_Click(object sender, EventArgs e) { if (this.openLibraryDialog.ShowDialog() == DialogResult.OK) { XmlSerializer s = newXmlSerializer(videoLib.GetType()); using (TextReader reader = newStreamReader(openLibraryDialog.FileName)) { List<VideoInfo> newVideos = (List<VideoInfo>)s.Deserialize(reader); foreach( VideoInfo video innewVideos) bindingVideoLib.Add(video); } } } Serializaiton Example - VideoLibrary File->Import menu Worksheet 4 from http://www.cse.ohio-state.edu/~crawfis/cse459_CSharp/index.html
Serialization Scenarios • Persistence • Remoting-By-Value • Remoting-By-Reference • Transacted Persistence
SerializationBasic Serialization • A Type is NOT Serializable unless Type is specifically marked as Serializable • The Serializable Attribute • The Non-Serializable Attribute [Serializable] public class MyClass {} [Serializable] public class MyClass { [NotSerialized] int _cashSize; }
Serialization • It is easy to write the individual fields of a record object to a file • For example, we can create a record that stores information about a student • Name • Address • ID number • Course enrolled for • etc • We can output each field of this record to a file (either text or binary)
Serialization Record file string stringint string StudentInfo Name Address ID number Course Info
Serialization • In this example, any program that needs to read the file needs to know the format of the data • 2 strings, an int and then a string • Also whether each item is on a separate line • .NET serializationallows complete objects to be read or written with a single statement (.NET does the plumbing for you using reflection). • A serialized object is an object represented as a sequence of bytes. • Information is stored about the data types of the objects instance fields as well as their values • Allows the object to be reconstructed (de-serialized) from the sequence of bytes.
Serialization Record file StudentInfo object StudentInfo Name Address ID number Course Info
Serialization • To serialize an object, the object class needs to be marked with the [Serializable] attribute or needs to implement the ISerializable interface • Requires the System.Runtime.Serialization namespace • Also we require a formatter to serialize/de-serialize the object before writing to or reading from file • IFormatter - BinaryFormatter • XMLSerializer (why is this not an IFormatter?)
SerializationISerializable Interface • Customize the serialization process • If a class implements ISerializable, that interface will always be called in preference to default serialization. • The ISerializable interface only contains one method: voidGetObjectData (SerializationInfo info, StreamingContext context); And an implied constructor that may be private. private <T> (SerializationInfo info, StreamingContext)
SerializationAdditional Attributes • The serialization framework allows you to also specify methods to be called when an instance is being deserialized, after it is deserialized, before it is serialized, etc. • [OnDeserialized] – see the MSDN example.
SerializationIDeserializationEventListener • If an object implements IDeserializationEventListener, the serialization infrastructure will call that class‘ OnDeserialization method as soon as the entire graph has been deserialized and all fix-ups completed • Provide a reasonable opportunity for objects that need to do fix-ups based on the state of their children
Serialization • Binary serialization is limited as only .NET applications can deserialize the data stream • For more general inter-operability especially across a network, xml serialization is used • xml is text based and self descibing and universal • Comprised name/attribute pairs • xml serialization easy to implement and uses text streams
Serialization • We need to insert xml tags into our StudentInfo class • Only public properties and fields can be serialized [XmlRoot("studentInfo")] public class StudentInfo { [XmlAttribute("name")] public string Name; [XmlAttribute("address")] public string Address; [XmlAttribute("course")] public string CourseInfo; [XmlAttribute("id")] private int ID; public StudentInfo() { } public StudentInfo(String n, String a, String ci, int id) { Name = n; Address = a; CourseInfo = ci; ID = id; } }