Serialization Example Discuss the code example on the Serialization Example slide in which default serialization is performed on a graph of objects, whose root is an ArrayList, and the s
Trang 2domain names, e-mail addresses, logos, people, places and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, place or event is intended or should be inferred Complying with all applicable copyright laws is the responsibility of the user Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property
2001-2002 Microsoft Corporation All rights reserved
Microsoft, ActiveX, BizTalk, IntelliMirror, Jscript, MSDN, MS-DOS, MSN, PowerPoint, Visual Basic, Visual C++, Visual C#, Visual Studio, Win32, Windows, Windows Media, and Window NT are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A and/or other countries
The names of actual companies and products mentioned herein may be the trademarks of their respective owners
Trang 3Instructor Notes
After completing this module, students will be able to:
• Write an application that serializes and deserializes an object graph by using either a binary or Simple Object Access Protocol (SOAP) XML format
Materials and Preparation
This section provides the materials and preparation tasks that you need to teach this module
Required Materials
To teach this module, you need the Microsoft® PowerPoint® file 2349B_12.ppt
Preparation Tasks
To prepare for this module, you should:
! Read all of the materials for this module
! Complete the lab
Presentation:
30 Minutes
Lab:
45 Minutes
Trang 4Module Strategy
Use the following strategy to present this module:
! Serialization Scenarios Discuss briefly how serialization is used in scenarios such as persisting in-memory objects to disk and in remoting Mention the Microsoft NET Framework’s support for serialization and deserialization as an introduction
to the rest of the module
! Serialization Attributes Explain how to mark a class with serialization attributes in C# by using the
Serializable attribute Also cover the NonSerialized attribute
! Object Graph Use the diagram on the Object Graph slide to discuss the object graph concept and the algorithm that is used to serialize or deserialize an object graph
! Serialization Process Introduce the classes that are used in the serialization process
! Serialization Example Discuss the code example on the Serialization Example slide in which default serialization is performed on a graph of objects, whose root is an
ArrayList, and the serialized stream is written to a FileStream in binary
format
! Deserialization Example Use the preceding serialization example to show how to create a clone of the graph by deserializing it
! Custom Serialization Discuss when to use custom serialization and the implementation details of
using the ISerializable interface to perform custom serialization and
Trang 5***************************** ILLEGAL FOR NON - TRAINER USE ******************************
Serialization is the process of converting a graph of objects into a linear
sequence of bytes That sequence of bytes can be sent elsewhere, for example,
to a remote computer, and be deserialized, thereby making a clone in the remote memory of the original graph of objects
After completing this module, you will be able to:
• Write an application that serializes and deserializes an object graph by using either a binary or Simple Object Access Protocol (SOAP) XML format
In this module, you will learn
about serialization and learn
how to write an application
that serializes and
deserializes an object graph
by using a binary or SOAP
XML format
Trang 6***************************** ILLEGAL FOR NON - TRAINER USE ******************************
Serialization is used in some very common scenarios, such as persisting a graph
of objects to disk or to objects in another process The Microsoft® NET Framework provides support for serialization and deserialization
Persistence
Consider a simple single-user desktop application, such as a two-dimensional drafting package that is built by using object-oriented techniques In such an application, a drawing is composed of different kinds of graphical objects of various types The application represents the drawing as a graph of in-memory objects One object represents the root of the entire picture For example, a simple round table could be represented by a graph that consists of a root object that is an instance of a circle class This instance of the circle class has four children that are each instances of a line class
To save the entire drawing to a disk file so the drawing can be restored after rebooting the computer, you could force each class to implement a serialize and corresponding deserialize method However, this approach is a potentially burdensome task for the application programmer
Serialization in the NET Framework
The NET Framework common language runtime reduces the amount of work that is involved in serialization At run time, the common language runtime maintains metadata that allows serialization code to discover the types and values of all fields and properties that make up any object Using the common language runtime, an application requires only a few lines of code to serialize a object, such as the drawing described in the preceding paragraphs, and write it
to a file, or to deserialize such a file into an in-memory graph of objects
Topic Objective
To show how serialization is
used
Lead-in
Serialization is used in some
very common scenarios,
such as persisting a graph
of objects to disk or to
objects in another process
Trang 7Remoting
In distributed computing, objects in one process may need to communicate with
objects in another process In the NET Framework, the term remoting is
typically used to refer to the process in which an object invokes a method in another object that is not in the same application domain If the remote method takes as one of its arguments an object that lies at the root of a graph of objects, and if all of the objects in the graph are marked as remote-by-value, you must serialize a copy of the object graph and pass the graph to the remote object The remote object must then deserialize the argument into an in-memory graph of objects
For more information about remoting, see Module 13, “Remoting and Web
Services,” in Course 2349B, Programming with the Microsoft NET Framework (Microsoft Visual C# NET)
Trang 8Serialization Attributes
! To Mark a Class, Use Serializable Attribute
! To Skip Specified Members, Use NonSerialized Attribute
! To Provide Custom Serialization, Implement ISerializable
[Serializable] public class MyClass {}
[Serializable] public class MyClass {[NonSerialized] int _cashSize;
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
If you are writing a class, you should be aware of serialization The common language runtime’s serialization services are built with the assumption that a type is not serializable unless the type is specifically marked as serializable In the simplest case, all you need to do is mark a class as serializable because the runtime metadata understands everything about each object’s layout in memory, and its field and property definitions
To mark a type as serializable in C#, you use the Serializable attribute, which
is a reserved custom attribute All fields in classes with this attribute are serialized, even private fields
In the following example, MyClass is marked as serializable:
[Serializable] public class MyClass {}
For slightly more complex classes that have state that is invalid to serialize, the runtime provides support for marking those fields and properties as transient
For example, the following code uses the NonSerialized attribute to ensure that the _cashSize member of MyClass is not serialized:
[Serializable] public class MyClass {
[NonSerialized] int _cashSize;
//
} The small set of classes that need to participate in their own serialization and
deserialization can provide a custom implementation of the ISerializable
interface For more information about custom serialization, see Custom Serialization in this module
Topic Objective
To explain how to mark a
class with serialization
attributes in C#
Lead-in
If you are writing a class,
you should be aware of
serialization
Trang 92 9
1
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
An object graph is a set of objects with references to each other Serialization
must provide a way to represent the links between the graph’s objects in the serialized stream that is created in the serialization process
Understanding Object Graphs
Serialization of an object graph must provide a way to represent the links between the graph’s objects in the serialized stream that it creates The value that is held in the field of the in-memory object, which links to another object,
is essentially a 32-bit address This address has meaning only in the owner address space and may change during garbage collection Therefore, serialization must allocate a unique number to each object in the stream
The illustration in the slide shows a graph of animal objects Each object is represented as a box with its identification number inside the box and its class name to the right of the box
You can represent the graph of objects that is shown in this illustration with a serialized stream, as in the following example:
Dog, 3, ref4, ref7, ref1 || Cat, 4, ref9 || Duck, 7 || Mouse,
1, ref9, ref2 || Horse, 9, ref4 || Duck, 2 The order in which you stream out the objects does not matter, nor does it matter what numbers you assign to the objects What does matter is that no two objects are assigned the same number The object numbers are significant only within a serialized stream They are simply a way to represent the graph topology and to allow you to reconstruct a copy of that graph, perhaps on another computer
Topic Objective
To define an object graph
and explain its function
Lead-in
An object graph is a set of
objects that share a set of
references to each other
Trang 10Tracking Object References
An algorithm that visits objects one at a time clearly must keep track of which objects it has already visited, for example, by using an internal list Without due care, the algorithm may incorrectly serialize or deserialize an object graph For example, in the object graph in the illustration, to avoid entering an infinite loop, you must detect the cycle in the graph that occurs because of the mutual references between Cat 4 and Horse 9 During serialization, you must note that the Cat 4 that is linked to by Dog 3 is the same Cat 4 that is linked to by Horse
9 to ensure that deserialization will result in both Dog 3 and Horse 9 referring
to the same Cat 4 object and not to two different copies
Trang 11Serialization Process
! Classes Used by the Default Serialization Process
" ObjectIDGenerator – generates IDs for objects
" ObjectManager – tracks objects as they are being
deserialized
! Examples of Classes Used with Serialized Streams
" FileStream, MemoryStream, NetworkStream
! Formatter Class
" Writes or reads data in a specified format to the output
or input streams
" Runtime provides BinaryFormatter and SoapFormatter
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
The process of serializing an object graph involves identifying the individual objects in the graph and the relationships between them
Classes Used by the Default Serialization Process
To create and track object ID numbers, serialization uses several classes, as follows:
! ObjectIDGenerator
The ObjectIDGenerator class generates IDs for objects It keeps track of
objects that have already been seen, so when you ask for the ID of an object,
the ObjectIDGenerator knows whether to return the existing ID, or to
generate, and remember, a new ID
! ObjectManager
The ObjectManager class keeps track of objects as they are being
deserialized During deserialization, queries are made to the
ObjectManager to determine whether a reference to an object that is in the
serialized stream refers to an object that has already been deserialized or to
an object that has not yet been deserialized A reference to an object that has
already been deserialized is called a backward reference A reference to an object that has not yet been serialized is called a forward reference
Topic Objective
To introduce the classes
that are used in the
serialization process
Lead-in
The process of serializing
an object graph involves
identifying the individual
objects in the graph and the
relationships between them
Trang 12Both the ObjectIDGenerator and ObjectManager classes are pluggable, so
you can build your own alternatives
During deserialization, fields are returned in the order in which they are returned from reflection Reflection does not guarantee that it will follow metadata ordering
You can serialize to many different kinds of streams, for example, to a
FileStream, a MemoryStream, or a NetStream The serialized stream’s
format is determined by the formatter object that you instantiate
The NET Framework runtime provides the following formatter classes:
! BinaryFormatter
The BinaryFormatter class is used for a compact binary representation
! SoapFormatter
The SoapFormatter class is used for an XML representation
Because formatters are pluggable, you can also build your own formatters
Note
Trang 13Serialization Example
class SerializeExample{
public static void Main(String[] args) {
// create the object graphArrayList l = new ArrayList();
for (int x=0; x< 100; x++) {
l.Add (x);
}// create the filestreamFileStream s = File.Create("foo.bin");
// create the BinaryFormatterBinaryFormatter b = new BinaryFormatter();// serialize the graph to the stream
b.Serialize(s, l);
s.Close();
}}
class SerializeExample{
public static void Main(String[] args) {
// create the object graphArrayList l = new ArrayList();
for (int x=0; x< 100; x++) {
l.Add (x);
}// create the filestreamFileStream s = File.Create("foo.bin");
// create the BinaryFormatterBinaryFormatter b = new BinaryFormatter();// serialize the graph to the stream
b.Serialize(s, l);
s.Close();
}}
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
The following code sample shows how to perform default serialization of a
graph of objects, whose root is an ArrayList The serialized stream is written to
a FileStream in binary format
public static void Main(String[] args) {
// create the object graph ArrayList l = new ArrayList();
for (int x=0; x< 100; x++) {
} // create the filestream FileStream s = File.Create("foo.bin");
// create the BinaryFormatter BinaryFormatter b = new BinaryFormatter();
// serialize the graph to the stream b.Serialize(s, l);
s.Close();
} }
This code sample shows
how to perform default
serialization of a graph of
objects, whose root is an
ArrayList
Trang 14Deserialization Example
class DeSerialize{
public static void Main(String[] args) {
// open the filestreamFileStream s = File.OpenRead("foo.bin");// create the formatter
BinaryFormatter b = new BinaryFormatter(); // deserialize
ArrayList p = (ArrayList) b.Deserialize(s);s.Close();
// print out the new object graph// see module text for PrintValues’ codePrintValues(p);
}
class DeSerialize{
public static void Main(String[] args) {
// open the filestreamFileStream s = File.OpenRead("foo.bin");// create the formatter
BinaryFormatter b = new BinaryFormatter(); // deserialize
ArrayList p = (ArrayList) b.Deserialize(s);s.Close();
// print out the new object graph// see module text for PrintValues’ codePrintValues(p);
}
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
The preceding Serialization Example shows how to perform default
serialization of a graph of objects, whose root is an ArrayList, with a serialized stream that is written to a FileStream in binary format
The following code sample shows how to create a clone of the graph by
deserializing it The root of the clone graph is called p
public static void Main(String[] args) {
// open the filestream FileStream s = File.OpenRead("foo.bin");
// create the formatter BinaryFormatter b = new BinaryFormatter();
// deserialize ArrayList p = (ArrayList) b.Deserialize(s);
To show how to create a
clone of the graph by
deserializing it
Lead-in
The preceding Serialization
Example shows how to
perform default serialization
of a graph of objects, whose
root is an ArrayList, with a
serialized stream that is
written to a FileStream in
binary format
Trang 15public static void PrintValues( IEnumerable myList ) {
System.Collections.IEnumerator myEnumerator = myList.GetEnumerator();
while ( myEnumerator.MoveNext() ) Console.WriteLine( "{0}", myEnumerator.Current ); }
}
Trang 16Custom Serialization
! Customize Serialization by Implementing ISerializable:
" When some of the data is not valid after deserialization
" When some of the data must be obtained by calculation
! ISerializable Requires:
" GetObjectData method, called during serialization,
which returns a PropertyBag of type SerializationInfo
" PropertyBag, which contains the type of the object
being serialized and the name/object pairs for the values being serialized
" A constructor, called during deserialization, which uses
SerializationInfo to reconstitute the state of the object
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
This module has so far discussed the default serialization process However, you may also want to customize the way that data from a given object is serialized
Custom serialization can be useful when some of the data that is associated with
an object is no longer valid after deserialization You may want to use custom serialization when working with pointers or hashcodes, or when you want to create data through calculations or other means that allow you to reconstruct the full state of the object during deserialization
To perform custom serialization, you should implement the ISerializable
interface on the given object
Implementation Details Required by ISerializable
To implement the ISerializable interface, you implement the GetObjectData method on your object and add a constructor that takes a SerializationInfo and
a StreamingContext, as shown in Custom Serialization Example in this
module
When GetObjectData is called during serialization, you are responsible for populating a SerializationInfo object A SerializationInfo object is a
PropertyBag that contains the type of the object that is being serialized and the
name/object pairs for the values that are being serialized
The Formatter emits the data out onto the wire in the method required by its
particular format You are free to serialize as few or as many fields as you want, but the data that is transmitted must be sufficient to reconstitute the entire state
of the object If the base object of the current class implements ISerializable, it
is usually correct to call the base object’s ISerializable.GetObjectData and
add any additional fields that are required for serializing the derived class to the
This module has so far
discussed the default
serialization process
However, you may also
want to customize the way
data from a given object is
serialized