DotNetLines Blogs

DotNetLines Blog

Compress and Decompress ViewState in ASP.NET

Feb 10

Written by:
2/10/2014 2:54 AM  RssIcon





Page ViewState is one of the important criteria for better performance of a page. In most of the ASP.NET web applications the page size increases because of the unmanaged ViewState size. Some Viewstate sizes range in several MBs, which results in increased page size and slower page load. It also affects other factors such as slow postback of the page.

We have already seen some of the posts like,Creating a custom ASP.NET Web Control - Email Textbox, Import Microsoft Word file to ASP.NET Webpage, A Simple way to export data from a DataTable to MS Excel fileA Simple way to export data from a DataTable to MS Excel fileCreate a simple Pie Chart in ASP.NET using C#, Create a simple Column Chart / Bar Chart in ASP.NET using C#, Re-size an image by keeping its aspect ratio in jQuery, Re-size an image by maintaining its aspect ratio, Avoid Skype toolbar to Phone/Fax number.

There are different ways to reduce the ViewState size such as

1. Disable ViewState on respective pages or user controls using EnableViewState=”false” property.

2. Disable ViewState for individual Server side control

3. Compress/Decompress ViewState

4. Save ViewState in a file and read back when required

5. Save ViewState to in database and read back when required

In this post we will see how to Compress and Decompress the ViewState and use it in an ASP.NET Web Application

In order to understand this post, install the following firebug extensions.

1. Firebug

2. ViewState Size

 

Implementation

I. Create a New ASP.NET Project in Visual Studio and create following form in one of the pages

<form id="form1" runat="server">

    <div>

        <asp:Label ID="lblUserName" runat="server" Text="Username:"></asp:Label>

        <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>

        <br />

        <br />

        <asp:Label ID="lblPassword" runat="server" Text="Password:"></asp:Label>

        <asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>

        <br />

        <br />

        <asp:Button ID="btnLogin" runat="server" Text="Login" />

        <br />

        <asp:LinkButton ID="lnkForgotPassword" runat="server" Text="Forgot Password" />

    </div>

</form>

Execute the application in Mozilla Firefox and check the Viewstate size and page loading time as shown in following screenshot.

 

II. Now add one class file in you App_Code directory and copy the following methods in it.

 

using System.IO;

using System.IO.Compression;

 

namespace ViewStatePOC

{

    public class ViewStateCompressor

    {

        public static byte[] CompressViewState(byte[] viewStateData)

        {

            MemoryStream output = new MemoryStream();

            GZipStream gzip = new GZipStream(output,

                              CompressionMode.Compress, true);

            gzip.Write(viewStateData, 0, viewStateData.Length);

            gzip.Close();

            return output.ToArray();

        }

 

        public static byte[] DecompressViewState(byte[] viewStateData)

        {

            MemoryStream input = new MemoryStream();

            input.Write(viewStateData, 0, viewStateData.Length);

            input.Position = 0;

            GZipStream gzip = new GZipStream(input,

                              CompressionMode.Decompress, true);

            MemoryStream output = new MemoryStream();

            byte[] buffer = new byte[64];

            int bytes = -1;

            bytes = gzip.Read(buffer, 0, buffer.Length);

            while (bytes > 0)

            {

                output.Write(buffer, 0, bytes);

                bytes = gzip.Read(buffer, 0, buffer.Length);

            }

            gzip.Close();

            return output.ToArray();

        }

    }

}

 

III. Write the following code in codebehind of the page where you want to Compress and Decompress the ViewState.

These methods have to be overriden from System.Web.UI.Page class.

Method LoadPageStateFromPersistenceMedium Compress the ViewState and another method SavePageStateToPersistenceMedium Decompress the ViewState.

 

using System;

using System.IO;

using System.Web.UI;

 

public partial class Index : System.Web.UI.Page

    {

        protected override void SavePageStateToPersistenceMedium(object viewState)

        {

            LosFormatter formatter = new LosFormatter();

            StringWriter writer = new StringWriter();

            formatter.Serialize(writer, viewState);

            string viewStateString = writer.ToString();

            byte[] bytes = Convert.FromBase64String(viewStateString);

            bytes = ViewStateCompressor.CompressViewState(bytes);

            ClientScript.RegisterHiddenField("__MYVIEWVSTATE", Convert.ToBase64String(bytes));

        }

        protected override object LoadPageStateFromPersistenceMedium()

        {

            string viewState = Request.Form["__MYVIEWSTATE"];

            byte[] bytes = Convert.FromBase64String(viewState);

            bytes = ViewStateCompressor.DecompressViewState(bytes);

            LosFormatter formatter = new LosFormatter();

            return formatter.Deserialize(Convert.ToBase64String(bytes));

        }

        protected void Page_Load(object sender, EventArgs e)

        {

        }

        protected void Page_Load(object sender, EventArgs e)

        {

 

        }

    }

Now run the project again and check the ViewState size and page load time.

You can easily identify that Viewstate size and Page loading time is almost negligible. Use this technic for larger pages and see the magic.


Copyright ©2014

Categories:
Location: Blogs Parent Separator ASP.NET

Your name:
Gravatar Preview
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Security Code
CAPTCHA image
Enter the code shown above in the box below
Add Comment   Cancel 

New_Blog

You must be logged in and have permission to create or edit a blog.