Skip to main content

Serialization

Serialization is a process where an object is converted to a form , able to store and transport to different places.
Used for:
to store object to hard drive
send object over the network [Without serialization the remoting will be impossible]
To serialize a class add [Serializable]  attribute in front of the class definition

if you dont want to serialize something in this 'serialized' class use [NonSerialized]  before it
Note: properties are not serialized

To store the data of a class into a file in binary format
    Store myStore = new Store(); // create object of a class to be serialized
    myStore.stockCount = 50; // pass value to the variable
    FileStream flStream = new FileStream("MyStore.dat", FileMode.OpenOrCreate, FileAccess.Write);
    try
    {
        BinaryFormatter binFormatter = new BinaryFormatter(); //to store the data to a file in binary format.
        binFormatter.Serialize(flStream, myStore);        //Seralize method stores the data in streams
    }
    finally
    {
        flStream.Close();
     }

DeSeralize
Store readStore = new Store();
    FileStream flStream = new FileStream("MyStore.dat",
        FileMode.Open, FileAccess.Read);
    try
    {
        BinaryFormatter binFormatter = new BinaryFormatter();
        readStore = (Store)binFormatter.Deserialize(flStream);   //'Deserialize' method returns the deserialized object which we cast to our own class 'Store'
    }
    finally
    {
        flStream.Close();
     }

SOAP formatter
seralizes object to XML file. It is a standardized format which all web services use
- add using and reference to System.Runtime.Serialization.Formatters.Soap
The SOAP format being an XML is readable by humans unlike the binary one. So I wrote a function to show the actual code which the object is converted to.
Here is the code: Store myStore = new Store();
Store myStore = new Store();
MemoryStream memStream = new MemoryStream();
    try
    {
        myStore.stockCount = 50;
        SoapFormatter soapFormatter = new SoapFormatter();
        soapFormatter.Serialize(memStream, myStore);
        byte[] buff = memStream.GetBuffer();
        string soapOutput = "";
        foreach(byte b in buff)
            soapOutput += (char)b;
        tbOutput.Text += Environment.NewLine +                  "Object 'myStore' serialized to SOAP!";
        tbOutput.Text += soapOutput;
    }
    finally
    {
        memStream.Close();
    }
 
Here I use a MemoryStream instead of the FileStream I used previously. This way we save ourselves the use of file.
After we store the data to the stream we get its contents with GetBuffer(). I didn't close the memStream right after the write as I did with the FileStream. This is because we loose the stored data once we close it.
The output we get by the SOAP formatter is this:
http://www.w3.org/2001/XMLSchema-instance
"
 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:clr="http://schemas.microsoft.com/soap/encoding/clr/1.0"
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
   
        http://schemas.microsoft.com/clr/nsassem/

SerializeTest/SerializeTest%2C%20Version%3D1.0.938.186%2C
%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull">
            50
            My local store
       
   

 
serialization - to save information to disk or the registry
Mark your classes with the [Serializable] attribute and there you go. It�s a simple matter of creating a Formatter and a Stream and a couple of lines later it�s done. Alternatively, you could mark up your class with the necessary attributes and use XML Serialization.
ISSUES with Serialization:
-  It forces you to design your classes a certain way
XML serialization only works on public methods and fields, and on classes with public constructors. That means your classes need to be accessible to the outside world. You cannot have private or internal classes, or serialize private data. In addition, it forces restrictions on how you implement collections.
- It is not future-proof for small changes
If you mark your classes as [Serializable], then all the private data not marked as [NonSerialized] will get dumped. You have no control over the format of this data. If you change the name of a private variable, then your code will break.
You can get around this by implementing the ISerializable interface. This gives you much better control of how data is serialized and deserialized.
-It is not future-proof for large changes
Type information is stored as part of the serialization information. If you change your class names or strong-name your assemblies, you�re going to hit all sorts of problems.
5. It is not secure
Using XML serialization is inherently insecure. Your classes need to be public, and they need to have public properties or fields. In addition, XML serialization works by creating temporary files. If you think you�re creating temporary representations of your data (for example, to create a string that you�re going to post to a web service), then files on disk will pose a potential security risk. If, instead, you implement the ISerializable interface and are persisting sensitive internal data, then, even if you�re not exposing private data through your classes, anyone can serialize your data to any file and read it that way, since GetObjectData is a public method.
6. It is inefficient
XML is verbose. And, if you are using the ISerializable interface, type information gets stored along with data. This makes serialization very expensive in terms of disk space.

Comments

Popular posts from this blog

Insufficient access rights to perform the operation. (Exception from HRESULT: 0x80072098)

While accessing the active directory (AD) and authorization manager (AZMAN) , If you get “   Insufficient access rights to perform the operation. (Exception from HRESULT: 0x80072098)  “ message check the    account that is being used to get the LDAP query from AD .  ERROR DETAILS Exception Details:  System.Runtime.InteropServices.COMException: Insufficient access rights to perform the operation. (Exception from HRESULT: 0x80072098) Source Error: Line 154:    'Session("FullName") = System.Security.Principal.WindowsIdentity.GetCurrent.Name.ToString() Line 155: Line 156:    If Not User.IsInRole("Role1") Then Line 157:          Response.Redirect("./Login.aspx") Line 158:    End If  Stack Trace : .... SOLVE IT Steps to do check the app pool rights: Click on the website name that you are having problem with in IIS  In the right panel you will see 'Basic Settings'. Click It. Select the specific pool option and enter the name of the ac

Sql Server database Read_Only / Read_Write

The ALTER DATABASE command allows a database administrator to modify SQL Server databases and their files and filegroups. This includes permitting the changing of database configuration options. Why Read Only ? When you need to ensure that the data is a database is not modified by any users or automated processes, it is useful to set the database into a read-only mode. Once read-only, the data can be read normally but any attempts to create, updated or delete table rows is disallowed. This makes the read-only mode ideal when preparing for data migration, performing data integrity checking or when the data is only required for historical reporting purposes. Make Database Read Only USE  [master] GO ALTER DATABASE  [TESTDB]  SET  READ_ONLY  WITH  NO_WAIT GO Make Database Read/Write USE  [master] GO ALTER DATABASE  [TESTDB]  SET  READ_WRITE  WITH  NO_WAIT GO In case you get the following error message make the database single user: Msg 5070, Level 16, Stat

Do's and Don't SQL

Do's: Writing comments whenever something is not very obvious, as it won’t impact the performance.  (--) for single line  (/*…*/) to mark a section Use proper indentation Use Upper Case for all SQL keywords. SELECT, UPDATE, INSERT, WHERE, INNER JOIN, AND, OR, LIKE. Use BEGIN... END block for multiple statements in conditional code  Use Declare and Set in beginning of Stored procedure Create objects in same database where its relevant table exists otherwise it will reduce network performance. Use PRIMARY key in WHERE condition of UPDATE or DELETE statements as this will avoid error possibilities. If User table references Employee table than the column name used in reference should be UserID where User is table name and ID primary column of User table and UserID is reference column of Employee table. Use select column name instead of select * Use CTE (Common Table Expression); its scope is limited to the next statement in SQL query, instead of temporary tables and der