Presentation is loading. Please wait.

Presentation is loading. Please wait.

Serialization.

Similar presentations


Presentation on theme: "Serialization."— Presentation transcript:

1 Serialization

2 Parts: 1) Serializing Objects 2) XML Serialization
3) Custom Serialization

3 Serializing Objects

4 How to Serialize an Object
1. Create a stream object to hold the serialized output. 2. Create a BinaryFormatter object (located in System.Runtime.Serialization.Formatters.Binary). 3. Call the BinaryFormatter.Serialize method to serialize the object, and output the result to the stream.

5 string data = "This must be stored in a file.";
// Create file to save the data to FileStream fs = newFileStream("SerializedString.Data", FileMode.Create); // Create a BinaryFormatter object to perform the serialization BinaryFormatter bf = new BinaryFormatter(); // Use the BinaryFormatter object to serialize the data to the file bf.Serialize(fs, data); // Close the file fs.Close();

6

7 // Create file to save the data to
FileStream fs = new FileStream("SerializedDate.Data", FileMode.Create); // Create a BinaryFormatter object to perform the serialization BinaryFormatter bf = new BinaryFormatter(); // Use the BinaryFormatter object to serialize the data to the file bf.Serialize(fs, System.DateTime.Now); // Close the file fs.Close();

8 How to Deserialize an Object
1. Create a stream object to read the serialized output. 2. Create a BinaryFormatter object. 3. Create a new object to store the deserialized data. 4. Call the BinaryFormatter.Deserialize method to deserialize the object, and cast it to the correct type.

9 // Open file to read the data from
FileStream fs = new FileStream("SerializedDate.Data", FileMode.Open); // Create a BinaryFormatter object to perform the deserialization BinaryFormatter bf = new BinaryFormatter(); // Create the object to store the deserialized data DateTime previousTime = new DateTime(); // Use the BinaryFormatter object to deserialize the data from the file previousTime = (DateTime) bf.Deserialize(fs); // Close the file fs.Close(); // Display the deserialized time Console.WriteLine("Day: " + previousTime.DayOfWeek ", _Time: " + previousTime.TimeOfDay.ToString());

10 How to Create Classes That Can Be Serialized
[Serializable] class ShoppingCartItem { public int productId; public decimal price; public int quantity; public decimal total; public ShoppingCartItem(int _productID, decimal _price, int _quantity) productId = _productID; price = _price; quantity = _quantity; total = price * quantity; }

