Coding Microsoft

Dynamic Code-Behind file compilation in ASP.NET 1.x

In so many of my ASP.NET presentations I get this question. How to do dynamic compilation of a code-behind .vb/.cs file used in a ASPX file?.

The situation is like this: “We have deployed a project developed with ASP.NET/Visual Studio to the data centre. After going live, we have done a small bug-fix in one of the .vb file, now we don’t want to recompile the whole-project in VS.NET to get a new DLL for deployment” or “We have lots of test pages that are half-done in a Web Project. If we compile in VS.NET, all of this code gets into the DLL. How do we avoid it?”

The answer for this lies in understanding the Attributes available for the @Page tag of ASPX. When you create a .aspx file in Visual Studio, for linking to the appropriate code-behind files, VS.NET uses the tag Codebehind. For example, if you have a ASPX file “Welcome.aspx”, you will have codebehind=”Welcome.aspx.vb”. According to MSDN Documentation for @Page Tag, if you use the codebehind tag, ASP.NET runtime requires the classes in .vb file to be compiled and present in dll in the /bin folder. To avoid this, you can use an alternate tag src, which has very similar syntax src=”welcome.aspx.vb”, except that src will automatically compile the referred file. The downside to this approach is that, you got to ship or deploy source code of all your code-behind files as well.

In the same web project, you can mix and match codebehind and src tags in various .aspx files, but in a single .aspx file there can be only one of them.

When I first did this demo, it failed!. Then I realized I got to change the namespace used in the Inherits tag. If you are using the Codebehind/VS.NET approach, VS.NET automatically uses the project name as the namespace. So Inherits for a web-project named “Venkat” will look like Inherits=“venkat.welcome”. But when you use src, it simply becomes Inherits=“welcome”.

Download a sample – DynamicCompile.zip (1.1 KB) which demonstrates the use of src tag. Extract the files into a web folder, run it from browser. Change the source in the .vb file and reload from browser to see the changes without manual recompilation.