ComponentOne Zip for .NET
Zip for .NET Tutorials / Compressed Serialization
In This Topic
    Compressed Serialization
    In This Topic

    This tutorial shows how you can serialize objects in compressed files, and then load them back into the memory.

    The sample creates a data table using the NorthWind database. The table is saved (serialized) into regular and compressed streams. Finally, the data is loaded back from either stream. Here is what the final application will look like:


    Step 1: Create the main form.

    Start a new Visual Studio project and from the Toolbox, add the following controls to the form:

    Step 2: Add references and Imports statements.

    Go to the Solution Explorer window and click the Show All Files button. Right-click on References, and select the Add Reference menu option. Select the C1.C1Zip assembly from the list, or browse to find the C1.C1Zip.2.dll file.

    Select the Form1.vb tab (Form1.cs in C#) or go to View|Code to open the Code Editor. At the top of the file, add the following statements:

    To write code in Visual Basic

    Visual Basic
    Copy Code
    Imports System.IO
    Imports System.Data.OleDb
    Imports System.Runtime.Serialization.Formatters.Binary
    Imports C1.C1Zip
    

    To write code in C#

    C#
    Copy Code
    using System.IO;
    using System.Data.OleDb;
    using System.Runtime.Serialization.Formatters.Binary;
    using C1.C1Zip;
    

    This declares the namespaces of the classes used in the project.

    Step 3: Declare constants.

    In the Code Editor of the form, type or copy the following lines in the body of the form implementation:

    To write code in Visual Basic

    Visual Basic
    Copy Code
    Private Const FN_REGULAR = "\DataTable.regular"
    Private Const FN_COMPRESSED = "\DataTable.compressed"
    Private Const MDBFILE = " C:\Users\\Documents\ComponentOne Samples\common\C1NWIND.MDB"
    

    To write code in C#

    C#
    Copy Code
    private const string FN_REGULAR = @"\DataTable.regular";
    private const string FN_COMPRESSED = @"\DataTable.compressed";
    private const string MDBFILE = @"C C:\Users\\Documents\ComponentOne Samples\common\C1NWIND.MDB";
    

    These constants define the name of the database used to populate the data table and the file names used to serialize the data.

    Step 4: Add code to create the data table.

    Add the following code to handle the Click event for the Create Data Table button:

    To write code in Visual Basic

    Visual Basic
    Copy Code
    Private Sub btnCreate_Click(sender As Object,e As EventArgs) Handles btnCreate.Click
     
        ' Open the table.
        Dim conn As String
        conn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & MDBFILE & ";"
        Dim rs As String = "select * from customers"
         ' Show status.
        Cursor = Cursors.WaitCursor
        ToolStripStatusLabel1.Text = "Loading data from mdb file..."
         ' Load data.
        Dim da As OleDbDataAdapter = New OleDbDataAdapter(rs, conn)
        Dim ds As DataSet = New DataSet()
        Try
            da.Fill(ds)
        Catch
            MessageBox.Show("Could not load data from " + MDBFILE)
        End Try
         ' Show status.
        Cursor = Cursors.Default
        ToolStripStatusLabel1.Text = "Loaded " & ds.Tables(0).Rows.Count & " records from mdb file."
         ' Bind to the grid.
        DataGridView1.DataSource = ds.Tables(0)
         ' Enable the save button.
        btnSave.Enabled = True
    End Sub
    

    To write code in C#

    C#
    Copy Code
    private void btnCreate_Click(object sender,EventArgs e)
    {
         // Open the table.
        string conn =  "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + MDBFILE + ";";
        string rs = "select * from customers";
         // Show status.
        Cursor = Cursors.WaitCursor;
        toolStripStatusLabel1.Text = "Loading data from mdb file...";
         // Load data.
        OleDbDataAdapter da = new OleDbDataAdapter(rs, conn);
        DataSet ds = new DataSet();
        try
        {
            da.Fill(ds);
        }
        catch
        {
            MessageBox.Show("Could not load data from " + MDBFILE);
        }
         // Show status.
        Cursor = Cursors.Default;
        toolStripStatusLabel1.Text = "Loaded " + ds.Tables[0].Rows.Count +  " records from mdb file.";
         // Bind to the grid.
        dataGridView1.DataSource = ds.Tables[0];
         // Enable the save button.
        btnSave.Enabled = true;
    }
    

    The function uses standard ADO.NET objects and methods to create and populate a DataTable object, which is then bound to the DataGrid control.

    Step 5: Add code to save the data table.

    Add the following code to handle the Click event for the Save Data Table button:

    To write code in Visual Basic

    Visual Basic
    Copy Code
    Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
         ' Get the data table from the grid.
        Dim dt As DataTable = DataGridView1.DataSource
         ' Show status.
        Cursor = Cursors.WaitCursor
        ToolStripStatusLabel1.Text = "Serializing data to regular file..."
         ' Serialize the data set to a regular file.
        Dim fn As String = Application.StartupPath + FN_REGULAR
        Dim fs As FileStream = New FileStream(fn, FileMode.Create)
        Dim bf As BinaryFormatter = New BinaryFormatter()
        bf.Serialize(fs, dt)
        Dim lenRegular As Long = fs.Length
        fs.Close()
         ' Show status.
        Cursor = Cursors.WaitCursor
        ToolStripStatusLabel1.Text = "Serializing data to compressed file..."
         ' Serialize the data set to a compressed file.
        fn = Application.StartupPath & FN_COMPRESSED
        fs = New FileStream(fn, FileMode.Create)
        Dim compressor As C1ZStreamWriter = New C1ZStreamWriter(fs)
        bf = New BinaryFormatter()
        bf.Serialize(compressor, dt)
        Dim lenCompressed As Long = fs.Length
        fs.Close()
         ' Show status.
        Cursor = Cursors.Default
        ToolStripStatusLabel1.Text = string.Format( "Saved to regular file ({0:#,###} bytes) and " & "compressed file ({1:#,###} bytes)", lenRegular, lenCompressed)
         ' Enable the load buttons.
        btnLoad.Enabled = True
        btnLoadCompressed.Enabled = True
    End Sub
    

    To write code in C#

    C#
    Copy Code
    private void btnSave_Click(object sender, EventArgs e)
    {
         // Get the data table from the grid.
         DataTable dt = (DataTable)dataGridView1.DataSource;
         // Show status.
        Cursor = Cursors.WaitCursor;
        toolStripStatusLabel1.Text = "Serializing data to regular file...";
         // Serialize the data set to a regular file.
        string fn = Application.StartupPath + FN_REGULAR;
        FileStream fs = new FileStream(fn, FileMode.Create);
        BinaryFormatter bf = new BinaryFormatter();
        bf.Serialize(fs, dt);
        long lenRegular = fs.Length;
        fs.Close();
         // Show status.
        Cursor = Cursors.WaitCursor;
        toolStripStatusLabel1.Text = "Serializing data to compressed file...";
         // Serialize the data set to a compressed file.
        fn = Application.StartupPath + FN_COMPRESSED;
        fs = new FileStream(fn, FileMode.Create);
        C1ZStreamWriter compressor = new C1ZStreamWriter(fs);
        bf = new BinaryFormatter();
        bf.Serialize(compressor, dt);
        long lenCompressed = fs.Length;
        fs.Close();
         // Show status.
        Cursor = Cursors.Default;
        toolStripStatusLabel1.Text = string.Format("Saved to regular file ({0:#,###} bytes) and " + "compressed file ({1:#,###} bytes)", lenRegular, lenCompressed);
         // Enable the load buttons.
        btnLoad.Enabled = true;
        btnLoadCompressed.Enabled = true;
    }
    

    The first set of code serializes the DataTable into a regular file, and the second serializes the DataTable into a compressed file. Note that only one additional line is required to compress the data.

    In both cases, the serialization is executed by the BinaryFormatter object. The only difference is that in the first case, the Serialize method is called with a regular file stream as a parameter; in the second, a C1ZStreamWriter is used instead.

    Step 6: Add code to load the data table from the regular file.

    Add the following code to handle the Click event for the Load Data Table button:

    To write code in Visual Basic

    Visual Basic
    Copy Code
    Private Sub btnLoad_Click(sender As Object, e As EventArgs) Handles btnLoad.Click
         ' Clear grid, show status.
        Cursor = Cursors.WaitCursor
        DataGridView1.DataSource = Nothing
        ToolStripStatusLabel1.Text = "Loading from regular file..."
         ' Deserialize from regular file.
        Dim fn As String = Application.StartupPath & FN_REGULAR
        Dim fs As FileStream = New FileStream(fn, FileMode.Open)
        Dim ticks As Long = DateTime.Now.Ticks
        Dim bf As BinaryFormatter = New BinaryFormatter()
        Dim dt As DataTable = bf.Deserialize(fs)
        Dim ms As Long = (DateTime.Now.Ticks - ticks) / TimeSpan.TicksPerMillisecond
        fs.Close()
         ' Show result.
        Cursor = Cursors.Default
        DataGridView1.DataSource = dt
        ToolStripStatusLabel1.Text = "Loaded from regular file in " & ms.ToString() & " ms."
    End Sub
    

    To write code in C#

    C#
    Copy Code
    private void btnLoad_Click(object sender, EventArgs e)
    {
         // Clear grid, show status.
        Cursor = Cursors.WaitCursor;
        dataGridView1.DataSource = null;
        toolStripStatusLabel1.Text = "Loading from regular file...";
         // Deserialize from regular file.
        string fn = Application.StartupPath + FN_REGULAR;
        FileStream fs = new FileStream(fn, FileMode.Open);
        long ticks = DateTime.Now.Ticks;
        BinaryFormatter bf = new BinaryFormatter();
        DataTable dt = (DataTable)bf.Deserialize(fs);
        long ms = (DateTime.Now.Ticks - ticks) / TimeSpan.TicksPerMillisecond;
        fs.Close();
         // Show result.
        Cursor = Cursors.Default;
        dataGridView1.DataSource = dt;
        toolStripStatusLabel1.Text = "Loaded from regular file in " + ms.ToString() + " ms.";
    }
    

    The first main line of code creates a new BinaryFormatter object and the second one calls its Deserialize method. The Deserialize method takes a single parameter: the stream in which the object is defined. In this case, the stream is a regular file stream.

    Step 7: Add code to load the data table from the compressed file.

    Add the following code to handle the Click event for the Load Compressed Data Table button:

    To write code in Visual Basic

    Visual Basic
    Copy Code
    Private Sub btnLoadCompressed_Click(sender As Object, e As EventArgs) Handles btnLoadCompressed.Click
         ' Clear grid, show status.
        Cursor = Cursors.WaitCursor
        DataGridView1.DataSource = Nothing
        ToolStripStatusLabel1.Text = "Loading from compressed file..."
         ' Deserialize from compressed file.
        Dim fn As String = Application.StartupPath + FN_COMPRESSED
        Dim fs As FileStream = New FileStream(fn, FileMode.Open)
        Dim ticks As Long   = DateTime.Now.Ticks
        Dim decompressor As C1ZstreamReader
        decompressor = New C1ZStreamReader(fs)
        Dim bf As BinaryFormatter = New BinaryFormatter()
        Dim dt As DataTable = bf.Deserialize(decompressor)
        Dim ms As Long = (DateTime.Now.Ticks - ticks) / TimeSpan.TicksPerMillisecond
        fs.Close()
         ' Show result.
        Cursor = Cursors.Default
        DataGridView1.DataSource = dt
        ToolStripStatusLabel1.Text = "Loaded from compressed file in " & ms.ToString() & " ms."
    End Sub
    

    To write code in C#

    C#
    Copy Code
    private void btnLoadCompressed_Click(object sender, EventArgs e)
    {
         // Clear grid, show status.
        Cursor = Cursors.WaitCursor;
        dataGridView1.DataSource = null;
        toolStripStatusLabel1.Text = "Loading from compressed file...";
         // Deserialize from compressed file.
        string fn = Application.StartupPath + FN_COMPRESSED;
        FileStream fs = new FileStream(fn, FileMode.Open);
        long ticks = DateTime.Now.Ticks;
        C1ZStreamReader decompressor;
        decompressor = new C1ZStreamReader(fs);
        BinaryFormatter bf = new BinaryFormatter();
        DataTable dt = (DataTable)bf.Deserialize(decompressor);
        long ms = (DateTime.Now.Ticks - ticks) / TimeSpan.TicksPerMillisecond;
        fs.Close();
         // Show result.
        Cursor = Cursors.Default;
        dataGridView1.DataSource = dt;
        toolStripStatusLabel1.Text = "Loaded from compressed file in " + ms.ToString() + " ms.";
    }
    

    The main lines are similar to the code used to deserialize data from a regular file. The only difference is that instead of passing a regular file stream to the Deserialize method, we now use a C1ZStreamReader object.

    This concludes the Compressed Serialization tutorial.