SlideShare une entreprise Scribd logo
1  sur  4
Serialization Surrogates
What it means and why you need it?

First, there may be a situation where you have been using a third party DLL (without the
available source code) in your application which contains a type that was not designed for
serialization and you need to serialize it as per your requirement.

Secondly, during the development process you may also have a requirement to deserilaze
an object to a different version of the type i.e. You need to map one version of a type to a
different version of a type.

This is where Serialization Surrogates come into picture!!!!


How the mechanism works?

You first define a “surrogate type” that takes over the actions required to serialize and
deserialize an existing type. Then you register an instance of your surrogate type with
the formatter, telling the formatter which existing type your surrogate type is
responsible for acting upon. When the formatter detects that it is trying to serialize or
deserialize an instance of the existing type, it will call methods defined by your surrogate
type.

The example below demonstrates how all this works.

Suppose that there is an existing type, Car, defined in an assembly for which you do not
have the source code, like:
Class Car {
  public String make, model;

 public Car(String make, String model)
 {
   this.make = make;
   this.model = model;
 }
}
The above type neither has a SerializableAttribute nor does it implement the ISerializable
interface, thus it does not allow instances of itself to be serialized. But by defining a
“surrogate type” you can force the formatter to serialize the object of this type.

The surrogate type must implement the
System.Runtime.Serialization.ISerializationSurrogate interface which is defined in the
Framework Class Library as follows:
public interface ISerializationSurrogate {
  void GetObjectData(Object obj,
SerializationInfo info, StreamingContext context);

    Object SetObjectData(Object obj,
     SerializationInfo info, StreamingContext context,
     ISurrogateSelector selector);
}

Step-1:Defien a Surrogate Type
Using this interface, a Car serialization surrogate type would be defined as shown in
Figure 1. The GetObjectData method in Figure 1 works just like the ISerializable
interface's GetObjectData method. The only difference is that ISerializationSurrogate's
GetObjectData method takes one additional parameter, a reference to the "real" object
that is to be serialized. In the GetObjectData method shown in Figure 1, this object is
cast to a Car and the object's field values are added to the SerializationInfo object.

Figure -1 CarSerializationSurrogate:
sealed class CarSerializationSurrogate : ISerializationSurrogate {

    // Method called to serialize a Car object
    public void GetObjectData(Object obj,
       SerializationInfo info, StreamingContext context) {

        Car c = (Car) obj;
        info.AddValue("make", c.make);
        info.AddValue("model", c.model);
    }

    // Method called to deserialize a Car object
    public Object SetObjectData(Object obj,
       SerializationInfo info, StreamingContext context,
       ISurrogateSelector selector) {

        Car c = (Car) obj;
        c.make = info.GetString("make");
        c.model = info.GetString("model");
        return null; // Formatters ignore this return value
    }
}

