Compressing viewstate in asp.net

Viewstate as we know basically is a serialized data which stores in pages in the form of hidden fields. As we know that viewstate stores in the page so it makes page size larger (increase page data size), so if your viewstate is not much there is no problem but if viewstate is enough larger then it would be the cause of slower page load and decrease
website performance, then there is the need of viewstate compression to minimizing viewstate size as much as possible.

How to compress and uncompress viewstate data is the question arising in our mind first and when to compress viewstate which would be able to make page performance faster than before, So here is the code for minimizing viewstate size as much possible, but beware, we are minimizing viewstate size by the code only for increasing page performance and decreasing page data size not for decreasing performance so please don't create overhead (don't compress, uncompress viewstate) if viewstate is not as much larger as it would be the cause the slower performance.

Paste the given code on the page for which you want to minimizing viewstate size.
use the following namespace for code working properly.

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



private ObjectStateFormatter osFormatter = new ObjectStateFormatter();
private static byte[] Compress(byte[] data)
{
    MemoryStream outputCompress = new MemoryStream();
    GZipStream compressStream = new GZipStream(outputCompress, CompressionMode.Compress, true);
    compressStream.Write(data, 0, data.Length);
    compressStream.Close();
    return outputCompress.ToArray();
}
private static byte[] Uncompress(byte[] data)
{
    MemoryStream compressedData = new MemoryStream();
    compressedData.Write(data, 0, data.Length);
    compressedData.Position = 0;
    GZipStream compressStream = new GZipStream(compressedData, CompressionMode.Decompress, true);
    MemoryStream uncompressedData = new MemoryStream();
    byte[] buffer = new byte[data.Length];
    int read = compressStream.Read(buffer, 0, buffer.Length);

    while (read > 0)
    {
        uncompressedData.Write(buffer, 0, read);
        read = compressStream.Read(buffer, 0, buffer.Length);
    }
    compressStream.Close();
    return uncompressedData.ToArray();
}
protected override void SavePageStateToPersistenceMedium(object viewState)
{
    MemoryStream ms = new MemoryStream();
    osFormatter.Serialize(ms, viewState);
    byte[] viewStateArray = ms.ToArray();
    ClientScript.RegisterHiddenField("__COMPRESSED_VIEWSTATE", Convert.ToBase64String(Compress(viewStateArray)));
}
protected override object LoadPageStateFromPersistenceMedium()
{
    var compressedViewState = Request.Form["__COMPRESSED_VIEWSTATE"];
    var bytes = Uncompress(Convert.FromBase64String(compressedViewState));
    return osFormatter.Deserialize(Convert.ToBase64String(bytes));
}



Popular Posts