Tag Archives: visual studio

Realtime MVC ModelState errors during debugging

While working on my most recent ASP.NET MVC project, I was having a tough time figuring out why my ModelState was invalid. It was due to the fact that I set the error messages to “Required” or “Invalid” for ALL of my model properties (to support the way the view presents the error messages). In retrospect, this probably wasn’t the smartest choice. Oh well, now I’m stuck figuring out another way to determine the properties causing Model validation to fail.

With Visual Studio 2015, I discovered a marvelous way to get the names of the properties with invalid values… buy using a watch! Watches now support lambda expressions (as long as there are no external dependencies, such as LINQ to SQL), so I thought… this would be a good time to test that functionality.

Since I was interested in the actual name of the property that was causing
ModelState.IsValid to return false, I used the following watch:

ModelState.Where(x => x.Value.Errors.Count > 0).Select(x => x.Key).ToList()

For those who don’t usually use watches, you may not know that a watch can be created directly in the watch window by just typing it in! That is what you will need to do here, since I’m guessing that this value is most likely not in your code…


If you get a message under Value saying “This expression causes side effects and will not be evaluated,” just click the refresh button to the right of the message to force-evaluate the watch. Once you do so, you’ll be able to expand the watch object to see your offenders!


Pretty neat!


allowDefinition=’MachineToApplication’ error after enabling MVC compile-time view checking

Two posts in one day?  Yesh… I’m just trying to make up for my extended hiatus from blogging!

Actually, this post supplements the previous one, but I think it is the more important of the two since I don’t believe there is a complete solution to this problem is anywhere else on the interweb (except for my answer on stackoverflow, which has ZERO upvotes… not that I’m counting LOL).

Here’s our scenario:

  1. The developer wants compile-time checking on views, so they set MvcBuildViews=true.
  2. The application builds fine, UNTIL they publish the project.
  3. Subsequent attempts to build the project result in a compile-time error: It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS.

So what causes this issue? When the project is published the compiler, by default it uses <project-dir>\obj\ to place copies of the source files that it will work with. Unfortunately, these files are not automatically deleted when publishing is complete. The next time the developer compiles the project with MvcBuildViews=true, it will error out because the aspnet compiler includes the obj\ folder during compilation, since it is underneath the <project-dir> folder.

So how do we fix this? Well, you have four options:

  1. Set MvcBuildViews=false. I don’t really consider this a solution, so let’s move on.
  2. Delete the files in <project-dir>\obj\. Works, but can be a hassle since it has to be done after every publish.
  3. Change the path that publishing uses as an intermediate directory through the use of the <BaseIntermediateOutputPath> property in your project config file. See this link.
  4. Add a new section in your project config file that deletes the offending files for you on build (reference Microsoft Connect). I’ve even made it easy for you, just copy and paste:
    <_EnableCleanOnBuildForMvcViews Condition=" '$(_EnableCleanOnBuildForMvcViews)'=='' ">true</_EnableCleanOnBuildForMvcViews>
    <Target Name="CleanupForBuildMvcViews" Condition=" '$(_EnableCleanOnBuildForMvcViews)'=='true' and '$(MVCBuildViews)'=='true' " BeforeTargets="MvcBuildViews">
        <_TempWebConfigToDelete Include="$(BaseIntermediateOutputPath)**\Package\**\*" />
        <_TempWebConfigToDelete Include="$(BaseIntermediateOutputPath)**\TransformWebConfig\**\*" />
        <_TempWebConfigToDelete Include="$(BaseIntermediateOutputPath)**\CSAutoParameterize\**\*" />
        <_TempWebConfigToDelete Include="$(BaseIntermediateOutputPath)**\TempPE\**\*" />
    <Delete Files="@(_TempWebConfigToDelete)"/>

My recommendation would be to use either option 3 or 4.

ASP.NET MVC compile-time view checks in Visual Studio 2012

Anyone who has worked with MVC has suffered through runtime view errors.  This is because views don’t get compiled until IIS renders them.  In order to check for successful compilation, you can:

  1. Manually visit every view in the browser (easy but tedious)
  2. Create automated UI tests (harder)
  3. Turn on compile-time view checks (just easy)!