The SetObjectData method is called in order to deserialize a Car object. When this
method is called, it is passed a reference to a Car object that has been allocated (via
FormatterServices' static GetUninitializedObject method). This means that the object's
fields are all null and no constructor has been called on the object. SetObjectData simply
initializes the fields of this object using the values from the passed-in SerializationInfo
object.
Step-2: Registering a Surrogate Object with a Formatter
You must be wondering how the Formatter knows to use this ISerializationSurrogate type
when it tries to serialize or deserialize the Car object.
The code in Figure -2 demonstrates how to test the CarSerializationSurrogate type. After
the 5 steps have executed, the formatter is ready to use the registered surrogate types.
When the formatter's Serialize method is called, each object's type is looked up in the set
maintained by the SurrogateSelector. If a match is found, then the ISerializationSurrogate
object's GetObjectData method is called to get the information that should be written out
to the byte stream.

Figure -2 Testing the Type :
static void SerializationSurrogateDemo() {
  // 1. Construct the desired formatter
  IFormatter formatter = new SoapFormatter();

    // 2. Construct a SurrogateSelector object
    SurrogateSelector ss = new SurrogateSelector();

    // 3. Construct an instance of our serialization surrogate type
    CarSerializationSurrogate css = new CarSerializationSurrogate();

    // 4. Tell the surrogate selector to use our object when a
    // Car object is serialized/deserialized
    ss.AddSurrogate(typeof(Car),
       new StreamingContext(StreamingContextStates.All),
       new CarSerializationSurrogate());
    // NOTE: AddSurrogate can be called multiple times to register
    // more types with their associated surrogate types

    // 5. Have the formatter use our surrogate selector
    formatter.SurrogateSelector = ss;

    // Try to serialize a Car object
    formatter.Serialize(stream, new Car("Toyota", "Celica"));

    // Rewind the stream and try to deserialize the Car object
    stream.Position = 0;
    Car c = (Car) formatter.Deserialize(stream);

    // Display the make/model to prove it worked
    Console.WriteLine("make = {0}, model = {1}", c.make, c.model);
}

When the formatter's Deserialize method is called, the type of the object about to be
deserialized is looked up in the formatter's SurrogateSelector and, if a match is found, the
ISerializationSurrogate object's SetObjectData method is called to set the fields within
the object being deserialized.


Conclusion:

There are many uses of serialization and employing it properly can greatly reduce the
effort required to build applications, persist data and transfer data between processes and
even machines.

Contenu connexe

En vedette

Collaboration friday
Collaboration fridayCollaboration friday
Collaboration fridaykacrey
 
First Line Of Defense
First Line Of DefenseFirst Line Of Defense
First Line Of Defensecjperego
 
Collaboration friday
Collaboration fridayCollaboration friday
Collaboration fridaykacrey
 
حقائق علمية وطبية في القرآن
حقائق علمية وطبية في القرآنحقائق علمية وطبية في القرآن
حقائق علمية وطبية في القرآنguest30004e2c
 
Collaboration friday
Collaboration fridayCollaboration friday
Collaboration fridaykacrey
 

En vedette (7)

Collaboration friday
Collaboration fridayCollaboration friday
Collaboration friday
 
First Line Of Defense
First Line Of DefenseFirst Line Of Defense
First Line Of Defense
 
Collaboration friday
Collaboration fridayCollaboration friday
Collaboration friday
 
حقائق علمية وطبية في القرآن
حقائق علمية وطبية في القرآنحقائق علمية وطبية في القرآن
حقائق علمية وطبية في القرآن
 
بحث
بحثبحث
بحث
 
Collaboration friday
Collaboration fridayCollaboration friday
Collaboration friday
 
ISPARTA_ENES_AKAR
ISPARTA_ENES_AKARISPARTA_ENES_AKAR
ISPARTA_ENES_AKAR
 

Similaire à Serialization Surrogates

Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objectsSandeep Chawla
 
Goal The goal of this assignment is to help students understand the.pdf
Goal The goal of this assignment is to help students understand the.pdfGoal The goal of this assignment is to help students understand the.pdf
Goal The goal of this assignment is to help students understand the.pdfarsmobiles
 
Constructors In Java – Unveiling Object Creation
Constructors In Java – Unveiling Object CreationConstructors In Java – Unveiling Object Creation
Constructors In Java – Unveiling Object CreationGeekster
 
(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_iiNico Ludwig
 
maXbox starter75 object detection
maXbox starter75 object detectionmaXbox starter75 object detection
maXbox starter75 object detectionMax Kleiner
 
Chap2 class,objects
Chap2 class,objectsChap2 class,objects
Chap2 class,objectsraksharao
 
pointers, virtual functions and polymorphisms in c++ || in cpp
pointers, virtual functions and polymorphisms in c++ || in cpppointers, virtual functions and polymorphisms in c++ || in cpp
pointers, virtual functions and polymorphisms in c++ || in cppgourav kottawar
 
Manipulating object-behavior-at-runtime
Manipulating object-behavior-at-runtimeManipulating object-behavior-at-runtime
Manipulating object-behavior-at-runtimeAndrei Ursan
 
Desing pattern prototype-Factory Method, Prototype and Builder
Desing pattern prototype-Factory Method, Prototype and Builder Desing pattern prototype-Factory Method, Prototype and Builder
Desing pattern prototype-Factory Method, Prototype and Builder paramisoft
 
How to not shoot yourself in the foot when working with serialization
How to not shoot yourself in the foot when working with serializationHow to not shoot yourself in the foot when working with serialization
How to not shoot yourself in the foot when working with serializationPVS-Studio
 
R Tanenbaum .Net Portfolio
R Tanenbaum .Net PortfolioR Tanenbaum .Net Portfolio
R Tanenbaum .Net PortfolioRobert Tanenbaum
 
Reflecting On The Code Dom
Reflecting On The Code DomReflecting On The Code Dom
Reflecting On The Code DomNick Harrison
 
Joel Landis Net Portfolio
Joel Landis Net PortfolioJoel Landis Net Portfolio
Joel Landis Net Portfoliojlshare
 
C questions
C questionsC questions
C questionsparm112
 
Custom Forms and Configuration Forms in Drupal 8
Custom Forms and Configuration Forms in Drupal 8Custom Forms and Configuration Forms in Drupal 8
Custom Forms and Configuration Forms in Drupal 8Italo Mairo
 
(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_iiNico Ludwig
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVCRichard Paul
 

Similaire à Serialization Surrogates (20)

L9
L9L9
L9
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objects
 
Goal The goal of this assignment is to help students understand the.pdf
Goal The goal of this assignment is to help students understand the.pdfGoal The goal of this assignment is to help students understand the.pdf
Goal The goal of this assignment is to help students understand the.pdf
 
Constructors In Java – Unveiling Object Creation
Constructors In Java – Unveiling Object CreationConstructors In Java – Unveiling Object Creation
Constructors In Java – Unveiling Object Creation
 
(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii
 
maXbox starter75 object detection
maXbox starter75 object detectionmaXbox starter75 object detection
maXbox starter75 object detection
 
Chap2 class,objects
Chap2 class,objectsChap2 class,objects
Chap2 class,objects
 
pointers, virtual functions and polymorphisms in c++ || in cpp
pointers, virtual functions and polymorphisms in c++ || in cpppointers, virtual functions and polymorphisms in c++ || in cpp
pointers, virtual functions and polymorphisms in c++ || in cpp
 
Manipulating object-behavior-at-runtime
Manipulating object-behavior-at-runtimeManipulating object-behavior-at-runtime
Manipulating object-behavior-at-runtime
 
Desing pattern prototype-Factory Method, Prototype and Builder
Desing pattern prototype-Factory Method, Prototype and Builder Desing pattern prototype-Factory Method, Prototype and Builder
Desing pattern prototype-Factory Method, Prototype and Builder
 
How to not shoot yourself in the foot when working with serialization
How to not shoot yourself in the foot when working with serializationHow to not shoot yourself in the foot when working with serialization
How to not shoot yourself in the foot when working with serialization
 
R Tanenbaum .Net Portfolio
R Tanenbaum .Net PortfolioR Tanenbaum .Net Portfolio
R Tanenbaum .Net Portfolio
 
Reflecting On The Code Dom
Reflecting On The Code DomReflecting On The Code Dom
Reflecting On The Code Dom
 
Joel Landis Net Portfolio
Joel Landis Net PortfolioJoel Landis Net Portfolio
Joel Landis Net Portfolio
 
Reflection
ReflectionReflection
Reflection
 
C questions
C questionsC questions
C questions
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Custom Forms and Configuration Forms in Drupal 8
Custom Forms and Configuration Forms in Drupal 8Custom Forms and Configuration Forms in Drupal 8
Custom Forms and Configuration Forms in Drupal 8
 
(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
 

Dernier

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 

Dernier (20)

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 

Serialization Surrogates

  • 1. Serialization Surrogates What it means and why you need it? First, there may be a situation where you have been using a third party DLL (without the available source code) in your application which contains a type that was not designed for serialization and you need to serialize it as per your requirement. Secondly, during the development process you may also have a requirement to deserilaze an object to a different version of the type i.e. You need to map one version of a type to a different version of a type. This is where Serialization Surrogates come into picture!!!! How the mechanism works? You first define a “surrogate type” that takes over the actions required to serialize and deserialize an existing type. Then you register an instance of your surrogate type with the formatter, telling the formatter which existing type your surrogate type is responsible for acting upon. When the formatter detects that it is trying to serialize or deserialize an instance of the existing type, it will call methods defined by your surrogate type. The example below demonstrates how all this works. Suppose that there is an existing type, Car, defined in an assembly for which you do not have the source code, like: Class Car { public String make, model; public Car(String make, String model) { this.make = make; this.model = model; } } The above type neither has a SerializableAttribute nor does it implement the ISerializable interface, thus it does not allow instances of itself to be serialized. But by defining a “surrogate type” you can force the formatter to serialize the object of this type. The surrogate type must implement the System.Runtime.Serialization.ISerializationSurrogate interface which is defined in the Framework Class Library as follows: public interface ISerializationSurrogate { void GetObjectData(Object obj,
  • 2. SerializationInfo info, StreamingContext context); Object SetObjectData(Object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector); } Step-1:Defien a Surrogate Type Using this interface, a Car serialization surrogate type would be defined as shown in Figure 1. The GetObjectData method in Figure 1 works just like the ISerializable interface's GetObjectData method. The only difference is that ISerializationSurrogate's GetObjectData method takes one additional parameter, a reference to the "real" object that is to be serialized. In the GetObjectData method shown in Figure 1, this object is cast to a Car and the object's field values are added to the SerializationInfo object. Figure -1 CarSerializationSurrogate: sealed class CarSerializationSurrogate : ISerializationSurrogate { // Method called to serialize a Car object public void GetObjectData(Object obj, SerializationInfo info, StreamingContext context) { Car c = (Car) obj; info.AddValue("make", c.make); info.AddValue("model", c.model); } // Method called to deserialize a Car object public Object SetObjectData(Object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector) { Car c = (Car) obj; c.make = info.GetString("make"); c.model = info.GetString("model"); return null; // Formatters ignore this return value } } The SetObjectData method is called in order to deserialize a Car object. When this method is called, it is passed a reference to a Car object that has been allocated (via FormatterServices' static GetUninitializedObject method). This means that the object's fields are all null and no constructor has been called on the object. SetObjectData simply initializes the fields of this object using the values from the passed-in SerializationInfo object.
  • 3. Step-2: Registering a Surrogate Object with a Formatter You must be wondering how the Formatter knows to use this ISerializationSurrogate type when it tries to serialize or deserialize the Car object. The code in Figure -2 demonstrates how to test the CarSerializationSurrogate type. After the 5 steps have executed, the formatter is ready to use the registered surrogate types. When the formatter's Serialize method is called, each object's type is looked up in the set maintained by the SurrogateSelector. If a match is found, then the ISerializationSurrogate object's GetObjectData method is called to get the information that should be written out to the byte stream. Figure -2 Testing the Type : static void SerializationSurrogateDemo() { // 1. Construct the desired formatter IFormatter formatter = new SoapFormatter(); // 2. Construct a SurrogateSelector object SurrogateSelector ss = new SurrogateSelector(); // 3. Construct an instance of our serialization surrogate type CarSerializationSurrogate css = new CarSerializationSurrogate(); // 4. Tell the surrogate selector to use our object when a // Car object is serialized/deserialized ss.AddSurrogate(typeof(Car), new StreamingContext(StreamingContextStates.All), new CarSerializationSurrogate()); // NOTE: AddSurrogate can be called multiple times to register // more types with their associated surrogate types // 5. Have the formatter use our surrogate selector formatter.SurrogateSelector = ss; // Try to serialize a Car object formatter.Serialize(stream, new Car("Toyota", "Celica")); // Rewind the stream and try to deserialize the Car object stream.Position = 0; Car c = (Car) formatter.Deserialize(stream); // Display the make/model to prove it worked Console.WriteLine("make = {0}, model = {1}", c.make, c.model); } When the formatter's Deserialize method is called, the type of the object about to be deserialized is looked up in the formatter's SurrogateSelector and, if a match is found, the
  • 4. ISerializationSurrogate object's SetObjectData method is called to set the fields within the object being deserialized. Conclusion: There are many uses of serialization and employing it properly can greatly reduce the effort required to build applications, persist data and transfer data between processes and even machines.