ViewState Compression

Mar 3, 2009 at 10:02 AM
Hi Stefan,
I implement a viewstate compression in your control:
First, the gzip ode:
        public static byte[] Compress(byte[] data)
        {
            MemoryStream output = new MemoryStream();
            GZipStream gzip = new GZipStream(output,
                              CompressionMode.Compress, true);
            gzip.Write(data, 0, data.Length);
            gzip.Close();
            return output.ToArray();
        }

        public static byte[] Decompress(byte[] data)
        {
            MemoryStream input = new MemoryStream();
            input.Write(data, 0, data.Length);
            input.Position = 0;
            GZipStream gzip = new GZipStream(input,
                              CompressionMode.Decompress, true);
            MemoryStream output = new MemoryStream();
            byte[] buff = new byte[64];
            int read = -1;
            read = gzip.Read(buff, 0, buff.Length);
            while (read > 0)
            {
                output.Write(buff, 0, read);
                read = gzip.Read(buff, 0, buff.Length);
            }
            gzip.Close();
            return output.ToArray();
        }

Now, we've just to compress viewstate in PartialPageStatePersister :
        public override void Load()
        {
            if (!string.IsNullOrEmpty(PageState))
            {
                LosFormatter format = new LosFormatter();

                try
                {
                    byte[] bytes = Convert.FromBase64String(PageState);
                    bytes = WebControlHelper.Decompress(bytes);

                    Pair pair = (Pair)format.Deserialize(Convert.ToBase64String(bytes));
                    base.ViewState = pair.First;
                    base.ControlState = pair.Second;
                }
                catch (ArgumentException)
                {
                }
            }
        }

        public override void Save()
        {
            if (ViewState != null || ControlState != null)
            {
                string pageState = "";

                if ((base.ViewState != null) || (base.ControlState != null))
                {
                    LosFormatter format = new LosFormatter();
                    StringWriter writer = new StringWriter();

                    format.Serialize(writer, new Pair(ViewState, ControlState));

                    byte[] bytes = Convert.FromBase64String(writer.ToString());
                    bytes = WebControlHelper.Compress(bytes);

                    pageState = Convert.ToBase64String(bytes);
                }

                PageState = pageState;
            }
        }