How to compress viewstate

Source: Internet
Author: User

FW: http://www.dotnetbips.com/articles/22d33d11-1a75-42c8-bbf6-ca1a345d3fcf.aspx

 

 

Introduction

Developers often worry about performance of their web sites. every developer wants that his Web site be optimized for good performance. there are several factors affecting performance of your web site and one of them is viewstate. in this article I am going
To show a way by which you can compress viewstate thus improving the performance.

What is viewstate?

Though this article is not intended to define strate what viewstate is Let's quickly discuss it. if you see HTML source of your web forms you will find a hidden form field named _ viewstate. clever ASP. net persists control values in this hidden field helping
You to preserve them into SS post backs. no doubt viewstate is helpful. however, at times viewstate can create performance issues. since viewstate is transferred between browser and server with each request it adds to network bandwidth.

 

One way to reduce the viewstate data flowing over the wire is to turn viewstate off. all the Web server controls have a property called enableviewstate. setting this property to false will disable viewstate for that control. however, without viewstate all
The job of State persistence comes on your shoulders and can be painful at times. another option, which the theme of this article, is to compress the viewstate before serializing it on the network. this way the amount of data on the wire will be substantially
Less.

In ASP. net 1.x people used this compression technique with custom code because there was no inbuilt way. the. NET 2.0, however, makes your life easy by providing system. io. compression namespace. the gzipstream class from system. io. compression comes handy
In compressing and decompressing streams. note that gzipstream works with only one stream at a time. the gzipstream class is not specifically designed for viewstate as such but we are going to harness its functionality for compressing and decompressing viewstate.

Creating viewstatehelper

To begin with, create a new web site using Visual Studio. Then add a class called viewstatehelper in its app_code folder. At the top of the class import namespaces as shown below:

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

The system. Io namespace provides stream classes such as memorystream. The system. Io. Compression namespace provides gzipstream class that allows you to represent data in GZIP format (RFC 1952 ).

Compressing data

Now add a method called compress () as shown below:

public static byte[] Compress(byte[] data){MemoryStream ms = new MemoryStream();GZipStream stream = new GZipStream(ms, CompressionMode.Compress);stream.Write(data, 0, data.Length);stream.Close();return ms.ToArray();}

The compress () Static Method accepts a byte array to be compressed and returns compressed byte array. it creates an instance of memorystream class. the memorystream class represents a stream in memory. it then creates gzipstream object by passing memorystream
And compression mode of compress. instead of memorystream you coshould have passed any type of stream. the compressed data is written to this stream. the write () method of gzipstream class accepts a byte array, compresses it and writes it to the supplied stream
(Memorystream in our case). After writing the data gzipstream is closed. Finally, toarray () method of memorystream class converts the underlying stream data into byte array.

Decompressing data

In order to decompress data add another method called decompress () and key in the following code in it:

public static byte[] Decompress(byte[] data){MemoryStream ms = new MemoryStream();ms.Write(data, 0, data.Length);ms.Position = 0;GZipStream stream = new GZipStream(ms, CompressionMode.Decompress);MemoryStream temp = new MemoryStream();byte[] buffer=new byte[1024];while (true){int read = stream.Read(buffer, 0, buffer.Length);if (read <= 0){break;}else{temp.Write(buffer, 0, buffer.Length);}}stream.Close();return temp.ToArray();}

The decompress () method accepts byte array of compressed data and returns its decompressed version. first, it creates a memorystream and writes compressed byte array to it. this stream is then supplied to gzipstream constructor. notice that this time compression
Mode is decompress. the decompressed data also needs to be stored somewhere. the Code creates another memorystream for this purpose. a while loop reads decompressed data from gzipstream In the chunks of 1024 bytes at a time. this data is then written to
Memorystream. Finally, gzipstream is closed and contents of decompressed memorystream are returned to the caller as byte array.

This completes the viewstatehelper class. Now you need to put this class in use for compressing and decompressing viewstate.

Creating a web form

Now open the default web form and drag and drop one SQL data source control on it. configure it to select all records from MERs table of northwind database.

Drag and Drop a gridview control and set its performanceid property to the ID of SQL data source control you Just configured. run the web form so as to ensure that it is working as expected. the following figure shows a sample run of the web form

Customizing viewstate serialization

Most of the times you don't interfere with viewstate serialization and deserialization mechanisms at all. however, since you wish to compress the viewstate you need to customize the way viewstate is serialized and deserialized. the page base class has two
Virtual Methods viz. savepagestatetopersistencemedium () and loadpagestatefrompersistencemedium (). Together they allow you to customize viewstate serialization and deserialization respectively.

Go in the code behind of the web form and override savepagestatetopersistencemedium () method first. You will compress viewstate and store it in a hidden variable in this method. The following code shows this method.

protected override voidSavePageStateToPersistenceMedium(object state){LosFormatter formatter = new LosFormatter();StringWriter writer = new StringWriter();formatter.Serialize(writer, state);string viewState = writer.ToString();byte[] data = Convert.FromBase64String(viewState);byte[] compressedData = ViewStateHelper.Compress(data);string str = Convert.ToBase64String(compressedData);ClientScript.RegisterHiddenField("__MYVIEWSTATE", str);}

The specified () method accepts an object that represents the viewstate data. Inside it creates losformatter object. The losformatter class allows you to serialize and deserialize data in viewstate compatible format. The serialize ()
Method of losformatter class accepts a stream where data is to be serialized and the State object. in our example we serialize the data into a stringwriter. the tostring () method of stringwriter returns a string that represents viewstate data in string form.
This string data is in base64 format (this how ASP. net stores the viewstate) and need to be converted into a plain string. the frombase64string () method of convert class does this job. the return value of frombase64string () method is a byte array which is then
Compressed using compress () method of viewstatehelper class. the compressed byte array is again converted into its base64 representation using tobase64string () method of convert class. finally, a hidden field named _ myviewstate is emitted using registerhiddenfield ()
Method of clientscript member with its value set to the compressed base64 string.

Compressing viewstate data is just one side of the coin. equally important is to decompress it back so that ASP. net can work with it further. this is done by overriding loadpagestatefrompersistencemedium () method as shown below:

protected override objectLoadPageStateFromPersistenceMedium(){string viewstate = Request.Form["__MYVIEWSTATE"];byte[] data = Convert.FromBase64String(viewstate);byte[] uncompressedData =ViewStateHelper.Decompress(data);string str = Convert.ToBase64String(uncompressedData);LosFormatter formatter = new LosFormatter();return formatter.Deserialize(str);}

The method retrieves _ myviewstate hidden field from Form collection. this field contains compressed version of The viewstate in base64 format. in order to decompress it you need to convert it into a byte array first. this is done via frombase64string ()
Method of convert class. then decompress () method of viewstatehelper decompresses the data. the decompressed data is again converted into a base64 string using tobase64string () method of convert class. finally, losformatter instance deserializes the decompressed
Viewstate.

That's it! Your viewstate compression scheme is now ready. During my testing I observed that the uncompressed viewstate was 13,568 bytes whereas the compressed viewstate was 5,932 bytes. A great deal of saving. Isn't it?

Summary

In this article you learned to improve performance of your web forms by compressing viewstate data. the new gzipstream class offers a ready made way to compress data in GZIP format. the compressed viewstate needs to be saved by overriding savepagestatetopersistencemedium ()
Method of page base class. Similarly, loadpagestatefrompersistencemedium () needs to be overridden for decompressing and loading the viewstate back.

 

Http://www.engao.com/home.php? MoD = Space & uid = 12833 & Do = Blog & id = 902 related articles

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.