SlideShare a Scribd company logo
Serialization
 What is Serialization?
 System.Serialization
 Scenarios in Serialization
 Basic Serialization
 Custom Serialization
Serialization/Deserialization
Object in memory
Object in memory
…binary or character stream…
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
 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
Serialization
Object 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
CatCat Mouse
Duck
Dog
2
1
3
4
9
7
Horse
Serialization
How 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
Serializaiton
FileStream Example
class SerializeExample{
public static void Main(String[] args)
{
ArrayList l = new ArrayList();
for (int x=0; x< 100; x++) {
l.Add (x);
} // create the object graph
FileStream s = File.Create("foo.bin"); // create the
filestream BinaryFormatter b = new BinaryFormatter();
// create the BinaryFormatter
b.Serialize(s, l);
// serialize the graph to the stream
} // end main
} // end class
Serializaiton
Deserialize Example
using System; using System.IO;
using System.Collections;
using System.Serialization;
using System.Serialization.Formatters.Binary;
class DeSerialize
{
public static void Main(String[] args) {
FileStream s = File.Open("foo.bin"); // open the
filestream BinaryFormatter b = new BinaryFormatter(); //
create the formatter ArrayList p = (ArrayList)
b.Deserialize(s); // deserialize
p.ToString(); // print out the new object graph
} // end Main
} // end Class DeSerialize
Serialization
Basic 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;
}
.NET Serialization Facilities
Take an extremely simple C# class:
public class InitialConfiguration
{
public enum Difficulty {hard, medium, easy};
public InitialConfiguration() { }
public Difficulty starting = Difficulty.medium;
}
.NET Serialization Facilities
Use .NET library functions to serialize it:
InitialConfiguration conf = new InitialConfiguration();
XmlSerializer ser
= new XmlSerializer(typeof(InitialConfiguration));
XmlTextWriter writer = new XmlTextWriter(
stream, System.Text.Encoding.UTF8);
ser.Serialize(writer, conf);
.NET Serialization Facilities
Get XML:
<?xml version="1.0" encoding=“utf-8"?>
<InitialConfiguration
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Starting>medium</starting>
</InitialConfiguration>
Serialization
Customize Serialization
 Implementing ISerializable interface
 IDeserializationEventListener
 Custom Formatters
Serialization
ISerializable Interface
 Customize the serialization process
 If a class implements ISerializable, that interface
will always be called in preference to default
serialization.
 The ISerializable interface is only contains one
method:
void GetObjectData (SerializationInfo info,
StreamingContext context); And an implied constructor
that may be private. private <TypeName>
(SerializationInfo info, StreamingContext)
Serialization
IDeserializationEventListener
 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
Custom Formatter
 Implementing IFormatter Interface:
public interface IFormatter:
{ //Properties
SerializationBinder Binder { get; set; }
StreamingContext Context { get; set; }
ISurrogateSelector SurrogateSelector { get; set; }
//Methods
object Deserialize(Stream serializationStream);
void Serialize(Stream serializationStream, object
graph);
}
Conclusion
 Types' metadata can be explored with Reflection
 Reflection provides dynamic type system
 The Federated Services Model is one of the core
concepts for designing .NET applications in Internet
 Key .NET Remoting scenarios are:
 Web Services Anywhere
 CLR Object Remoting
 Serialization is the process of converting an object, or a
connected graph of objects, stored within computer
memory, into a linear sequence of bytes
Resources
 http://msdn.microsoft.com/net/
 .NET Framework SDK

More Related Content

What's hot

Wrapper class
Wrapper classWrapper class
Wrapper class
kamal kotecha
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
sets and maps
 sets and maps sets and maps
sets and maps
Rajkattamuri
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
Tushar B Kute
 
Event handling
Event handlingEvent handling
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
Hamid Ghorbani
 
Session tracking in servlets
Session tracking in servletsSession tracking in servlets
Session tracking in servlets
vishal choudhary
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
Nilesh Dalvi
 
ADO .Net
ADO .Net ADO .Net
ADO .Net
DrSonali Vyas
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
VINOTH R
 
