Você está na página 1de 7

Chapitre 1- Introduction aux technologies J2EE

70-536 Chapitre 5

Plan

„ Lesson 1 : Serializing objects


.NET Framework 2.0
Application Development
Foundation
„ Lesson 2 : XML Serialization
Chapitre 5
„ Lesson 3 : Custom Serialization

Serialization

Mohamed Romdhani
INSAT, Octobre 2007 2
M. Romdhani, Octobre 2007

70-536 Chapitre 5 70-536 Chapitre 5

What is serialization ?

„ Serialization, as implemented in the System.Runtime.Serialization


namespace, is the process of serializing and deserializing objects so
that they can be stored or transferred and then later re-created.
„ Serializing is the process of converting an object into a linear sequence
of bytes that can be stored or transferred.
„ Deserializing is the process of converting a previously serialized
sequence of bytes into an object.
Lesson 1 : Serializing objects

M. Romdhani, Octobre 2007 3 M. Romdhani, Octobre 2007 4

70-536 Chapitre 5 70-536 Chapitre 5

How to serialize an object ? How to deserialize an object ?


„ At a high level, the steps for serializing an object are as follows: „ Deserializing an object allows you to create a new object based on stored data.
Essentially, deserializing restores a saved object. At a high level, the steps for
1. Create a stream object to hold the serialized output. deserializing an object are as follows:
2. Create a BinaryFormatter object (located in 1. Create a stream object to read the serialized output.
System.Runtime.Serialization.Formatters.Binary).
3. Call the BinaryFormatter.Serialize method to serialize the object, and output the result to 2. Create a BinaryFormatter object.
the stream. 3. Create a new object to store the deserialized data.
4. Call the BinaryFormatter.Deserialize method to deserialize the object, and cast it
„ At the development level, serialization can be implemented with very little code. to the correct type.
„ The following console application which requires the System.IO,
System.Runtime.Serialization, and System.Runtime.Serialization.Formatters.Binary „ At the code level, the steps for deserializing an object are easy to implement.
namespaces demonstrates this: The following console application which requires the System.IO,
string data = "This must be stored in a file."; System.Runtime.Serialization, and
// Create file to save the data to
System.Runtime.Serialization.Formatters.Binary namespaces—demonstrates
how to read and display the serialized string data saved in an earlier example:
FileStream fs = new FileStream("SerializedString.Data", FileMode.Create);
// Open file to read the data from
// Create a BinaryFormatter object to perform the serialization
FileStream fs = new FileStream("SerializedString.Data", FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
// Use the BinaryFormatter object to serialize the data to the file
// Create a BinaryFormatter object to perform the deserialization
bf.Serialize(fs, data); BinaryFormatter bf = new BinaryFormatter();
// Close the file // Create the object to store the deserialized data
fs.Close(); string data = "";
„ If you just needed to store a single string in a file, you wouldn’t need to use // Use the BinaryFormatter object to deserialize the data from the file
serialization you could simply write the string directly to a text file. Serialization data = (string) bf.Deserialize(fs);
becomes useful when storing more complex information, such as the current fs.Close(); // Close the file
date and time. Console.WriteLine(data); // Display the deserialized string
M. Romdhani, Octobre 2007 5 M. Romdhani, Octobre 2007 6

1
Chapitre 1- Introduction aux technologies J2EE

70-536 Chapitre 5 70-536 Chapitre 5


How to create classes that can be How to create classes that can be
serialized ? serialized ?
„ To enable your class to automatically initialize a nonserialized member,
„ You can serialize and deserialize custom classes by adding the Serializable attribute to the use the IDeserializationCallback interface, and then implement
class.
„ NOTE : Security concerns with serialization
IDeserializationCallback .OnDeserialization.
Serialization can allow other code to see or modify object instance data that would otherwise „ Each time your class is deserialized, the runtime will call the
be inaccessible. Therefore, code performing serialization requires the SecurityPermission IDeserializationCallback.OnDeserialization method after deserialization
attribute (from the System.Security.Permissions namespace) with the SerializationFormatter is complete.
flag specified. Under default policy, this permission is not given to Internet-downloaded or
intranet code; only code on the local computer is granted this permission. [Serializable]
class ShoppingCartItem : IDeserializationCallback {
„ You can also control serialization of your classes to improve the efficiency of your class or public int productId;
to meet custom requirements.
„ How to Disable Serialization of Specific Members public decimal price;
[Serializable] public int quantity;
class ShoppingCartItem { [NonSerialized] public decimal total;
public int productId;
public ShoppingCartItem(int _productID, decimal _price, int _quantity) {
public decimal price;
public int quantity; productId = _productID;
[NonSerialized] public decimal total; price = _price;quantity = _quantity;
public ShoppingCartItem(int _productID, decimal _price, int _quantity) { total = price * quantity;
productId = _productID;
}
price = _price;
quantity = _quantity; void IDeserializationCallback.OnDeserialization(Object sender) {
total = price * quantity; // After deserialization, calculate the total
} total = price * quantity;
}
}
}
M. Romdhani, Octobre 2007 7 M. Romdhani, Octobre 2007 8

70-536 Chapitre 5 70-536 Chapitre 5

How to Provide Version Compatibility ? Choosing a serialization format


„ You might have version compatibility issues if you ever attempt to deserialize
an object that has been serialized by an earlier version of your application. „ The .NET Framework includes two methods for formatting serialized data in the
System .Runtime.Serialization namespace, both of which implement the
„ Specifically, if you add a member to a custom class and attempt to deserialize IRemotingFormatter interface:
an object that lacks that member, the runtime will throw an exception.
1. BinaryFormatter Located in the
„ To overcome this limitation, you have two choices: System.Runtime.Serialization.Formatters.Binary namespace, this formatter is
1. Implement custom serialization, as described in Lesson 3, that is capable of importing the most efficient way to serialize objects that will be read by only .NET
earlier serialized objects. Framework–based applications.
2. Apply the OptionalField attribute to newly added members that might cause version 2. SoapFormatter Located in the System.Runtime.Serialization.Formatters.Soap
compatibility problems. namespace, this XML-based formatter is the most reliable way to serialize
„ The OptionalField attribute does not affect the serialization process. During objects that will be transmitted across a network or read by non–.NET
deserialization, if the member was not serialized, the runtime will leave the Framework applications. SoapFormatter is more likely to successfully traverse
member’s value as null rather than throwing an exception. firewalls than BinaryFormatter.
[Serializable]
class ShoppingCartItem : IDeserializationCallback { „ BinaryFormatter or SoapFormatter
public int productId; „ You should choose BinaryFormatter only when you know that all clients
public decimal price; opening the serialized data will be .NET Framework applications.
Therefore, if you are writing objects to the disk to be read later by your
public int quantity; application, BinaryFormatter is perfect.
[NonSerialized] public decimal total;
„ Use SoapFormatter when other applications might read your serialized
[OptionalField] public bool taxable; data and when sending data across a network. SoapFormatter also works
„ If you need to initialize optional members, either implement the IDeserialization reliably in situations where you could choose BinaryFormatter, but the
Callback interface as described in the “How to Disable Serialization of Specific serialized object can consume three to four times more space.
Members” section earlier in this lesson, or respond to serialization events, as
described in Lesson 3.
M. Romdhani, Octobre 2007 9 M. Romdhani, Octobre 2007 10

70-536 Chapitre 5 70-536 Chapitre 5

How to Use SoapFormatter How to Control SOAP Serialization


„ To use SoapFormatter, add a reference to the
System.Runtime.Serialization.Formatters.Soap.dll assembly to your „ You can control the formatting of a SOAP serialized document by using
project. Then write code exactly as you would to use BinaryFormatter, the attributes listed below:
but substitute the SoapFormatter class for the BinaryFormatter class. „ Attribute Applies to
„ SoapAttribute Public field, property,
„ While writing code for BinaryFormatter and SoapFormatter is very
similar, the serialized data is very different. The following example is a parameter, or return value
three-member object serialized with SoapFormatter that has been „ SoapElement Public field, property,
slightly edited for readability:
parameter, or return value
<SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SOAP-ENV:Body> „ SoapEnum Public field that is an
<a1:ShoppingCartItem id="ref-1"> enumeration identifier
<productId>100</productId>
„ SoapIgnore Public properties and fields
<price>10.25</price>
<quantity>2</quantity> „ SoapInclude Public derived class declarations and public methods
</a1:ShoppingCartItem> for Web Services Description
</SOAP-ENV:Body> Language (WSDL) documents
</SOAP-ENV:Envelope>
„ NOTE .NET 2.0 „ SOAP serialization attributes function similarly to XML serialization
SoapFormatter does not support serialization compatibility between versions of the attributes.
.NET Framework. Serialization between versions 1.1 and 2.0 types in the Framework
often fails. BinaryFormatter does provide compatibility between versions.
M. Romdhani, Octobre 2007 11 M. Romdhani, Octobre 2007 12

2
Chapitre 1- Introduction aux technologies J2EE

70-536 Chapitre 5 70-536 Chapitre 5

Guidelines for Serialization Lesson Summary


„ Serialization is the process of converting information into a byte
„ Keep the following guidelines in mind when using serialization: stream that can be stored or transferred.
„ When in doubt, mark a class as Serializable. Even if you do not need to „ To serialize an object, first create a stream object. Then create a
serialize it now, you might need serialization later. Or another developer BinaryFormatter object and call the BinaryFormatter.Serialize method. To
might need to serialize a derived class. deserialize an object, follow the same steps but call the
BinaryFormatter.Deserialize method.
„ Mark calculated or temporary members as NonSerialized. For example,
if you track the current thread ID in a member variable, the thread ID is „ To create a class that can be serialized, add the Serializable attribute. You
likely to not be valid upon deserialization. Therefore, you should not can also use attributes to disable serialization of specific members.
store it.
„ Use SoapFormatter when you require portability. Use „ SoapFormatter provides a less efficient, but more interoperable,
BinaryFormatter for greatest efficiency. alternative to the BinaryFormatter class.
„ To use SoapFormatter, follow the same process as you would for
BinaryFormatter, but use the
System.Runtime.Serialization.Formatters.Soap.SoapFormatter class.
„ You can control SoapFormatter serialization by using attributes to specify
the names of serialized elements and to specify whether a member is
serialized as an element or an attribute.

„ It is a good practice to make all classes serializable even if you do not


immediately require serialization. You should disable serialization for
calculated and temporary members.

M. Romdhani, Octobre 2007 13 M. Romdhani, Octobre 2007 14

70-536 Chapitre 5 70-536 Chapitre 5

Why Use XML Serialization?

„ Use XML serialization when you need to exchange an object with an


application that might not be based on the .NET Framework, and you
do not need to serialize any private members. XML serialization
provides the following benefits over standard serialization:
„ Greater interoperability
„ More administrator-friendly
Lesson 2 : XML Serialization „ Better forward-compatibility

„ Specifically, XML serialization has the following limitations:


„ XML serialization can serialize only public data. You cannot serialize
private data.
„ You cannot serialize object graphs; you can use XML serialization only
on objects.

M. Romdhani, Octobre 2007 15 M. Romdhani, Octobre 2007 16

70-536 Chapitre 5 70-536 Chapitre 5

How to Use XML to Serialize an Object How to Use XML to Deserialize an Object

„ At a high level, the steps for serializing an object are as follows: „ To deserialize an object, follow these steps:
1. Create a stream, TextWriter, or XmlWriter object to hold the serialized output. 1. Create a stream, TextReader, or XmlReader object to read the serialized input.
2. Create an XmlSerializer object (in the System.Xml.Serialization namespace) by 2. Create an XmlSerializer object (in the System.Xml.Serialization namespace) by
passing it the type of object you plan to serialize. passing it the type of object you plan to deserialize.
3. Call the XmlSerializer.Serialize method to serialize the object and output the 3. Call the XmlSerializer.Deserialize method to deserialize the object, and cast it to
results to the stream. the correct type.

„ At the code level, these steps are similar to standard serialization. The „ The following code sample deserializes an XML file containing a
following console applicatio which requires using System.IO and DateTime object and displays that object’s day of the week and time
System.Xml.Serialization namespace demonstrates the simplicity:
FileStream fs = new FileStream("SerializedDate.XML", FileMode.Open);
// Create file to save the data to
// Create an XmlSerializer object to perform the deserialization
FileStream fs = new FileStream("SerializedDate.XML", FileMode.Create);
XmlSerializer xs = new XmlSerializer(typeof(DateTime));
// Create an XmlSerializer object to perform the serialization
XmlSerializer xs = new XmlSerializer(typeof(DateTime)); // Use the XmlSerializer object to deserialize the data from the file
// Use the XmlSerializer object to serialize the data to the file DateTime previousTime = (DateTime)xs.Deserialize(fs);
xs.Serialize(fs, System.DateTime.Now); fs.Close(); // Close the file
fs.Close(); // Close the file // Display the deserialized time
„ When run, the application produces a text file similar to the following: Console.WriteLine("Day: " + previousTime.DayOfWeek + ",
<?xml version="1.0" ?> Time: " + previousTime.TimeOfDay.ToString());
<dateTime>2005-12-05T16:28:11.0533408-05:00</dateTime>

M. Romdhani, Octobre 2007 17 M. Romdhani, Octobre 2007 18

3
Chapitre 1- Introduction aux technologies J2EE

70-536 Chapitre 5 70-536 Chapitre 5


How to Create Classes that Can Be
Serialized by Using XML Serialization
How to Control XML Serialization

„ To create a class that can be serialized by using XML serialization, you „ If you serialize a class that meets the requirements for XML
must perform the following tasks: serialization but does not have any XML serialization attributes, the
runtime uses default settings that meet many people’s requirements.
„ Specify the class as public.
„ Consider the following simple class:
„ Specify all members that must be serialized as public. public class ShoppingCartItem {
„ Create a parameterless constructor. public Int32 productId;
public decimal price;
„ Unlike classes processed with standard serialization, classes do not private Int32 quantity;
have to have the Serializable attribute to be processed with XML public decimal total;
serialization. public ShoppingCartItem(){}
„ If there are private or protected members, they will be skipped during }
serialization. „ Serializing an instance of this class with sample values creates the
following XML :
<?xml version="1.0" ?>
<ShoppingCartItem>
<productId>100</productId>
<price>10.25</price>
<total>20.50</total>
</ShoppingCartItem>

M. Romdhani, Octobre 2007 19 M. Romdhani, Octobre 2007 20

70-536 Chapitre 5 70-536 Chapitre 5

How to Control XML Serialization How to Control XML Serialization


„ If you need to create XML documents that conform to specific standards, you
might need to control how the serialization is structured. You can do this using „ Consider the attributes required to make the following three changes to
the attributes listed below: the serialized XML document:
„ XmlAnyAttribute : When deserializing, the array will be filled with XmlAttribute objects that „ Change the ShoppingCartItem element name to CartItem.
represent all XML attributes unknown to the schema.
„ Make productId an attribute of CartItem, rather than a separate element.
„ XmlAnyElement : When deserializing, the array is filled with XmlElement objects that
represent all XML elements unknown to the schema. „ Do not include the total in the serialized document.
„ XmlArrays : The members of the array will be generated as members of an XML array.
„ XmlArrayItem :The derived types that can be inserted into an array. Usually applied in „ To make these changes, modify the class with attributes as shown:
conjunction with XmlArrayAttribute.
[XmlRoot ("CartItem")]
„ XmlAttribute : The member will be serialized as an XML attribute. public class ShoppingCartItem {
„ XmlChoiceIdentifier : The member can be further disambiguated by using an enumeration. [XmlAttribute] public Int32 productId;
„ XmlElement : The field or property will be serialized as an XML element. public decimal price;
„ XmlEnum : The element name of an enumeration member public Int32 quantity;
„ XmlIgnore : The property or field should be ignored when the containing class is serialized. [XmlIgnore] public decimal total;
This functions similarly to the NonSerialized standard serialization attribute. public ShoppingCartItem(){}
„ XmlInclude :The class should be included when generating schemas (to be recognized }
when serialized).
„ This would result in the following XML file, which meets the specified requirements:
„ XmlRoot : Controls XML serialization of the attribute target as an XML root element. Use the
attribute to further specify the namespace and element name. <?xml version="1.0" ?>
„ XmlText : The property or field should be serialized as XML text. <CartItem productId="100">
„ XmlType :The name and namespace of the XML type. <price>10.25</price>
<quantity>2</quantity>
</CartItem>
M. Romdhani, Octobre 2007 21 M. Romdhani, Octobre 2007 22

70-536 Chapitre 5 70-536 Chapitre 5

How to Control XML Serialization How to Conform to an XML Schema

„ Although attributes will enable you to meet most XML serialization „ An XML schema defines the structure of an XML document.
requirements, you can take complete control over XML serialization by
implementing the IXmlSerializable interface in your class. „ If you have an XML schema, you can run the XML Schema Definition
tool (Xsd.exe) to produce a set of classes that are strongly typed to the
„ For example, you can separate data into bytes instead of buffering schema and annotated with attributes.
large data sets, and also avoid the inflation that occurs when the data „ When an instance of such a class is serialized, the generated XML
is encoded using Base64 encoding. adheres to the XML schema.
„ To control the serialization, implement the ReadXml and WriteXml „ This is a simpler alternative to using other classes in the .NET
methods to control the XmlReader and XmlWriter classes used to read Framework, such as the XmlReader and XmlWriter classes, to parse
and write the XML. and write an XML stream.

„ To generate a class based on a schema, follow these steps:


1. Create or download the XML schema .xsd file on your computer.
2. Open a Visual Studio 2005 Command Prompt.
3. From the Visual Studio 2005 Command Prompt, run Xsd.exe
schema.xsd /classes /language:CS
4. Open the newly created file (named Schema.CS or Schema.VB), and
add the class to your application.

M. Romdhani, Octobre 2007 23 M. Romdhani, Octobre 2007 24

4
Chapitre 1- Introduction aux technologies J2EE

70-536 Chapitre 5 70-536 Chapitre 5

How to serialize a DataSet Lesson Summary


„ Besides serializing an instance of a public class, an instance of a DataSet
object can also be serialized, as shown in the following example: „ XML serialization provides the interoperability to communicate with different
private void SerializeDataSet(string filename){ platforms and the flexibility to conform to an XML schema.
XmlSerializer ser = new XmlSerializer(typeof(DataSet)); „ XML serialization cannot be used to serialize private data or object graphs.
// Creates a DataSet; adds a table, column, and ten rows.
DataSet ds = new DataSet("myDataSet"); „ To serialize an object, first create a stream, TextWriter, or XmlWriter. Then
DataTable t = new DataTable("table1"); create an XmlSerializer object and call the XmlSerializer.Serialize method.
DataColumn c = new DataColumn("thing"); „ To deserialize an object, follow the same steps but call the
t.Columns.Add(c);ds.Tables.Add(t); XmlSerializer.Deserialize method.
DataRow r;
for(int i = 0; i<10;i++){ r = t.NewRow(); „ To create a class that can be serialized, specify the class and all members as
r[0] = "Thing " + i; public, and create a parameterless constructor.
t.Rows.Add(r); }
TextWriter writer = new StreamWriter(filename); „ You can control XML serialization by using attributes. Attributes can change the
ser.Serialize(writer, ds); names of elements, serialize members as attributes rather than elements, and
writer.Close(); exclude members from serialization.
}
„ Use the Xsd.exe tool to create a class that will automatically conform to an XML
„ Similarly, you can serialize arrays, collections, and instances of an XmlElement schema when serialized.
or XmlNode class.
„ Although this is useful, it does not provide the same level of control that you „ Datasets, arrays, collections, and instances of an XmlElement or XmlNode class
would have if the data were stored in custom classes. can all be serialized with XmlSerializer.
„ Alternatively, you could use the DataSet.WriteXml, DataSet.ReadXML, and
DataSet.GetXml methods.
M. Romdhani, Octobre 2007 25 M. Romdhani, Octobre 2007 26

70-536 Chapitre 5 70-536 Chapitre 5

How to Implement Custom Serialization

„ Serialization in the .NET Framework is very flexible and can be customized to


meet most development requirements.
„ In some circumstances, you might need complete control over the serialization
process.
„ This is particularly useful in cases where the value of a member variable is invalid after
deserialization, but you need to provide the variable with a value to reconstruct the full
state of the object.
„ In addition, you should not use default serialization on a class that is marked with the
Lesson 3 : Custom Serialization Serializable attribute and has declarative or imperative security at the class level or on
its constructors. Instead, these classes should always implement the ISerializable
interface.

„ Implementing ISerializable involves implementing the GetObjectData method


and a special constructor that is used when the object is deserialized.
„ The runtime calls GetObjectData during serialization, and the serialization
constructor during deserialization.

„ When the runtime calls GetObjectData during serialization, you are responsible
for populating the SerializationInfo object provided with the method call.
„ Simply add the variables to be serialized as name/value pairs using the AddValue
method, which internally creates SerializationEntry structures to store the information.
„ Any text can be used as the name. You have the freedom to decide which member
variables are added to the SerializationInfo object, provided that sufficient data is
serialized to restore the object during deserialization.
„ When the runtime calls your serialization constructor, simply retrieve the values of the
M. Romdhani, Octobre 2007 27 variables from SerializationInfo using the names used during serialization.
M. Romdhani, Octobre 2007 28

70-536 Chapitre 5 70-536 Chapitre 5

How to Implement Custom Serialization Responding to Serialization Events


„ The following sample code, which uses the System.Runtime.Serialization
and System.Security.Permissions namespaces, shows how to implement „ The .NET Framework 2.0 supports binary serialization events when
ISerializable, the serialization constructor, and the GetObjectData method: using the Binary Formatter class. These events call methods in your
[Serializable] class when serialization and deserialization take place. There are four
class ShoppingCartItem : ISerializable { serialization events:
public Int32 productId; public decimal price; public Int32 quantity;
[NonSerialized] public decimal total; „ Serializing
// The standard, non-serialization constructor „ This event is raised just before serialization takes place. Apply the
public ShoppingCartItem(int _productID, decimal _price, int _quantity) { OnSerializing attribute to the method that should run during this event.
productId = _productID; price = _price;quantity = _quantity; total = price * quantity;}
// The following constructor is for deserialization „ Serialized
protected ShoppingCartItem(SerializationInfo info,StreamingContext context){ „ This event is raised just after serialization takes place. Apply the
productId = info.GetInt32("Product ID"); OnSerialized attribute to the method that should run during this event.
price = info.GetDecimal("Price");
quantity = info.GetInt32("Quantity"); „ Deserializing
total = price * quantity; } „ This event is raised just before deserialization takes place. Apply the
// The following method is called during serialization OnDeserialized attribute to the method that should run during this event.
[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter=true)]
public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { „ Deserialized
info.AddValue("Product ID", productId); „ This event is raised just after deserialization takes place and after
info.AddValue("Price", price);info.AddValue("Quantity", quantity);} IDeserializationCallback.OnDeserialization has been called. You should use
public override string ToString(){return productId + ": " + price + " x " + quantity + " = " + total;} IDeserializationCallback.OnDeserialization instead when formatters other
} than BinaryFormatter might be used. Apply the OnDeserializing attribute to
the method that should run during this event.
„ In this example, SerializationInfo does much of the work of serialization and deserialization. The
construction of a SerializationInfo object requires an object whose type implements the
IFormatterConverter interface.
M. Romdhani, Octobre 2007 29 M. Romdhani, Octobre 2007 30

5
Chapitre 1- Introduction aux technologies J2EE

70-536 Chapitre 5 70-536 Chapitre 5

Responding to Serialization Events Responding to Serialization Events


„ The sequence of these events is „ The following example demonstrates how to create an object that responds to
serialization events.
illustrated in the Figure :
„ In your own code, you can respond to as many or as few events as you want.
„ Additionally, you can apply the same serialization event to multiple methods, or apply
multiple events to a single method.

[Serializable]
„ Using these events is the best and easiest
way to control the serialization process. class ShoppingCartItem {
public Int32 productId;
„ The methods do not access the public decimal price;
serialization stream but instead allow public Int32 quantity;
you to alter the object before and after public decimal total;
serialization, or before and after [OnSerializing]
deserialization. void CalculateTotal(StreamingContext sc) {
total = price * quantity;
„ For a method to respond to one of these }
events, it must meet these requirements: [OnDeserialized]
void CheckTotal(StreamingContext sc) {
„ Accept a StreamingContext object as a if (total == 0) { CalculateTotal(sc); }
parameter }
„ Return void }

„ Have the attribute that matches the „ Events are supported only for BinaryFormatter serialization
event you want to intercept
„ For SoapFormatter or custom serialization, you are limited to using the
IDeserializationCallback interface, as discussed in Lesson 1 of this chapter.

M. Romdhani, Octobre 2007 31 M. Romdhani, Octobre 2007 32

70-536 Chapitre 5 70-536 Chapitre 5


How to Change Serialization Based on
Context
„ Typically, when you serialize an object, the destination does not matter. „ To make context decisions during serialization and deserialization,
„ In some circumstances,however, you might want to serialize and deserialize an implement the ISerialization interface in your class.
object differently depending on the destination. „ For serialization, inspect the StreamingContext structure passed to your
„ For example, you should typically not serialize members that contain information object’s GetObjectData method.
about the current process, because that information might be invalid when the
object is deserialized. However, that information would be useful if the object is „ For deserialization, inspect the StreamingContext structure passed to
going to be deserialized by the same process. your object’s serialization constructor.
„ Alternatively, if the object is useful only if deserialized by the same process, you
might choose to throw an exception if you knew the destination was a different „ If you are serializing or deserializing an object and want to provide
process. context information, modify the IFormatter.Context StreamingContext
property before calling the formatter’s Serialize or Deserialize methods.
„ The StreamingContext structure can provide information about the destination
of a serialized object to classes that implement the ISerializable interface. „ This property is implemented by both the BinaryFormatter and
StreamingContext is passed to both GetObjectData and an object’s serialization SoapFormatter classes. When you construct a formatter, the formatter
constructor. automatically sets the Context property to null and the State property to
„ The Streaming Context structure has two properties:
All.
1. Context A reference to an object that contains any user-desired context
information.
2. State A set of bit flags indicating the source or destination of the objects being
serialized/deserialized. The flags are: CrossProcess, CrossMachine, File,
Persistence, Remoting, Other, Close, CrossAppDomain, all.

M. Romdhani, Octobre 2007 33 M. Romdhani, Octobre 2007 34

70-536 Chapitre 5 70-536 Chapitre 5

How to Create a Custom Formatter Lesson Summary

„ To create a custom formatter, implement the IFormatter or „ You can implement ISerialization to perform custom serialization.
IGenericFormatter interface.
„ Both BinaryFormatter and SoapFormatter implement the IFormatter „ BinaryFormatter provides four events that you can use to control parts
interface. The FormatterServices class provides static methods of the serialization process:
(including GetObjectData) to aid with theimplementation of a formatter. „ OnSerializing, OnSerialized, OnDeserializing, and OnDeserialized.
„ NOTE .NET 2.0 : Although IFormatter was available beginning with
.NET 1.1, IGenericFormatter is new with .NET 2.0. „ The StreamingContext class, an instance of which is provided to
methods called during serialization events, gives you information
about the origin or planned destination of the serialization process.
„ The method performing serialization must specify this information for it
to be useful.

„ Though few developers will require total control over serialization, you
can implement the IFormatter or IGenericFormatter interfaces to create
custom formatters.

M. Romdhani, Octobre 2007 35 M. Romdhani, Octobre 2007 36

6
Chapitre 1- Introduction aux technologies J2EE

70-536 Chapitre 5

Chapter Summary

„ Serialization outputs an object as a series of bytes, whereas


deserialization reads a serialized object and defines the value of an
object.
„ Most custom classes can be serialized by simply adding the Serializable
attribute. In some cases, you might be able to improve efficiency or
provide for changes to the structure of classes by modifying your class
to change the default serialization behavior.

„ XML serialization provides a way to store and transfer objects using


open standards.
„ XML serialization can be customized to fit the exact requirements of an
XML schema, making it simple to convert objects into XML documents
and back into objects.

„ Custom serialization is required in situations where classes contain


complex information, significant changes have occurred to the
structure of a class between different versions, and where you need
complete control over how information is stored.
„ You can perform custom serialization by implementing the ISerializable
interface or by responding to serialization events.

M. Romdhani, Octobre 2007 37

Você também pode gostar