Skip to main content

Posts

Showing posts with the label Serialization

Custom Object Serialization in .Net

Namespace: System.Runtime.Serialization In a very complex object creation scenario we may want to implement serialization our self. To do custom serialization one must apply the serialization attributes to the class in the same way and also class must implement ISerializable interface. Constructor to be implemented should look like: Protected <ClassName>(SerializationInfo si, StreamingContext sc) {                 productid = info.GetInt32(“Product ID”);                 productprice = info.GetInt32(“Price”); productQuantity = info.GetInt32(“Quantity”); total = productprice * productQuantity; } For Deserialization implement the method: [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] public virtual void GetObjectData(SerializationInfo info, StreamContext contex...

XML Serialization in .Net

Namespace: System.XML.Serialization It provides Greater interoperability, More Administrative friendly, better forward-compatibility. Using XML Serialization: FileStream fs = new FileStream(“FileStream.xml”, FileMode.Create); XmlSerializer xs = new XmlSerializer(typeof(DateTime)); //Optional to specify xs.Serilize(fs,System.DateTime.Now); Fs.close(); Deserializing objects: FileStream fs = new FileStream(“FileStream.xml”, FileMode.Open); XmlSerializer xs = new XmlSerializer(typeof(DateTime)); //Optional to specify Console.WriteLine(“Previouse Date : ” + (DateTime)xs.Deserialize(fs)); Fs.close(); Rules for XML Serialization: • Specify the class as public • A public parameter less Constructor • Members to be serialized must be public. XML Serialization can be controlled using XmlAnyAttribute , XmlAnyElement , XmlArray , XmlArrayItem , XmlAttribute , XmlChoiceIdentifier , XmlElement , XmlEnum , XmlIgnore , XmlInclude , XmlRoot , Xml...

Data Serialization in .Net

Namespace: System.Runtime.Serialization Serialization is the process of converting object so that they can be transmitted over the network, or stored in file for later use, or passing them to a web service or any other application. .Net WebServices, Session Object, .Net Remoting and clipboard rely on Serialization. Binary Serialization: It’s efficient but not portable solution. String data = “Hello”; FileStream fs = new FileStream(“FileStream.Data”, FileMode.Create); BinaryFormatter bf = new BinarFormatter (); Bf.Serilize(fs, data); //Wrting Objects Bf.Serilize(fs,System.DateTime.Now); Fs.close(); Deserializing Objects FileStream fs = new FileStream(“FileStream.Data”, FileMode.Open); BinaryFormatter bf = new BinarFormatter (); String Data = (String)bf.Deserialize(fs); DateTime vTime = (DateTime) bf.Derialize(fs); To serialize a class one must the Serializeable attribute to that class. To omit some attribute from deseriali...