How to compress ASP.NET ViewState

In this example I will show you how to compress ASP.NET web page ViewState. The ViewState is used to save page state between requests, if you have a page with a large amount of controls you could end up with a bloated ViewState. We will create an abstract class that can be reused within your application.

This class which handles all the GZip compression functionality


using System.IO;
using System.IO.Compression;

namespace CompressViewStateTestApp
{
    public class GZip
    {
        public static byte[] Compress(byte[] data)
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (GZipStream gZipStream = new GZipStream(memoryStream, CompressionMode.Compress, true))
                {
                    gZipStream.Write(data, 0, data.Length);
                    gZipStream.Close();
                }
                return memoryStream.ToArray();
            }
        }

        public static byte[] Decompress(byte[] data)
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                memoryStream.Write(data, 0, data.Length);
                memoryStream.Position = 0;
                using (GZipStream gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress, true))
                {
                    using (MemoryStream stream = new MemoryStream())
                    {
                        byte[] buffer = new byte[64];
                        int read = -1;
                        read = gZipStream.Read(buffer, 0, buffer.Length);
                        while (read > 0)
                        {
                            stream.Write(buffer, 0, read);
                            read = gZipStream.Read(buffer, 0, buffer.Length);
                        }
                        gZipStream.Close();
                        return stream.ToArray();
                    }
                }
            }
        }
    }
}

This is our abstract page class, it overrides the SavePageStateToPersistenceMedium method and the LoadPageStateFromPersistenceMedium method.


using System;
using System.IO;
using System.Web.UI;

namespace CompressViewStateTestApp
{
    public abstract class CompressedViewStatePage : Page
    {
        private readonly ObjectStateFormatter _objectStateFormatter =
            new ObjectStateFormatter();

        protected override void SavePageStateToPersistenceMedium(object viewState)
        {
            byte[] viewStateArray;
            using (MemoryStream memoryStream = new MemoryStream())
            {
                _objectStateFormatter.Serialize(memoryStream, viewState);
                viewStateArray = memoryStream.ToArray();
            }
            ClientScript.RegisterHiddenField("__COMPRESSEDVIEWSTATE",
                                             Convert.ToBase64String(GZip.Compress(viewStateArray)));
        }

        protected override object LoadPageStateFromPersistenceMedium()
        {
            string viewState = Request.Form["__COMPRESSEDVIEWSTATE"];
            byte[] bytes = Convert.FromBase64String(viewState);
            bytes = GZip.Decompress(bytes);
            return _objectStateFormatter.Deserialize(Convert.ToBase64String(bytes));
        }
    }
}

This is an example has a DataGrid


Then lets bind all the CultureInfo to the DataGrid


using System;
using System.Globalization;

namespace CompressViewStateTestApp
{
    public partial class CompressedPage : CompressedViewStatePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            GridCulture.DataSource = CultureInfo.GetCultures(CultureTypes.AllCultures);
            GridCulture.DataBind();
        }
    }
}

Usually this could generate a page size of 156KB, but when using the GZip compression the page size is reduced to 88KB.

Obviously there is increased CPU overhead to do this, but generally CPU power is cheap these days and people expect quick, slick and responsive web applications.

You can download the GZip Compressed ViewState Project here



Comments

No comments yet.

Add Yours

  • Author Avatar

    YOU


Comment Arrow




About Author

Robert

Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning hands down.