11 How to Disable Serialization of Specific Members
[Serializable] class ShoppingCartItem : IDeserializationCallback { // … [NonSerialized] public decimal total; // … void IDeserializationCallback.OnDeserialization(Object sender) // After deserialization, calculate the total total = price * quantity; }

12 Choosing a Serialization Format
■ BinaryFormatter Located in the System.Runtime.Serialization.Formatters.Binary namespace, this formatter is the most efficient way to serialize objects that will be read by only .NET Framework based applications. ■ SoapFormatter Located in the System.Runtime.Serialization.Formatters.Soap namespace, this XML-based formatter is the most reliable way to serialize objects that will be transmitted across a network or read by non–.NET Framework applications. SoapFormatter is more likely to successfully traverse firewalls than BinaryFormatter.

13 Use SoapFormatter <SOAP-ENV:Envelope xmlns:xsi=" <SOAP-ENV:Body> <a1:ShoppingCartItem id="ref-1"> <productId>100</productId> <price>10.25</price> <quantity>2</quantity> </a1:ShoppingCartItem> </SOAP-ENV:Body> </SOAP-ENV:Envelope>

14 Guidelines for Serialization
■ When in doubt, mark a class as Serializable. Even if you do not need to serialize it now, you might need serialization later. Or another developer might need to serialize a derived class. ■ Mark calculated or temporary members as NonSerialized. For example, if you track the current thread ID in a member variable, the thread ID is likely to not be valid upon deserialization. Therefore, you should not store it. ■ Use SoapFormatter when you require portability. Use BinaryFormatter for greatest efficiency.

15 Summary ■ Serialization is the process of converting information into a byte stream that can be stored or transferred. ■ To serialize an object, first create a stream object. Then create a BinaryFormatter object and call the BinaryFormatter.Serialize method. To deserialize an object, follow the same steps but call the BinaryFormatter.Deserialize method. ■ To create a class that can be serialized, add the Serializable attribute. You can also use attributes to disable serialization of specific members. ■ SoapFormatter provides a less efficient, but more interoperable, 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.

16 XML Serialization

17 Why Use XML Serialization?
■ Greater interoperability ■ More administrator-friendly ■ Better forward-compatibility

18 How to Use XML to Serialize an Object
// Create file to save the data to FileStream fs = new FileStream("SerializedDate.XML", FileMode.Create); // Create an XmlSerializer object to perform the serialization XmlSerializer xs = new XmlSerializer(typeof(DateTime)); // Use the XmlSerializer object to serialize the data to the file xs.Serialize(fs, System.DateTime.Now); // Close the file fs.Close(); //<?xml version="1.0" ?> //<dateTime> T16:28: :00</dateTime>

19 How to Create Classes that Can Be Serialized by Using XML Serialization
■ Specify the class as public. ■ Specify all members that must be serialized as public. ■ Create a parameterless constructor.

20 <?xml version="1.0" ?> <ShoppingCartItem> <productId>100</productId> <price>10.25</price> <total>20.50</total> </ShoppingCartItem>

21 How to Control XML Serialization
[XmlRoot ("CartItem")] public class ShoppingCartItem { [XmlAttribute] public Int32 productId; public decimal price; public Int32 quantity; [XmlIgnore] public decimal total; public ShoppingCartItem() }

22 <?xml version="1.0" ?> <CartItem productId="100"> <price>10.25</price> <quantity>2</quantity> </CartItem>

23 How to Conform to an XML Schema
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 For example, to create a new class based on a schema file named: C:\schema\library.xsd You would run the following command: xsd C:\schema\library.xsd /classes /language:CS 4. Open the newly created file (named Schema.CS), and add the class to your application.

24 XML Schema Part 0: Primer
Using Schema and Serialization to Leverage Business Logic

25 Summary ■ XML serialization provides the interoperability to communicate with different platforms and the flexibility to conform to an XML schema. ■ XML serialization cannot be used to serialize private data or object graphs. ■ To serialize an object, first create a stream, TextWriter, or XmlWriter. Then create an XmlSerializer object and call the XmlSerializer.Serialize method. To deserialize an object, follow the same steps but call the XmlSerializer.Deserialize method. ■ To create a class that can be serialized, specify the class and all members as public, and create a parameterless constructor. ■ You can control XML serialization by using attributes. Attributes can change the names of elements, serialize members as attributes rather than elements, and exclude members from serialization. ■ Use the Xsd.exe tool to create a class that will automatically conform to an XML schema when serialized. ■ Datasets, arrays, collections, and instances of an XmlElement or XmlNode class can all be serialized with XmlSerializer.

26 Custom Serialization

27 How to Provide Version Compatibility
■ Implement custom serialization, that is capable of importing earlier serialized objects. ■ Apply the OptionalField attribute to newly added members that might cause version compatibility problems.

28 // C# [Serializable] class ShoppingCartItem : IDeserializationCallback { public int productId; public decimal price; public int quantity; [NonSerialized] public decimal total; [OptionalField] public bool taxable; //…

29 [Serializable] class ShoppingCartItem : ISerializable { //… // The following constructor is for deserialization protected ShoppingCartItem(SerializationInfo info, StreamingContext context) productId = info.GetInt32("Product ID"); price = info.GetDecimal("Price"); quantity = info.GetInt32("Quantity"); total = price * quantity; } // The following method is called during serialization [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter=true)] public virtual void GetObjectData(SerializationInfo info, StreamingContext context) info.AddValue("Product ID", productId); info.AddValue("Price", price); info.AddValue("Quantity", quantity); public override string ToString() return productId + ": " + price + " x " + quantity + " = " + total;

30

31 [Serializable] class ShoppingCartItem { public Int32 productId; public decimal price; public Int32 quantity; public decimal total; [OnSerializing] void CalculateTotal(StreamingContext sc) total = price * quantity; } [OnDeserialized] void CheckTotal(StreamingContext sc) if (total == 0) { CalculateTotal(sc); }

32 How to Change Serialization Based on Context
■ Context A reference to an object that contains any user-desired context information. ■ State A set of bit flags indicating the source or destination of the objects being serialized/deserialized. The flags are: ❑ CrossProcess The source or destination is a different process on the same machine. ❑ CrossMachine The source or destination is on a different machine. ❑ File The source or destination is a file. Don’t assume that same process will deserialize the data. ❑ Persistence The source or destination is a store such as a database, file, or other. Don’t assume that same process will deserialize the data. ❑ Remoting The source or destination is remoting to an unknown location. The location might be on the same machine but might also be on another machine. ❑ Other The source or destination is unknown. ❑ Close The object graph is being cloned. The serialization code might assume that the same process will deserialize the data and it is therefore safe to access handles or other unmanaged resources.

33 Summary ■ You can implement ISerialization to perform custom serialization. ■ BinaryFormatter provides four events that you can use to control parts of the serialization process: OnSerializing, OnSerialized, OnDeserializing, and OnDeserialized. ■ 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.

34 Your Key Competences ■ Choose between binary, SOAP, XML, and custom serialization. ■ Serialize and deserialize objects using the standard libraries. ■ Create classes that can be serialized and deserialized. ■ Change the standard behavior of the serialization and deserialization process. ■ Implement custom serialization to take complete control of the serialization process. ■ Serialize and deserialize objects using XML serialization. ■ Customize serialization behavior of custom classes to meet specific requirements, such as an XML schema. ■ Serialize a dataset. ■ Implement the ISerializable interface to take control over how a class is serialized. ■ Respond to serialization events to run code at different stages of the serialization ■ Write code that adjusts serialization and deserialization according to the context. ■ Describe the role of IFormatter.

35 Key Terms ■ BinaryFormatter ■ deserialization ■ serialization
■ SoapFormatter ■ XML (eXtensible Markup Language)


Download ppt "Serialization."

Similar presentations


Ads by Google