The views expressed on this weblog are mine alone and do not necessarily reflect the views of my employer.
 Friday, January 10, 2003
Set the ASP.NET Application Object to Read-Only

Requirement:

Pre-Load the ASP.NET Application object and don’t allow other pages in your project to add/modify/delete. Basically, make Application read-only.

Solution:

         private void SetApplicationReadOnlyStatus( bool state ) {
                  Type type = Application.GetType().BaseType;
                  PropertyInfo readPropInfo = type.GetProperty("IsReadOnly",  BindingFlags.NonPublic | BindingFlags.Instance) ;
                  if( readPropInfo != null ) {
                        readPropInfo.SetValue( Application,Convert.ChangeType(state,readPropInfo.PropertyType ) ,null);
                  }
            }
            private void Page_Load(object sender, System.EventArgs e) {
                  Application["MyKey"] = "myValue";
                  // Set application to readonly so that we will not allow any changes.
                  SetApplicationReadOnlyStatus( true );
                  try
                  {
                        // Try setting a value 
                        Application["MyKey"] = "New value";
                        Response.Write("You won't see this");
                  }
                  catch(Exception ex) {
                        // You'll end up here
                        Response.Write(ex.Message);
                }
            }

Thanks to Sairama for the code!


Updated Link to this post 10:29:31 AM  #    comment []  trackback []