SlideShare ist ein Scribd-Unternehmen logo
1 von 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.

Weitere ähnliche Inhalte

Andere mochten auch (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
 

Ähnlich wie Serialization Surrogates

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
arsmobiles
 
Manipulating object-behavior-at-runtime
Manipulating object-behavior-at-runtimeManipulating object-behavior-at-runtime
Manipulating object-behavior-at-runtime
Andrei Ursan
 

Ähnlich wie 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
 

Kürzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Kürzlich hochgeladen (20)

AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 

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.