Storing ASP.NET View State in a Flat File or Session

To prevent Invalid view state or 64Bit invalid viewstate issues, and to improve page performance, I have loaded view state in a flat file at times.

Follow These Steps:

1. Add the Class File to your project

3. Have your page Inherit from the View State class (attached .cs file).

 public partial class ViewStateInFlatFile : MyClass.PersistViewStateToFile //Inhert the class that handles view state

4. Setup a scheduled task to delete old view state files. I delete files that are one day old.

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

namespace MyClass
{
    public class PersistViewStateToFile : System.Web.UI.Page
    {
        public string ViewStatePath = string.Empty;

        public PersistViewStateToFile()
        {
            ViewStatePath = Server.MapPath(@"~\ViewState");
        } 
        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()
        {
            string filepath = ViewStateFilePath;
            // determine the file to access
            if (!File.Exists(filepath))
                return null;
            else
            {
                // open the file
                StreamReader sr = File.OpenText(filepath);
                string viewStateString = sr.ReadToEnd();
                sr.Close();

                // deserialize the string
                LosFormatter los = new LosFormatter();
                return los.Deserialize(viewStateString);
            }
        }
        public string ViewStateFilePath
        {
            get
            {
                if (Session["viewstateFilPath"] == null)
                {
                    var fileName = Session.SessionID + "-" + Path.GetFileNameWithoutExtension(Request.Path).Replace("/", "-") + ".ViewState";
                    var filepath = Path.Combine(ViewStatePath, fileName);
                    Session["viewstateFilPath"] = filepath;
                }

                return Session["viewstateFilPath"].ToString();                          
            }
        }
        public string GetValue(string uniqueId)
        {
            return System.Web.HttpContext.Current.Request.Form[uniqueId];
        }
        /// 
        /// Replace this with BAT Files to delete these View State files.
        /// 
        private void RemoveFilesfromServer()
        {
            try
            {
                //string folderName = Path.Combine(Request.PhysicalApplicationPath, "PersistedViewState");
                string folderName = ViewStatePath;
                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");
            }
        }
        /// 
        /// A GUID is created to store the file names
        /// 
        private string GenerateGUID()
        {
            return System.Guid.NewGuid().ToString("");
        }
    }
}
C# source for View State save to flat file and save to session: 

PersistViewStateToFile.cs (3.45 kb)

PersistViewStateSession.cs (1.23 kb)

ASP.NET Numeric Input Validation

There are many ways to validate and force users to type only Numeric data.  You have Bootstrap, MVC, Text Boxes with the attribute of, TextMode="Number", 3rd party controls with Mask Edit such as DevExpress, Infragistics, and others.

The problem with some of these options is that they only work on browsers that support HTML5, some don't play well with IE. In the case of the mask editors I have found these to be very clunky such as you have to hit back space to enter data, delete does not work, or it seems the entry just locks up. 

I own DevExpress but prefer to use the JavaScript method discussed below. It handles the data entry much nicer. 

There is an old standby that I have used from mredkj. It is basically a very well written JavaScript that allows numeric entry only, optional decimal positions allowed as well as prevent negative numbers if you chose to do so.

You can test it out that mredkj blog at this link.

EXAMPLE:

1. Add JS File to your project

 <script src="Scripts/ValidateNumber.js" type="text/javascript" ></script> 

2. Add a TextBox to a page.

<asp:TextBox ID="TxtValScript" runat="server"></asp:TextBox>

3. In the code behind attach to the JavaScript (you can include or exclude decimals / negative values)

TxtValScript.Attributes.Add("onblur", "extractNumber(this,2,false);");
TxtValScript.Attributes.Add("onkeyup", "extractNumber(this,2,false);");
TxtValScript.Attributes.Add("onkeypress", "return blockNonNumbers(this,event,true,false);");
TxtValScript.MaxLength = 8;

The attached ZIP file has the JavaScript. 

Validation.zip (1.64 kb)