Infolink

 

Search This Blog

Oct 21, 2012

How to Detect Errors of Our ASP.NET MVC Views on Compile Time

I have simple ASP.NET MVC 4 internet application which we get out of the box (Things that I will show can be applied with ASP.NET MVC 3 as well). Then I will put a bug inside the index view of my home controller :

@{
    var poo = "bar"
    }

<h3>We suggest the following:</h3>
As you can see it is not a valid code. So it should fail on both compile time and runtime, right? Let’s build the project first :

Error1


Successful! Let’s run it :


Boom! Now you have a new, polished ScottGu’s YSOD (Yellow Screen of Death). So, the question here is why it wasn’t caught by VS.

By default, on ASP.NET MVC projects, your views aren’t compiled on build process of your application. VS treats your views just like it treats CSS files. This doesn’t mean that VS isn’t doing its job, it certainly does. Here is a proof of it :

 I went into my index.cshtml file and and press CTRL+W, E to bring up the Error List window. Here is the result :



Everything is there. But how many of us really check this window on regular basis unless you work on a team project and your team has a habit of putting #warning blocks inside your C# codes. Probably a few of us.

What we can do here is a fairly simple action to get this blow up on compile time.


Blow Up In My Face so I can See you

Right click on your project inside solution explorer and click Unload Project section as follows :





 After that your project will be unloaded.

Then, right click it again and it will bring up much shorter. From that list, click on Edit {yourProjectName}.csproj section (If your project is a VB project, then .csproj should be .vbproj) as follows :




As you will see, there is so much going on there. We won’t dive into detail there. What we will simply do is to toggle MvcBuildViews node from false to true :




Save the file and close it. Then, right click on your project inside solution explorer again. This time click Reload Project section :



Now, when we correct the bug, we will see that we will have a successful build. Note that this won’t compile your views into a .dll file, this action will only check them for any compile time errors.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...