Java awt
Java awtJava awt
Java awt
Arati Gadgil
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
Elizabeth alexander
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
teach4uin
 
Serialization in java
Serialization in javaSerialization in java
Serialization in java
Janu Jahnavi
 
Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Java awt (abstract window toolkit)
Java awt (abstract window toolkit)
Elizabeth alexander
 
Abstract class and Interface
Abstract class and InterfaceAbstract class and Interface
Abstract class and Interface
Haris Bin Zahid
 
Java beans
Java beansJava beans
Java beans
Rajkiran Mummadi
 
Applets
AppletsApplets

What's hot (20)

Wrapper class
Wrapper classWrapper class
Wrapper class
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
sets and maps
 sets and maps sets and maps
sets and maps
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
Event handling
Event handlingEvent handling
Event handling
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Session tracking in servlets
Session tracking in servletsSession tracking in servlets
Session tracking in servlets
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
ADO .Net
ADO .Net ADO .Net
ADO .Net
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
Generics
GenericsGenerics
Generics
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Java awt
Java awtJava awt
Java awt
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
 
Serialization in java
Serialization in javaSerialization in java
Serialization in java
 
Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Java awt (abstract window toolkit)
Java awt (abstract window toolkit)
 
Abstract class and Interface
Abstract class and InterfaceAbstract class and Interface
Abstract class and Interface
 
Java beans
Java beansJava beans
Java beans
 
Applets
AppletsApplets
Applets
 

Viewers also liked

Crypto theory practice
Crypto theory practiceCrypto theory practice
Crypto theory practice
Young Alista
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherence
Young Alista
 
Tecnologías de Información y Comunicación
Tecnologías de Información y ComunicaciónTecnologías de Información y Comunicación
Tecnologías de Información y Comunicación
polivirtual972
 
Data visualization
Data visualizationData visualization
Data visualization
Young Alista
 
Python language data types
Python language data typesPython language data types
Python language data types
Young Alista
 
Python your new best friend
Python your new best friendPython your new best friend
Python your new best friend
Young Alista
 
Abstraction file
Abstraction fileAbstraction file
Abstraction file
Young Alista
 
Crypto passport authentication
Crypto passport authenticationCrypto passport authentication
Crypto passport authentication
Young Alista
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
Young Alista
 
Prolog programming
Prolog programmingProlog programming
Prolog programming
Young Alista
 
Data preparation
Data preparationData preparation
Data preparation
Young Alista
 
Czego pragna klienci
Czego pragna klienciCzego pragna klienci
Czego pragna klienci
Kurs Na Nieruchomości
 
Introduction to security_and_crypto
Introduction to security_and_cryptoIntroduction to security_and_crypto
Introduction to security_and_crypto
Young Alista
 

Viewers also liked (20)

Crypto theory practice
Crypto theory practiceCrypto theory practice
Crypto theory practice
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherence
 
Tecnologías de Información y Comunicación
Tecnologías de Información y ComunicaciónTecnologías de Información y Comunicación
Tecnologías de Información y Comunicación
 
Data visualization
Data visualizationData visualization
Data visualization
 
Prolog resume
Prolog resumeProlog resume
Prolog resume
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Reflection
ReflectionReflection
Reflection
 
Python your new best friend
Python your new best friendPython your new best friend
Python your new best friend
 
Abstraction file
Abstraction fileAbstraction file
Abstraction file
 
Crypto passport authentication
Crypto passport authenticationCrypto passport authentication
Crypto passport authentication
 
Python basics
Python basicsPython basics
Python basics
 
Exception
ExceptionException
Exception
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
Prolog programming
Prolog programmingProlog programming
Prolog programming
 
Data preparation
Data preparationData preparation
Data preparation
 
Maven
MavenMaven
Maven
 
Czego pragna klienci
Czego pragna klienciCzego pragna klienci
Czego pragna klienci
 
Html5
Html5Html5
Html5
 
Introduction to security_and_crypto
Introduction to security_and_cryptoIntroduction to security_and_crypto
Introduction to security_and_crypto
 
