Click here to Skip to main content
15,884,472 members
Articles / Web Development / ASP.NET

ViewState: Various ways to reduce performance overhead

Rate me:
Please Sign up or sign in to vote.
4.97/5 (55 votes)
19 Aug 2010CPOL12 min read 508.8K   1.6K   123  
This article discusses about ViewState and several ways to reduce the performance hit caused by it, with a sample application.
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.IO.Compression;

/// <summary>
/// Summary description for PersistViewStateToFileSystem
/// </summary>
public class PersistViewStateToFileSystem:Page
{
	public PersistViewStateToFileSystem()
	{
		//
		// TODO: Add constructor logic here
		//
	}
    protected override void SavePageStateToPersistenceMedium(object state)
    {
        LosFormatter los = new LosFormatter();
        StringWriter sw = new StringWriter();
        los.Serialize(sw, state);

        StreamWriter w = File.CreateText(ViewStateFilePath);
        w.Write(sw.ToString());
        w.Close();
        sw.Close();
    
    }

    protected override object LoadPageStateFromPersistenceMedium()
    {
        // determine the file to access
        if (!File.Exists(ViewStateFilePath))
            return null;
        else
        {
            // open the file
            StreamReader sr = File.OpenText(ViewStateFilePath);
            string viewStateString = sr.ReadToEnd();
            sr.Close();

            // deserialize the string
            LosFormatter los = new LosFormatter();
            return los.Deserialize(viewStateString);
        }
    }


    public string ViewStateFilePath
    {

        get
        {
            bool isSessionId = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["isSessionId"]);
            string folderName = Path.Combine(Request.PhysicalApplicationPath, "PersistedViewState");
            string fileName = string.Empty;
            string filepath = string.Empty;
            if (!isSessionId)
            {
                HiddenField hfVSFileName = null;
                string VSFileName = "";

                // Get the HiddenField Key from the page
                hfVSFileName = FindControl(this, "hfVSFileName") as HiddenField;

                // Get the HiddenField value from the page
                string hfVSFileNameVal = GetValue(hfVSFileName.UniqueID.ToString());
                if (!string.IsNullOrEmpty(hfVSFileNameVal))
                {
                    VSFileName = hfVSFileNameVal;
                }

                if (!Page.IsPostBack)
                {
                    VSFileName = GenerateGUID();
                     hfVSFileName.Value = VSFileName;

                    //Removing files from Server
                    RemoveFilesfromServer();
                }

                fileName = VSFileName + "-" + Path.GetFileNameWithoutExtension(Request.Path).Replace("/", "-") + ".vs";
                filepath = Path.Combine(folderName, fileName);

                return filepath;
            }
            else
            {
                if (Session["viewstateFilPath"] == null)
                {

                    fileName = Session.SessionID + "-" + Path.GetFileNameWithoutExtension(Request.Path).Replace("/", "-") + ".vs";
                    filepath = Path.Combine(folderName, fileName);
                    Session["viewstateFilPath"] = filepath;
                }
                return Session["viewstateFilPath"].ToString();
            }
        }
    }

    public static Control FindControl(Control root, string controlId)
    {
        if (root.ID == controlId)
        {
            return root;
        }

        foreach (Control c in root.Controls)
        {
            Control t = FindControl(c, controlId);
            if (t != null)
            {
                return t;
            }
        }

        return null;
    }
    public string GetValue(string uniqueId)
    {
        return System.Web.HttpContext.Current.Request.Form[uniqueId];
    }

    private void RemoveFilesfromServer()
    {
        try
        {
            string folderName = Path.Combine(Request.PhysicalApplicationPath, "PersistedViewState");
            DirectoryInfo _Directory = new DirectoryInfo(folderName);
            FileInfo[] files = _Directory.GetFiles();
            DateTime threshold = DateTime.Now.AddDays(-3);
            foreach (FileInfo file in files)
            {
                if (file.CreationTime <= threshold)
                    file.Delete();
            }
        }
        catch (Exception ex)
        {
            throw new ApplicationException("Removing Files from Server");
        }
    }
    /// <summary>
    /// A GUID is created to store the file names
    /// </summary>
    private string GenerateGUID()
    {
        return System.Guid.NewGuid().ToString("");
    }

}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
Brij is a 3-times Microsoft MVP in ASP.NET/IIS Category and a passionate .NET developer. More than 6 years of experience in IT field, currently serving a MNC as a Tech Lead/Architect.

He is a very passionate .NET developer and have expertise over Web technologies like ASP.NET 2.0/3.5/4.0, jQuery, JSON, Javascript, IIS and related technologies. He is also a Exchange Server (EWS) Specialist. He has great experience in design patterns and N-Tier Architecture.

He is also certified as Microsoft Certified Technologies Specialist-ASP.NET and Microsoft Certified Technologies Specialist-WCF in .NET 4.0. He has also received several awards at various forums and his various articles got listed as "Article of the day" at ASP.NET Microsoft Official Website www.asp.net.

He has done MCA from NIT Durgapur and completed his graduation from Lucknow University.

Learning new technologies and sharing knowledge excites him most. Blogging, solving problems at various forums, helping people, keeps him busy entire day.


Visit his Blog: Code Wala

Area of Expertise :
C#, ASP.NET 2.0,3.5,4.0, AJAX, JQuery, JSON, XML, XSLT, ADO.Net, WCF, Active Directory, Exchange Server 2007 (EWS), Java script, Web Services ,Win services, DotnetNuke, WSS 3.0,Sharepoint Designer, SQL Server 2000/2005/2008

Comments and Discussions