Presentation is loading. Please wait.

Presentation is loading. Please wait.

Advanced .NET Programming II 6th Lecture

Similar presentations


Presentation on theme: "Advanced .NET Programming II 6th Lecture"— Presentation transcript:

1 Advanced .NET Programming II 6th Lecture
Pavel Ježek Some of the slides are based on University of Linz .NET presentations. © University of Linz, Institute for System Software, 2004 published under the Microsoft Curriculum License (

2 Serialization

3 System.Runtime.Serialization Serialization and Formatters
namespace System.Runtime.Serialization.Formatters.Binary BinaryFormatter namespace System.Runtime.Serialization.Formatters.Soap assembly System.Runtime.Serialization.Formatters.Soap SoapFormatter Serializable objects: Must have SerializableAttribute defined All public and private member fields are serialized – this implies that all of them must be serializable, i.e. have SerializableAttribute defined Fields with NonSerializedAttribute are excluded from default serialization Can implement ISerializable interface to provide their custom serialization public interface IFormatter { void Serialize(Stream serializationStream, object graph); object Deserialize(Stream serializationStream); }

4 Example: Serialization
[Serializable] public class TestSimpleObject { int member1; string member2; string member3; double member4; [NonSerialized] string member5; public TestSimpleObject() member1 = 11; member2 = "hello"; member3 = "hello"; member4 = ; member5 = "hello world!"; } [OnDeserializing] public void SetDefaults(StreamingContext ctx) { member5 = "DefaultValue"; public void Print() Console.WriteLine("member1 = '{0}'", member1); Console.WriteLine("member2 = '{0}'", member2); Console.WriteLine("member3 = '{0}'", member3); Console.WriteLine("member4 = '{0}'", member4); Console.WriteLine("member5 = '{0}'", member5);

5 Example: Serialization, cont.
using System; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Soap; public class Test { public static void Main() TestSimpleObject obj = new TestSimpleObject(); obj.Print(); Stream stream = File.Open("data.xml", FileMode.Create); SoapFormatter formatter = new SoapFormatter(); formatter.Serialize(stream, obj); stream.Close(); obj = null; // stream = File.Open("data.xml", FileMode.Open); obj = (TestSimpleObject) formatter.Deserialize(stream); }

6 Example: Serialization, cont.
Output of SoapFormatter: <SOAP-ENV:Envelope …> <SOAP-ENV:Body> <a1:TestSimpleObject id="ref-1" xmlns:a1=" <member1>11</member1> <member2 id="ref-3">hello</member2> <member3 href="#ref-3"/> <member4> </member4> </a1:TestSimpleObject> </SOAP-ENV:Body> </SOAP-ENV:Envelope> Output of BinaryFormatter:


Download ppt "Advanced .NET Programming II 6th Lecture"

Similar presentations


Ads by Google