Xml schema
Xml schemaXml schema
Xml schema
 

Similar to Serialization/deserialization

09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WP09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WP
Nguyen Tuan
 
.NET Reflection
.NET Reflection.NET Reflection
.NET Reflection
Robert MacLean
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12Vince Vo
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and Output
Eduardo Bergavera
 
IO Streams, Serialization, de-serialization, autoboxing
IO Streams, Serialization, de-serialization, autoboxingIO Streams, Serialization, de-serialization, autoboxing
IO Streams, Serialization, de-serialization, autoboxing
Gurpreet singh
 
Intorduction of Playframework
Intorduction of PlayframeworkIntorduction of Playframework
Intorduction of Playframework
maltiyadav
 
Advance Java
Advance JavaAdvance Java
Advance Java
Vidyacenter
 
Gulshan serialization inJava PPT ex.pptx
Gulshan serialization inJava PPT ex.pptxGulshan serialization inJava PPT ex.pptx
Gulshan serialization inJava PPT ex.pptx
PRABHATMISHRA969924
 
Intake 37 ef2
Intake 37 ef2Intake 37 ef2
Intake 37 ef2
Mahmoud Ouf
 
GateIn Frameworks
GateIn FrameworksGateIn Frameworks
GateIn Frameworksjviet
 
5-Hibernate.ppt
5-Hibernate.ppt5-Hibernate.ppt
5-Hibernate.ppt
ShivaPriya60
 
hibernate with JPA
hibernate with JPAhibernate with JPA
hibernate with JPA
Mohammad Faizan
 
Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5
Mahmoud Ouf
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
Whats New for WPF in .NET 4.5
Whats New for WPF in .NET 4.5Whats New for WPF in .NET 4.5
Whats New for WPF in .NET 4.5
Rainer Stropek
 
Sharepoint Saturday India Online best practice for developing share point sol...
Sharepoint Saturday India Online best practice for developing share point sol...Sharepoint Saturday India Online best practice for developing share point sol...
Sharepoint Saturday India Online best practice for developing share point sol...Shakir Majeed Khan
 
Local Storage
Local StorageLocal Storage
Local Storage
Ivano Malavolta
 
Developing your first application using FI-WARE
Developing your first application using FI-WAREDeveloping your first application using FI-WARE
Developing your first application using FI-WAREFermin Galan
 

Similar to Serialization/deserialization (20)

09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WP09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WP
 
.NET Reflection
.NET Reflection.NET Reflection
.NET Reflection
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and Output
 
IO Streams, Serialization, de-serialization, autoboxing
IO Streams, Serialization, de-serialization, autoboxingIO Streams, Serialization, de-serialization, autoboxing
IO Streams, Serialization, de-serialization, autoboxing
 
Intorduction of Playframework
Intorduction of PlayframeworkIntorduction of Playframework
Intorduction of Playframework
 
Advance Java
Advance JavaAdvance Java
Advance Java
 
Gulshan serialization inJava PPT ex.pptx
Gulshan serialization inJava PPT ex.pptxGulshan serialization inJava PPT ex.pptx
Gulshan serialization inJava PPT ex.pptx
 
Intake 37 ef2
Intake 37 ef2Intake 37 ef2
Intake 37 ef2
 
GateIn Frameworks
GateIn FrameworksGateIn Frameworks
GateIn Frameworks
 
5-Hibernate.ppt
5-Hibernate.ppt5-Hibernate.ppt
5-Hibernate.ppt
 
Reflection
ReflectionReflection
Reflection
 
hibernate with JPA
hibernate with JPAhibernate with JPA
hibernate with JPA
 
Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5
 
Java I/O
Java I/OJava I/O
Java I/O
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
Whats New for WPF in .NET 4.5
Whats New for WPF in .NET 4.5Whats New for WPF in .NET 4.5
Whats New for WPF in .NET 4.5
 
Sharepoint Saturday India Online best practice for developing share point sol...
Sharepoint Saturday India Online best practice for developing share point sol...Sharepoint Saturday India Online best practice for developing share point sol...
Sharepoint Saturday India Online best practice for developing share point sol...
 
