ASP .NET Dynamically generate classes & compiles an assembly to the Temporary ASP.NET files.
I would like to be able to get information when this process happens. Ultimately, I would like to have an event that will fire the name of the source file and the generated class name + assembly so I could map between methods in the original source file and methods in the generated classes.
I'll appreciate your help.
I would recommend using the FileSystemWatcher class to create a watcher for the appropriate directories, and then do processing based on that.
You can find info about it here: https://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(v=vs.110).aspx
Essentially, the watcher would allow you to get events to file changes in the directory, of which then you can use the Assembly class to load and process through reflection information about the generated code. I cannot say this will be easy, but it is very doable. You're also going to want to have a database for keeping track of what's changed, mapping source to compiled code, etc. to make it more robust.
Hopefully this points you in the right direction.
Elaborating on the suggestion from @Inari
Just make sure you watch the folder AppDomain.CurrentDomain.DynamicDirectory with IncludeSubdirectories set to true. To be sure you are not too late to monitor all compilations, you need to fire up as the very first, so I would suggest you use the PreApplicationStartMethodAttribute for that.
This helps in getting the information when this process happens. If you also want to find source files, that depends on what you are interested in (only compiled assemblies ? => reflection, also compiled razor pages => by name ) .
[assembly: PreApplicationStartMethod(typeof(Demo.CompilationWatcher), "Initialize")]
namespace Demo
{
public static class CompilationWatcher
{
public static void Initialize()
{
while (true)
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = AppDomain.CurrentDomain.DynamicDirectory;
watcher.IncludeSubdirectories = true;
watcher.NotifyFilter = NotifyFilters.Attributes |
NotifyFilters.CreationTime |
NotifyFilters.DirectoryName |
NotifyFilters.FileName |
NotifyFilters.LastAccess |
NotifyFilters.LastWrite |
NotifyFilters.Security |
NotifyFilters.Size;
watcher.Filter = "*.*"; // consider filtering only *.dll, *.compiled etc
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
}
}
public static void OnChanged(object source, FileSystemEventArgs e)
{
// your thread-safe logic here to log e.Name, e.FullPath, an d get the source file through reflection / name etc. ...
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With