This is an extention of the article that i posted here:
http://p2p.wrox.com/topic.asp?TOPIC_ID=60283
regarding compressing the viewstate globally across your site. i've since had a little brainwave on how to change a few lines of code in the BasePage.cs file to make it work completely server side using the HttpRuntime.Cache.
ok - as an academic excerise, thought id try the minimal approach once more but this time use the server cache and guid's. seems to work just as well, not sure about the server load but the client only ever now receives a guid key. anyway, only about 3 lines of code changed from previous version (new/amended lines in blue):
BasePage.cs
namespace MB.TheBeerHouse.UI
{
public class BasePage : System.Web.UI.Page
{
// added to compress viewstate also in globals
protected override object LoadPageStateFromPersistenceMedium()
{
string viewState = Request.Form["__VSTATE"];
//byte[] bytes = Convert.FromBase64String(viewState);
// if using client vstate, unrem line above and rem out line below
if (HttpRuntime.Cache[viewState] != null)
{
byte[] bytes = (byte[])HttpRuntime.Cache[viewState];
bytes = Globals.Decompress(bytes);
LosFormatter formatter = new LosFormatter();
HttpRuntime.Cache.Remove(viewState);
return formatter.Deserialize(Convert.ToBase64String(bytes ));
}
else
{
return null;
}
}
protected override void SavePageStateToPersistenceMedium(object viewState)
{
string viewStateGuid = Guid.NewGuid().ToString();
LosFormatter formatter = new LosFormatter();
StringWriter writer = new StringWriter();
formatter.Serialize(writer, viewState);
string viewStateString = writer.ToString();
byte[] bytes = Convert.FromBase64String(viewStateString);
bytes = Globals.Compress(bytes);
//ClientScript.RegisterHiddenField("__VSTATE", Convert.ToBase64String(bytes));
// if using line above (to use client vstate), rem out bottom two lines
HttpRuntime.Cache.Insert(viewStateGuid, bytes, null,
DateTime.Now.AddMinutes(10),
System.Web.Caching.Cache.NoSlidingExpiration);
ClientScript.RegisterHiddenField("__VSTATE", viewStateGuid);
}
// end viewstate additions
I think this one is the 'winner' in my book - looking fwd to comments on it's shortcomings tho' (i.e. should i be using Session[viewStateGuid] or HttpRuntime.Cache[viewStateGuid]). i'm experimenting with both the Session object and the HttpRuntime.Cache to see what differences i can find. i'm certain that i should be using the Session object after reading references to webfarms etc... however, i beleive that the session objects don't expire, so was worried about the implications on that front. of course, i suppose the session 'dies' when the client closes or timesout.
i also have noticed that the SavePageStateToPersistenceMedium is called far more than the LoadPageStateFromPersistenceMedium (which only get's called on a postback), so altho' i'm setting the cache to expire after 10 mins, there will be quite a few cache items that will never be used. food for thought anyway
jimi
http://www.jamestollan.com