Local Storage
Local StorageLocal Storage
Local Storage
 
Developing your first application using FI-WARE
Developing your first application using FI-WAREDeveloping your first application using FI-WARE
Developing your first application using FI-WARE
 

More from Young Alista

Google appenginejava.ppt
Google appenginejava.pptGoogle appenginejava.ppt
Google appenginejava.ppt
Young Alista
 
Motivation for multithreaded architectures
Motivation for multithreaded architecturesMotivation for multithreaded architectures
Motivation for multithreaded architectures
Young Alista
 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data mining
Young Alista
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data mining
Young Alista
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discovery
Young Alista
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cache
Young Alista
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching works
Young Alista
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessors
Young Alista
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Young Alista
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
Young Alista
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and python
Young Alista
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysis
Young Alista
 
Programming for engineers in python
Programming for engineers in pythonProgramming for engineers in python
Programming for engineers in python
Young Alista
 
Learning python
Learning pythonLearning python
Learning python
Young Alista
 
Extending burp with python
Extending burp with pythonExtending burp with python
Extending burp with python
Young Alista
 

More from Young Alista (20)

Google appenginejava.ppt
Google appenginejava.pptGoogle appenginejava.ppt
Google appenginejava.ppt
 
Motivation for multithreaded architectures
Motivation for multithreaded architecturesMotivation for multithreaded architectures
Motivation for multithreaded architectures
 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data mining
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data mining
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discovery
 
Cache recap
Cache recapCache recap
Cache recap
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cache
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching works
 
Object model
Object modelObject model
Object model
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessors
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Abstract class
Abstract classAbstract class
Abstract class
 
Inheritance
InheritanceInheritance
Inheritance
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and python
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysis
 
Programming for engineers in python
Programming for engineers in pythonProgramming for engineers in python
Programming for engineers in python
 
Api crash
Api crashApi crash
Api crash
 
Learning python
Learning pythonLearning python
Learning python
 
Extending burp with python
Extending burp with pythonExtending burp with python
Extending burp with python
 

Recently uploaded

FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
Fwdays
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 

Recently uploaded (20)

FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 

