Lets say we want to beam Kirk and Spock (from StarTrek) to earth to save earth! To do this Kirk and Spock have to be de-materialized into energy pattern and these energy pattern re-materialize when it arrives on earth.
Similarly, if you want to send two .NET objects, for example Kirk and Spock, over the wire to another application then you can use Serializers. Serializers are used to serialize objects into message and then to deserialize message back to objects at the destination.
WCF uses a number of Serializers here are some of them:
- DataContractSerializer
- NetDataContractSerializer
Both serializers inherit from XMLObjectSerializer
NetDataContractSerializer
- Used when same type is expected on either side of the wire. Requires .NET framework on both ends
- Makes the resulting XML more complex
When serializing an instance of a type note the following:
- Serializer created to serialize a root type can only be used to serialize instances of that root type and instance of types that are derived from it.
- KnownTypeAttribute is use to let the serializer know how to deserialize the a type
- This attribute should be applied to Data Contracts and not to Data Members
- Elements are serialized in ascending alphabetical order
- The Name and namespace of the outermost XML element can be changed by Name and Namespace of the DataContract
DataContractSerializer Example:
static void Main(string[] args)
{
ProductReview p = new ProductReview() { Id = "001", ProductCode = "12", ProductName = "Mask", Review = "Very Good!" };
DataContractSerializer dcs = new DataContractSerializer(typeof(ProductReview));
//Serialize
using (FileStream fs = new FileStream("ProductReview.xml", FileMode.Create))
{
dcs.WriteObject(fs, p);
}
//Deserialize
using (FileStream fs = new FileStream("ProductReview.xml", FileMode.Open))
{
ProductReview pr = (ProductReview)dcs.ReadObject(fs);
Console.WriteLine("Product Name: {0} \nCustomer Review: {1}", pr.ProductName, pr.Review);
}
Console.ReadKey();
}
Links and References
- Serialization and Deserialization - https://msdn.microsoft.com/en-us/library/ms731073(v=vs.110).aspx
Comments
Post a Comment