Announcing MVC3 starter site

2 Comments

Inspired by Rob Conery’s MVC starter site, I’ve created an MVC3 starter site.

It basically takes Visual Studio’s File -> New Project -> ASP.NET MVC 3 Web Application and builds on that, adding all the things we need to get started – IOC (Unity), Unit of work pattern, Logging (NLog), Reporting, oh and some CSS from freecsstemplates.org.

It’s also my first open source project in a while…

You can download it from codeplex at http://mvc3starter.codeplex.com

mvc3 starter app screenshot

Log exceptions with Health Monitoring in ASP.NET MVC3

4 Comments

Out of the box, ASP.NET MVC3 applications have basic error handling. To see, let’s create an action that will deliberately throw an error.
HomeController.cs:

public ActionResult NoView() // this Action has no view, for testing error handling!
{
    return View();
}

Now when we hit /Home/NoView (in our development environment), we get the YSOD because MVC raises an InvalidOperationException, as expected.

In our production environment the error is automatically handled nicely and the /Shared/Error view is shown:

I’m not quite sure how MVC is handling the error in production under the covers, since I am NOT specifying the [HandleError] attribute anywhere. Hmm, wait a second, what’s this?
Global.asax.cs:

public class MvcApplication : System.Web.HttpApplication
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }

Cool, I just learnt something. The [HandleError] attribute is registered globally when we created a new project. That’s going to make the rest of this blog post easier…

Logging Exceptions

In our development environment, when these exceptions are thrown they appear in the eventlog. But in production, they don’t get put into the eventlog. We need to log them somewhere!
There’s a bucketload of ways to log in ASP.NET – log4net, ELMAH, etc. But I decided I wanted to use one that comes built into ASP.NET – health monitoring.

Heath monitoring

Following the helpful chaps at 4guysfromRolla, we can enable .NET health monitoring by editing our web.config:

<configuration>
    <system.web>
      <healthMonitoring enabled="true">
       <eventMappings>
          <clear />
          <add name="All Errors" type="System.Web.Management.WebBaseErrorEvent"
                   startEventCode="0" endEventCode="2147483647" />
       </eventMappings>

       <providers>
          <clear />
          <add name="EventLogProvider" type="System.Web.Management.EventLogWebEventProvider" />
       </providers>

       <rules>
          <clear />
          <add name="All Errors Default" eventName="All Errors" provider="EventLogProvider"
                   profile="Default" minInstances="1" maxLimit="Infinite" minInterval="00:00:00" />
       </rules>
      </healthMonitoring>
    </system.web>
</configuration>

But that’s not enough. For some reason, the ASP.NET MVC [HandleError] attribute (registered globally in Global.ascx.cs, remember) doesn’t invoke the health monitoring features. But thanks to a helpful post by Andrew Wilinski, we can create our own HandleError attribute which will. Create a new class called HandleErrorHm.cs:

/// <seealso cref="http://weblogs.asp.net/awilinsk/archive/2008/12/11/handleerrorattribute-and-health-monitoring.aspx"/>
public class HandleErrorHmAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext context)
    {
        base.OnException(context);
        new WebRequestErrorEventMvc("An unhandled exception has occurred.", this, 103005, context.Exception).Raise();
    }
}

public class WebRequestErrorEventMvc : WebRequestErrorEvent 
{
    public WebRequestErrorEventMvc(string message, object eventSource, int eventCode, Exception exception) : base(message, eventSource, eventCode, exception) {}
    public WebRequestErrorEventMvc(string message, object eventSource, int eventCode, int eventDetailCode, Exception exception) : base(message, eventSource, eventCode, eventDetailCode, exception) {}
}

And now change our Global.asax.cs to use our attribute instead:

public class MvcApplication : System.Web.HttpApplication
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorHmAttribute());
    }

Big success!! Our exceptions appear in the eventlog on our production web server.

Logging to a SQL database

Since I’m already using ASP.NET authentication I already have an aspnet_WebEvent_Events table. So if I follow the rest of the 4GuysfromRolla post, I can set it up to log to my existing application database:

<connectionStrings>
    <add name="ApplicationServices" connectionString="Data Source=.\sqlexpress;Initial Catalog=Jobs;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>
...
  <system.web>
    <healthMonitoring enabled="true">
      <eventMappings>
        <clear />
        <!-- Log ALL error events -->
        <add name="All Errors" type="System.Web.Management.WebBaseErrorEvent" startEventCode="0" endEventCode="2147483647" />
        <!-- Log application startup/shutdown events -->
        <add name="Application Events" type="System.Web.Management.WebApplicationLifetimeEvent" startEventCode="0" endEventCode="2147483647"/>
      </eventMappings>
      <providers>
        <clear />
        <!-- Provide any customized SqlWebEventProvider information here (such as a different connection string name value -->
        <add connectionStringName="ApplicationServices" maxEventDetailsLength="1073741823" buffer="false" name="SqlWebEventProvider" type="System.Web.Management.SqlWebEventProvider" />
      </providers>
      <rules>
        <clear />
        <add name="All Errors Default" eventName="All Errors" provider="SqlWebEventProvider" profile="Default" minInstances="1" maxLimit="Infinite" minInterval="00:00:00" />
        <add name="Application Events Default" eventName="Application Events" provider="SqlWebEventProvider" profile="Default" minInstances="1" maxLimit="Infinite" minInterval="00:00:00" />
      </rules>
    </healthMonitoring>

And now my errors are logged to my SQL database (although they’re not very readable).

What about 404 errors?

We don’t really want 404 errors to be handled in the same way – we should show the user a “page not found” error page instead of the generic “an error occured” page.
Web.Release.config:

  <system.web>
    <compilation xdt:Transform="RemoveAttributes(debug)" />
    <customErrors mode="On" xdt:Transform="Replace">
      <error statusCode="404" redirect="/Home/NotFound"/>
    </customErrors>
  </system.web>

HomeController.cs:

public ActionResult NotFound() // web.config sends 404s here
{
    return View();
}

Then in Views/Shared, add a new view called NotFound.cshtml:

@{
    ViewBag.Title = "404 Not Found";
}

<h2>@ViewBag.Title</h2>

Sorry, but we couldn't find that page.

Note that in our dev environment it will still show the YSOD for 404s, but in production our users will get redirected correctly.

One final note: if you follow these steps, 404s are NOT logged by health monitoring.

jQuery UI not working with ASP.NET MVC3 partial views

2 Comments

I was playing with ASP.NET MVC3 (RC2) and I couldn’t get jQuery UI’s datepicker to work for me in a partial view. It would always say datepicker is not a function.

It took me a while to figure out the problem is.

Firstly I was referencing jQueryUI’s css and jQuery UI in my layout page


_Layout.cshtml:

<head>
 <title>@ViewBag.Title</title>
 <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
 <link href="@Url.Content("~/Content/themes/base/jquery-ui.css")" rel="stylesheet" type="text/css" />
 <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
 <script src="@Url.Content("~/Scripts/jquery-ui.min.js")" type="text/javascript"></script></head>

Then, at the bottom of my partial view I was calling datepicker like so:

Job.cshtml:
<div>
    @Html.LabelFor(model => model.DueDate)
</div>
<div>
    @Html.EditorFor(model => model.DueDate)
    @Html.ValidationMessageFor(model => model.DueDate)
</div>
<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        $("#DueDate").datepicker();
    });
</script>

The problem was I didn’t notice that the MVC scaffolding had added a reference to jQuery to the top of my partial view. This reference to jQuery was wiping out the earlier reference to jQuery UI in layout page.

Job.cshtml:
@model JobSystem.Web.Models.Job

<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

The solution was to remove the reference to jquery in my partial view (Job.cshtml).

I also decided to remove the reference to jQuery UI from the layout page (_Layout.cshtml) and add it to the partial view (Job.cshtml).

Download binary files in IE6 with ASP.NET MVC 2.0

1 Comment

On an ASP.NET MVC 2.0 application I was supporting, the application had a download link for downloading a PDF. When clicked, the browser would popup the usual question – what do you want to do with the file? Open, Save or Cancel?

If they click Save it would always work fine with all browsers, but if they click Open it would work fine in all browsers except IE6. With IE6, when they click Open, the file gets downloaded to IE6’s temporary files folder, and then (for PDFs) Acrobat Reader would try to open it. However, it would fail with the error message: “There was an error opening this document. This file cannot be found.” The same problem would also happen with Word documents.

This was only happening in IE6, all other browsers were fine.

Currently, the  Download method on the Controller would write an audit entry and then send the file to the browser using MVC’s File() method, like so:

public ActionResult Download(int id)
{
    Document doc = _documentRepository.GetById(id);

    if (doc != null)
    {
        return File(doc.Filepath, doc.FileType1.Mimetype, Path.GetFilename(doc.Filepath));
    }
    return RedirectToAction("Index");
}

After a lot of Fiddler investigation, playing around with the headers (content-type and content-disposition), and playing with the browser settings I still couldn’t get it to work. I finally found the solution via a stack overflow post. Here’s my version:

public class BinaryFileResult : ActionResult
{
    public string Filename { get; set; }
    public string Path { get; set; }
    public string ContentType { get; set; }

    public override void ExecuteResult(ControllerContext context)
    {
        FileStream sourceFile = new FileStream(context.HttpContext.Server.MapPath(Path), FileMode.Open);
        int length = (int)sourceFile.Length; // NB. this will only allow download of the first 2Gb of the file.
        byte[] buffer = new byte[length];
        sourceFile.Read(buffer, 0, length);
        sourceFile.Close();

        context.HttpContext.Response.ClearContent();
        context.HttpContext.Response.ClearHeaders();
        context.HttpContext.Response.Buffer = true;
        context.HttpContext.Response.ContentType = ContentType;
        context.HttpContext.Response.AddHeader("Content-Length", length.ToString());
        context.HttpContext.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + Filename + "\"");
        context.HttpContext.Response.BinaryWrite(buffer);
        context.HttpContext.Response.Flush();
        context.HttpContext.Response.End();
    }
}

And it is called via:


public ActionResult Download(int id)
{
    Document doc = _documentRepository.GetById(id);

    if (doc != null)
    {
        BinaryFileResult res = new BinaryFileResult
        {
            Path.GetFileName(doc.filepath).Trim(),
            Path = doc.filepath,
            ContentType = doc.FileType1.mimetype.Trim()
        };

        return res;
    }
    return RedirectToAction("Index");
}

And that worked fine in IE6 and all later browsers (Fx 3.6, Chrome 8, IE8).

Follow

Get every new post delivered to your Inbox.