Serialization/deserialization

  • 1. Serialization  What is Serialization?  System.Serialization  Scenarios in Serialization  Basic Serialization  Custom Serialization
  • 2. Serialization/Deserialization Object in memory Object in memory …binary or character stream…
  • 3. 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  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
  • 4. Serialization Object 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 CatCat Mouse Duck Dog 2 1 3 4 9 7 Horse
  • 5. Serialization How 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
  • 6. Serializaiton FileStream Example class SerializeExample{ public static void Main(String[] args) { ArrayList l = new ArrayList(); for (int x=0; x< 100; x++) { l.Add (x); } // create the object graph FileStream s = File.Create("foo.bin"); // create the filestream BinaryFormatter b = new BinaryFormatter(); // create the BinaryFormatter b.Serialize(s, l); // serialize the graph to the stream } // end main } // end class
  • 7. Serializaiton Deserialize Example using System; using System.IO; using System.Collections; using System.Serialization; using System.Serialization.Formatters.Binary; class DeSerialize { public static void Main(String[] args) { FileStream s = File.Open("foo.bin"); // open the filestream BinaryFormatter b = new BinaryFormatter(); // create the formatter ArrayList p = (ArrayList) b.Deserialize(s); // deserialize p.ToString(); // print out the new object graph } // end Main } // end Class DeSerialize
  • 8. Serialization Basic 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; }
  • 9. .NET Serialization Facilities Take an extremely simple C# class: public class InitialConfiguration { public enum Difficulty {hard, medium, easy}; public InitialConfiguration() { } public Difficulty starting = Difficulty.medium; }
  • 10. .NET Serialization Facilities Use .NET library functions to serialize it: InitialConfiguration conf = new InitialConfiguration(); XmlSerializer ser = new XmlSerializer(typeof(InitialConfiguration)); XmlTextWriter writer = new XmlTextWriter( stream, System.Text.Encoding.UTF8); ser.Serialize(writer, conf);
  • 11. .NET Serialization Facilities Get XML: <?xml version="1.0" encoding=“utf-8"?> <InitialConfiguration xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Starting>medium</starting> </InitialConfiguration>
  • 12. Serialization Customize Serialization  Implementing ISerializable interface  IDeserializationEventListener  Custom Formatters
  • 13. Serialization ISerializable Interface  Customize the serialization process  If a class implements ISerializable, that interface will always be called in preference to default serialization.  The ISerializable interface is only contains one method: void GetObjectData (SerializationInfo info, StreamingContext context); And an implied constructor that may be private. private <TypeName> (SerializationInfo info, StreamingContext)
  • 14. Serialization IDeserializationEventListener  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
  • 15. Serialization Custom Formatter  Implementing IFormatter Interface: public interface IFormatter: { //Properties SerializationBinder Binder { get; set; } StreamingContext Context { get; set; } ISurrogateSelector SurrogateSelector { get; set; } //Methods object Deserialize(Stream serializationStream); void Serialize(Stream serializationStream, object graph); }
  • 16. Conclusion  Types' metadata can be explored with Reflection  Reflection provides dynamic type system  The Federated Services Model is one of the core concepts for designing .NET applications in Internet  Key .NET Remoting scenarios are:  Web Services Anywhere  CLR Object Remoting  Serialization is the process of converting an object, or a connected graph of objects, stored within computer memory, into a linear sequence of bytes

Editor's Notes

  1. Serialization = writing the object’s state out in serial (sequential) order to a stream of some sort. DeSerialiation = reading the object state back in from the stream to restore it. This is all about state, although structure is important too. If I serialize things ABC, and you deserialize them expecting CBA, we’re in trouble. XML is particularly neat for serialization because it’s self-describing.
  2. Let&amp;apos;s clearly define what we mean by serialization. By Serialization we mean converting an object, or a connected graph of objects, stored within computer memory, and conventionally drawn on paper in two dimensions, into a linear sequence of bytes. That string of bytes contains all of the important information that was held in the objects we started with. We can go on to use that sequence of bytes in several ways. For example: Send it to another process (on the same machine) and use it to construct arguments to a method that is run in that other process. In this case, the sequence of bytes is copied from one location in the machine&amp;apos;s physical memory to another – it never leaves the machine Send it to the clipboard, to be browsed or included in another application. As above, the sequence of bytes is transferred to another location in memory on the current machine. Send it &amp;apos;down the wire&amp;apos; to another machine and use it to create a clone on that machine of the original object graph. As above, we might then use this object graph as an argument to a method call. In this case, however, the sequence of bytes is actually transferred outside of the originating machine. Send it to a file on-disk, so that it can be reused later.   (See, for example, the classic &amp;quot;Scribble tutorial&amp;quot; in &amp;quot;Using Visual C++&amp;quot; issued as part of the Visual C++ 6.0, and earlier).
  3. An object graph is a set of objects with some set of references to each other. The interesting question here is what problems does this bring for Serialization? The most obvious problem is how to represent the links between the objects in the Serialized stream. After all, the value held in the field of the in-memory object which links to another object is essentially a 32-bit address, which has meaning only in the owner address space (and may even change, &amp;apos;beneath our feet&amp;apos;, due to garbage collection). Serialization needs to allocate each object in the stream a number. So, for example, we have assigned arbitrary, small numbers to objects below, and shown the class of each: Then we can represent this graph of objects with a serialized stream like this: Dog, 3, ref 4, ref 7, ref 1 || Cat, 4 || Cat 7 || Mouse, 1, ref 9, ref 2 || Horse, 9, ref 4 || Duck, 2
  4. Because the runtime metadata &amp;apos;knows&amp;apos; all there is to know about each object&amp;apos;s layout in memory, 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. Pluggable formatters allow the developer to serialize objects in with the two supplied formats (binary and SOAP) or create their own. Serializetion can take place with any stream, not just a FileStream (see MemoryStream, NetStream, etc.) Serialization makes use of several classes, as follows: Formatter — Responsible for writing object data in some specified format to the output stream. This class is also responsible for driving the deserialization operation. ObjectIDGenerator — ObjectIDGenerator generates IDs for objects. It keeps track of objects already &amp;apos;seen&amp;apos; so that if you ask for the ID of an object, it knows whether to return its existing ID, or generate (and remember) a new ID. ObjectManager — Keeps track of objects as they are being deserialized. In this way, deserialization can query the ObjectManager to know whether a reference to an object, in the serialized stream, refers to an object that has already been deserialized (a backward reference), or to an object that has not yet been deserialized (a forward reference). Each of these components is &amp;apos;pluggable&amp;apos; — the programmer can provide alternatives
  5. This example shows how to perform default Serialization of a graph of objects, whose root is the arraylist l. This code serializes the graph to a FileStream:
  6. This example shows how to perform default Serialization of a graph of objects, whose root is the arraylist l. This code serializes the graph to a FileStream:
  7. Class authors need to be aware of serialization. The serialization services assume that a type is NOT Serializable unless type is specifically marked as Serializable. In the most simple case marking a class as Serializable is the all the class author will have to do. For slightly more complex classes with state that is invalid to serialize, we provide support for marking those fields and properties as transient. For the handful of classes that need to participate in their own serialization an Deserialization we provide an ISerializable interface. A class must be marked with the Serializable bit to be Serialized. An exception is thrown during serialization if the bit is not set of any class involved in the graph being serialized. In C#, this bit is set with a reserved custom attribute [Serializable] public class MyClass {} Classes with this addribute have all fields (even private ones) serialized. There are fields and properties on some types that it does not make since to serialize. Either for performance or correctness reasons the class author needs to tell the serialization service to &amp;quot;skip&amp;quot; these members. This is done by using the NotSerialized custom attribute. If the NotSerialized attribute is set the class author is saying this field or property within a class should not be serialized. In C# this bit is set with the transient keyword [Serializable] public class MyClass { [NotSerialized] int _cashSize; }
  8. There’s nothing that indicates that this class can be serialized, but…
  9. … this code will serialize it. This uses reflection, something familiar to Java programmers. Stream = whatever stream we want to send this to.
  10. Note that we didn’t need to do anything to the class which we’ve just serialized, and yet we get reasonable XML. All that’s required to serialize as XML or SOAP: Default constructor, and public data members or properties. (When in doubt, use properties.) Don’t worry about the schema stuff; that’s boilerplate. You actually can omit it from your input XML files. But it’s better practice to use it.
  11. Developers may want a way to customize exactly how data from a given object is serialized.   For that, the developer should implement the ISerializable interface on the given object. This may be useful for example when some of the data associated with your object may not be valid after deserialization (pointers, hashcodes, etc.) or when you want to create some data (through calculations or some other means) that allows you to reconstruct the full state of the object during deserialization. Implementing ISerializable involves implementing the GetObjectData method on your object and adding a constructor that takes a SerializationInfo and a StreamingContext as shown below.
  12. If a class author wishes to take special action when objects of that class are serialized and deserialized, he can choose to implement the ISerializable interface. This allows full control. For example, the author may define his own, custom SerializationInfo, to describe parts of the object, or synthesized fields that capture the object state for serialization. If a class implements ISerializable, that interface will always be called in preference to default serialization. The ISerializable interface is only contains one method: void GetObjectData (SerializationInfo info, StreamingContext context); And an implied constructor that may be private. private &amp;lt;TypeName&amp;gt; (SerializationInfo info, StreamingContext) An important note on deserialization is that we return the fields in the same order in which they are returned from Reflection. Reflection makes no guarantee that it will follow metadata ordering.
  13. As seen a few times before, the Formatters are the classes that actualy format the information in the SerializationInfo into something that can be written to a stream. The Runtime provides two such formatters, the BinaryFormatter, and the SOAPFormatter. Since formatters are pluggable, developers can build their own if need be. The basic picture is as follows: The IFormatter interface must be implemented by a developer wishing to write their own formatter. The interface is simple and consists of two methods and three properties: