Serialization.

Slides:



Advertisements
Similar presentations
C# and Windows Programming Application Domains and Remoting.
Advertisements

Object Oriented Programming Files and Streams Dr. Mike Spann
C# - Files and Streams Outline Files and Streams Classes File and Directory Creating a Sequential-Access File Reading Data from a Sequential-Access.
Serialization objects created in a program reside in RAM through references object o; heap stack content.
Portable binary serialization, the Google way
Writing Object Oriented Software with C#. C# and OOP C# is designed for the.NET Framework  The.NET Framework is Object Oriented In C#  Your access to.
Portability CPSC 315 – Programming Studio Spring 2008 Material from The Practice of Programming, by Pike and Kernighan.
About the Presentations The presentations cover the objectives found in the opening of each chapter. All chapter objectives are listed in the beginning.
ASP.NET Programming with C# and SQL Server First Edition
Creating Sequential-Access File  Serializable attribute indicates to the compiler that objects of a class can be serialized– written to or read from a.
Sequential-access file Create, read and write an object into a sequential-access file Serialize and deserialize the object to write and read from a data.
1 An Introduction to Visual Basic Objectives Explain the history of programming languages Define the terminology used in object-oriented programming.
Windows Programming Using C# Windows Services, Serialization, and Isolated Storage.
.NET, and Service Gateways Group members: Andre Tran, Priyanka Gangishetty, Irena Mao, Wileen Chiu.
1 Chapter One A First Program Using C#. 2 Objectives Learn about programming tasks Learn object-oriented programming concepts Learn about the C# programming.
.NET Framework Introduction: Metadata
1 Binary Files ผศ. ดร. หมัดอามีน หมันหลิน Faculty of IST, MUT
Advanced .NET Programming I 13th Lecture
Module 7: Object-Oriented Programming in Visual Basic .NET
1 Understanding Inheritance COSC 156 C++ Programming Lecture 8.
HeuristicLab. Motivation  less memory pressure no DOM single pass linear process  less developer effort no interfaces to implement  modularity & flexibility.
Tutorial C#. PLAN I. Introduction II. Example of C# program :Hello World III. How to use C# language GUI elements Primitives Types Expressions and operators.
Software Design 13.1 XML: Another TLA or the Future? XML is eXtensible Markup Language  It's a w3c standard.
CSCI 6962: Server-side Design and Programming Web Services.
Serialization  What is Serialization?  System.Serialization  Scenarios in Serialization  Basic Serialization  Custom Serialization.
Reference: Lecturer Lecturer Reham O. Al-Abdul Jabba lectures for cap211 Files and Streams- I.
Object Persistence and Object serialization CSNB534 Asma Shakil.
Serialization What is Serialization Serialization is the process of converting an object, or a connected graph of objects, stored within computer memory,
The Role of .NET Exception Handling
Lecture 19 Serialization Richard Gesick. Serialization Sometimes it is easier to read or write entire objects than to read and write individual fields.
Object Serialization.  When the data was output to disk, certain information was lost, such as the type of each value.  If the value "3" is read from.
Representing data with XML SE-2030 Dr. Mark L. Hornick 1.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 JSP Application Models.
©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.
Web Services from 10,000 feet Part I Tom Perkins NTPCUG CertSIG XML Web Services.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
.NET Mobile Application Development XML Web Services.
.NET XML Web Services by Joe Mayo Mayo Software Consulting
CHAPTER NINE Accessing Data Using XML. McGraw Hill/Irwin ©2002 by The McGraw-Hill Companies, Inc. All rights reserved Introduction The eXtensible.
The purpose of a CPU is to process data Custom written software is created for a user to meet exact purpose Off the shelf software is developed by a software.
ASP.NET Programming with C# and SQL Server First Edition
Computing with C# and the .NET Framework
CSC 243 – Java Programming, Spring 2014
A Web Services Journey on the .NET Bus
Advanced Object-Oriented Programming Features
Introduction to Visual Basic 2008 Programming
Input and Output 23: Input and Output
Advanced .NET Programming II 6th Lecture
Java Primer 1: Types, Classes and Operators
Java Beans Sagun Dhakhwa.
CS3340 – OOP and C++ L. Grewe.
Objectives Identify the built-in data types in C++
18 Files and Streams.
CPSC 315 – Programming Studio Spring 2012
Microsoft .NET 3. Language Innovations Pan Wuming 2017.
XAML User Interface Creation in C#
Interfaces and Inheritance
CS360 Windows Programming
Tutorial C#.
Understanding Inheritance
Portability CPSC 315 – Programming Studio
Deepak Shenoy Agni Software
Fundaments of Game Design
How to organize and document your classes
CSC 220 – Processing Spring, 2017
Quiz Points 3 Rules Raise your hand if you know the question
Chapter 15 Files, Streams and Object Serialization
Chapter 11 Saving Data and Objects In Files
5. OOP OOP © 2003 Microsoft.
.NET Web Services by Akram Mohammed.
Presentation transcript:

Serialization

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

Serializing Objects

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.

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();

// 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();

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.

// 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());

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; }

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; }

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.

Use SoapFormatter <SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <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>

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.

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.

XML Serialization

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

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>2005-12-05T16:28:11.0533408-05:00</dateTime>

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.

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

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() }

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

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.

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

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.

Custom Serialization

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.

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

[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;

[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); }

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.

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.

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.

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