Ignoring ReSharper Code Issues in Your New ASP.NET MVC 3 Application

ReSharper is a great tool for identifying problems with your code.  Simply right-click on any project in the Solution Explorer and select Find Code Issues.  After ReSharper analyzes all the files, you’ll see a window with several categories of issues including “Common Practices and Code Improvements”, “Constraint Violations”, and “Potential Code Quality Issues”.

Unfortunately, when you create a new ASP.NET MVC 3 application in Visual Studio 2010, Resharper will find thousands of code issues before you even start coding.

2019 issues found

Most of these “issues” are in jQuery and Microsoft’s AJAX libraries, and your average developer is not going to go around adding semicolons all day when they have real work to do.  So we need to tell ReSharper to ignore these known issues somehow.

It would be nice if ReSharper allowed you to ignore files using file masks, but it doesn’t.  You must specify each file or folder individually.  Go to ReSharper->Options…->Code Inspection->Settings.  Click Edit Items to Skip.

My first instinct was to lasso or shift-click to select all the jQuery scripts, but this is not allowed!  I certainly wasn’t going to bounce back and forth between dialog windows a dozen times just to add each file.

Luckily this is ReSharper, and we can move all the script files into another directory and update references automatically.  Select all the jQuery scripts in the Scripts folder simultaneously, right-click, and go to Refactor->Move.  Create a new jquery folder under Scripts and click Next.

Move to Folder

Now you can go back into the ReSharper options and add this folder to the list of items to skip.

Skip jQuery folder

Move Microsoft’s script files into their own folder, and tell ReSharper to ignore these as well.  I’m also using modernizr so I exluded the two modernizr scripts individually.

Skip Files and Folders

Find Code Issues again and things should look much better.  I’ve only got 25 issues now.

25 code issues

With the help of ReSharper’s refactoring capabilities I was able to get this down to one issue in just a few minutes.  Now you can get on with your project without having to mentally filter out a bunch of noise in the Inspection Results window.

Happy coding!

Advertisement

Conditional Validation with Data Annotations in ASP.NET MVC

In the simple blog engine I’m building, I encountered a scenario where I wanted to display different UI elements depending on whether the user was logged in:

Comment Form
Not logged in

 

Comment Form Logged In
Logged in

 

When the user is authenticated, their name and email is known, so it’s unnecessary to display them on the comment input form.  While it would be possible to hide just those fields, I decided to make separate partial views and display them in the Post view with the following code:

<%
    if (Model.AllowComments)
    {
        var commentControlName = Request.IsAuthenticated ? AuthenticatedCommentFormControl" : "CommentFormControl";
        Html.RenderPartial(commentControlName, new DotBlog.Models.ViewModels.CommentViewModel(Model.PostId));
    }
%>

This is the view model I used for both partial views:

public class CommentViewModel
{
    ...

    [Required]
    [StringLength(50)]
    [DisplayName("Name")]
    public string CommenterName { get; set; }

    public DateTime Date { get; set; }

    [Required]
    [StringLength(100)]
    public string Email { get; set; }

    [StringLength(100)]
    [DisplayName("Web Site")]
    public string WebSite { get; set; }

    [Required]
    [StringLength(1024)]
    [DisplayName("Comment")]
    public string CommentText { get; set; }

    ...
}

As you can see, I’m using data annotations to enforce required fields and string lengths.  The problem is, even though the name and email aren’t always displayed, they are still required.  I needed a way to validate certain fields conditionally.  Here are the options I came up with:

  • Stop using data annotations and find a different solution for validation
  • Use two different view models: one for each partial view
  • Use actual conditional data annotations, like the library built by Simon Ince.
  • When the form is posted, remove the fields from the model state so they’re not validated.

 

Let’s look at each of these individually:

Stop Using Data Annotations

Data annotations are not the only way to specify validation rules, but they’re easy to implement.  xVal was fine for ASP.MVC 1.0, but is now deprecated.  Custom validation code with ModelState.AddModelError() is flexible, but requires extra work.

Use Two Different View Models

Since I’m using two partial views for the comment form (one for authenticated users and one for guests), I could use a dedicated view model for each.  One would omit the data annotations on name and email and therefore not cause any validation problems.  This was my original implementation, but lead to unnecessary code duplication and other design problems.

Use Conditional Data Annotations

Simon Ince has built a cool library for conditional annotations that allows you to write code like this:

public class ValidationSample
{
    [RequiredIf("PropertyValidationDependsOn", true)]
    public string PropertyToValidate { get; set; }

    public bool PropertyValidationDependsOn { get; set; }
}

Conditionally Remove Fields from the Model State in the Controller

In the end, this is the solution I went with.  The controller executes this code when the form is posted:

if (Request.IsAuthenticated)
{
    ...

    // We don't need to validate user fields if user is logged in.
    ModelState.Remove("CommenterName");
    ModelState.Remove("Email");
}

By removing the fields from the model state, it won’t be invalid when they are missing.  This method is simple and avoids adding additional dependencies.