Since I like just easy, I’m going to show you how to turn on compile-time view checks:

  1. Unload the project (right-click on the project in Solution Explorer and select Unload Project
  2. Right-click the project again and select Edit *.csproj
  3. In the PropertyGroup section, add: <MvcBuildViews>true</MvcBuildViews>
  4. Save the csproj file and reload the project
  5. Eat a banana (optional)

Now, when running the build, visual studio will compile all of your views as well, and identify any errors.

Javascript Intellisense in Visual Studio 2012

After years of use, I tend to accumulate a lot of cruft on my work computer hard drives, so whenever I replace a machine or hard drive I like to start fresh and only pull down old files from the backup server as I need them.  Last week, I replaced the hard drive on my laptop, so I had to redo all of the settings on Visual Studio.  As I had forgotten how to do this, I figured I should write it down to help me next time… perhaps it will help you too?

When developing Visual Studio MVC projects, if you’re like me, you like to move directories around to make more sense of the layout (instead of the default structure that M$ gives you).  An example of this is creating a public directory to hold your publicly available files, like styesheets and scripts.  You’ll also notice that when you move your Javascript libraries, Intellisense breaks.  This happens whenever the _references.js file is moved from its expected location*.

To fix, simply go to Tools | Options | Text Editor | JavaScript | IntelliSense References.  Switch to the Implicit (Web) Reference Group and add a new reference that resolves to the new location of the _references.js file:


Note that if you want to use a path relative to your project, it has to be entered into the text box at the bottom, in the form of “~/whatever_dirs_below_project_root”.

* If you want Intellisense support for your Javascript libraries, you need to be sure that the library name is included in the _references.js file.  This is not all, however.  VS also needs a vsdoc.js file that provides the particular data needed by Visual Studio Intellisense (e.g. jquery-1.10.0-vsdoc.js supports jquery-1.10.0.js).  Note that you should NOT include the vsdoc file name in the _references.js file, just the main file.  Intellisense vsdoc files for jquery are available on the ASP.NET CDN at http://www.asp.net/ajaxlibrary/cdn.ashx.

Breakpoints not hitting Visual Studio Unit Test projects

I’ve switched over to working some software development for the past few months and haven’t been too active on this blog.  Seems that there are plenty of people WAY smarter than me when it comes to coding, so I don’t usually have too much to say about the stuff (other than that I’m a good faker coder).  Anyway, was working on some unit tests for a particular class in my current project and for some reason, breakpoints were never hitting in my tests.  The solution would build without error, but the breakpoints always said ‘symbols not loaded’.

This was really driving me crazy, and since I thought I screwed up the build configuration, I ended up tearing out the test project and putting it back in, with no success.  Then looking at Test Explorer, I noticed that the unit tests were failing.  Looking at the error message, it turned out that the signature the test method with the [ClassInitialize] attribute had an incorrect signature (specifically, it needed to be public static void and have one parameter of the TestContext type).

So, long story short, a bad setup in your unit tests won’t necessarily prevent it from building, but will almost certainly prevent your tests from running.  And the Text Explorer will be more than happily tell you that you are stupid.

Referenced assembly could not be resolved because it has a dependency which is not in the currently targeted framework

If you are using third-party development tools (like Ninject) with your .NET 4.0 project.  You may get the following error at compile time:

Warning: The referenced assembly "<Assembly>" could not be resolved because it has a dependency on "System.Web, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" which is not in the currently targeted framework ".NETFramework,Version=v4.0,Profile=Client". Please remove references to assemblies not in the targeted framework or consider retargeting your project.

This error is a result of .NET 4.0 targeting (by default) the .NET Framework 4 Client Profile.  This profile is a subset of the full profile and does not have the entire .NET class library.  To fix, go into Project Properties  | Application, and change the target framework to: .NET Framework 4.  Visual Studio will prompt you that your solution must be closed and reloaded.  Once you do this, the project should compile as expected.

SharePoint assemblies and the GAC

One of the more tedious aspects of SharePoint feature development is that the feature receiver must be installed into the Global Assembly Cache. Because of this, the dll has to be strongly named and referenced by its four-part assembly name within the Feature.xml file. The first three parts (name, version, and culture) are pretty easy to figure out. But the last part, the public key token, is not so obvious.

In my opinion, the most elegant way to discover this information is to use the Strong Name tool (sn.exe) provided in Visual Studio (see Wriju’s blog entry on this http://blogs.msdn.com/wriju/archive/2008/07/01/how-to-find-public-key-token-for-a-net-dll-or-assembly.aspx).

Not to be outdone, and being a generally lazy guy, I set out to find a way to make this process even easier. So I created a new External Tool command in Visual Studio that runs sn.exe and gets the public key token of an assembly for me and displays it in the IDE’s Output window:

In Tools
External Tools, click the add button.

For title, call it something like ‘Get &Public Key Token’ (for you non win forms developers, the ampersand creates a keyboard shortcut for the command).

In command, enter ‘C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\sn.exe’ (you may need to modify the path depending on where you have sn.exe installed).

For arguments, enter ‘-Tp $(TargetPath)’. This ensures that the correct assembly is checked, based on build configuration. Ensure ‘Use Output window’ is checked. And that’s it. Of course, the assembly needs to be signed and you need to build the dll before running this command.

What is up with that %@#*&( batch file?!?!

So I’m working on a batch file to run some post-build events in Visual Studio, but when i run the build I notice something funny in the output window:

{{[[@ECHO OFF is not recognized as a valid command

Disclaimer: That might not be exactly how the error read, because I’ve already fixed the error and I’m too lazy to recreate it to get the exact wording, but you get the idea.

Now, the first line in my batch file is in fact a valid command, but there are all of these funny characters at the beginning of the line in the output window. So I go back to the actual batch file and those funny characters are not there.
So here I am scratching my head, thinking “I didn’t put those characters there, so who did?” Of course, my first reaction is to blame the machine!
After fiddling around with it, I discovered that whenever you create a new text file in Visual Studio and make it a batch file, it introduces these funny characters to the beginning of the file. I can only speculate (since I didn’t actually look at the bytes in the file), but I think it might be a Unicode vs ASCII encoding issue.

Long story short: if you want to create a batch file, first create it Notepad. Save it off and then edit it in Visual Studio and you won’t have any problems with encoding.