SlideShare a Scribd company logo
1 of 17
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 (20)

Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Remote Method Invocation (RMI)
Remote Method Invocation (RMI)Remote Method Invocation (RMI)
Remote Method Invocation (RMI)
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
Applets
AppletsApplets
Applets
 
Introduction to .NET Framework
Introduction to .NET FrameworkIntroduction to .NET Framework
Introduction to .NET Framework
 
Operating system critical section
Operating system   critical sectionOperating system   critical section
Operating system critical section
 
Polymorphism in oop
Polymorphism in oopPolymorphism in oop
Polymorphism in oop
 
Java IO
Java IOJava IO
Java IO
 
Java RMI
Java RMIJava RMI
Java RMI
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Java RMI Presentation
Java RMI PresentationJava RMI Presentation
Java RMI Presentation
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
Asp.net.
Asp.net.Asp.net.
Asp.net.
 
Interface
InterfaceInterface
Interface
 
File concept and access method
File concept and access methodFile concept and access method
File concept and access method
 

Viewers also liked

Crypto theory practice
Crypto theory practiceCrypto theory practice
Crypto theory practiceYoung Alista
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherenceYoung 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ónpolivirtual972
 
Data visualization
Data visualizationData visualization
Data visualizationYoung Alista
 
Python language data types
Python language data typesPython language data types
Python language data typesYoung Alista
 
Python your new best friend
Python your new best friendPython your new best friend
Python your new best friendYoung Alista
 
Crypto passport authentication
Crypto passport authenticationCrypto passport authentication
Crypto passport authenticationYoung Alista
 
Abstract data types
Abstract data typesAbstract data types
Abstract data typesYoung Alista
 
Prolog programming
Prolog programmingProlog programming
Prolog programmingYoung Alista
 
Introduction to security_and_crypto
Introduction to security_and_cryptoIntroduction to security_and_crypto
Introduction to security_and_cryptoYoung 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 WPNguyen Tuan
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and OutputEduardo Bergavera
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12Vince Vo
 
IO Streams, Serialization, de-serialization, autoboxing
IO Streams, Serialization, de-serialization, autoboxingIO Streams, Serialization, de-serialization, autoboxing
IO Streams, Serialization, de-serialization, autoboxingGurpreet singh
 
Intorduction of Playframework
Intorduction of PlayframeworkIntorduction of Playframework
Intorduction of Playframeworkmaltiyadav
 
GateIn Frameworks
GateIn FrameworksGateIn Frameworks
GateIn Frameworksjviet
 
Serialization in java
Serialization in javaSerialization in java
Serialization in javaJanu Jahnavi
 
Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5Mahmoud 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.5Rainer 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
 
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
 
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io StreamsJedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io StreamsDon Bosco BSIT
 

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
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and Output
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12
 
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
 
Intake 37 ef2
Intake 37 ef2Intake 37 ef2
Intake 37 ef2
 
GateIn Frameworks
GateIn FrameworksGateIn Frameworks
GateIn Frameworks
 
Serialization in java
Serialization in javaSerialization in java
Serialization in java
 
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
 
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
 
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io StreamsJedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io Streams
 

More from Young Alista

Google appenginejava.ppt
Google appenginejava.pptGoogle appenginejava.ppt
Google appenginejava.pptYoung Alista
 
Motivation for multithreaded architectures
Motivation for multithreaded architecturesMotivation for multithreaded architectures
Motivation for multithreaded architecturesYoung Alista
 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data miningYoung Alista
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data miningYoung Alista
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discoveryYoung Alista
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cacheYoung Alista
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching worksYoung Alista
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsYoung Alista
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaYoung Alista
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsYoung Alista
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and pythonYoung Alista
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysisYoung Alista
 
Programming for engineers in python
Programming for engineers in pythonProgramming for engineers in python
Programming for engineers in pythonYoung Alista
 
Extending burp with python
Extending burp with pythonExtending burp with python
Extending burp with pythonYoung 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

DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 

Recently uploaded (20)

DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 

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: