Rank: Administration Groups: Administration
Joined: 4/5/2009 Posts: 7
|
The common practice of compressing viewstate and adding to the client controls collection using ClientScript.RegisterHiddenField will cause issues with some third party controls. Use the following code instead.
Create new compressor class.
public static class Compressor { 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(); }
Add the following to page (or to a base page if you have one)
protected override object LoadPageStateFromPersistenceMedium () { String alteredViewState; byte[] bytes; Object rawViewState; LosFormatter formatter = new LosFormatter(); this.PageStatePersister.Load(); alteredViewState = this.PageStatePersister.ViewState.ToString(); bytes = Convert.FromBase64String(alteredViewState); bytes = Compressor.Decompress(bytes); rawViewState = formatter.Deserialize(Convert.ToBase64String(bytes)); return new Pair(this.PageStatePersister.ControlState, rawViewState);
}
protected override void SavePageStateToPersistenceMedium (object viewState) {
LosFormatter formatter = new LosFormatter(); using (StringWriter writer = new StringWriter()) { Pair rawPair; Object rawViewState; if (viewState is Pair) { rawPair = ((Pair)viewState); this.PageStatePersister.ControlState = rawPair.First; rawViewState = rawPair.Second; } else { rawViewState = viewState; } formatter.Serialize(writer, rawViewState); byte[] bytes = Convert.FromBase64String(writer.ToString()); bytes = Compressor.Compress(bytes); string alteredViewState = Convert.ToBase64String(bytes); bytes = null; this.PageStatePersister.ViewState = alteredViewState; this.PageStatePersister.Save(); } }
|