tisdag 31 mars 2009

Removing a subdirectory from your application will cost you your session state

Encountered a curious error, with users being logged out from an admin application, when they removed a folder. Turns out the behavior is by design: Removing a folder anywhere in your application, programatically or manually, will cause a full AppDomain recycle, in just the same manner as uploading a DLL file to bin or making a change to web.config does, and that's all there's to it.

Managed to come up with only one work-around, that'll still allow the file change notifier to monitor web.config and bin directory, and it's not very pretty, but it seems to work:
private void SafelyDeleteFolder(string folder, bool recursive)
{
   //FIX disable AppDomain restart when deleting subdirectory
   //This code will turn off monitoring from the root website directory.
   //Monitoring of Bin, App_Themes and other folders will still be operational, so updated DLLs will still auto deploy.

   System.Reflection.PropertyInfo p = typeof(HttpRuntime).GetProperty("FileChangesMonitor", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);

   object o = p.GetValue(null, null);
   System.Reflection.FieldInfo f = o.GetType().GetField("_dirMonSubdirs", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.IgnoreCase);

   object monitor = f.GetValue(o);
   System.Reflection.MethodInfo m = monitor.GetType().GetMethod("StopMonitoring", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
   m.Invoke(monitor, new object[] { });

   System.IO.Directory.Delete(folder, recursive);
}

Inga kommentarer: