Using the WebAPI to send errors for your apps

by Shawn 26. January 2013 22:55

If your app does anything at all complex, it’s going to crash. You’re going to miss checking something for null. You’re going to use a resource that doesn’t exist. Your app is going to crash. Luckily there are some ways to make sure you know what’s happening. Little Watson by Andy Pennell shows us a great way to send application errors but requires the user to email them to you. Bjorn Kuiper extended Little Watson by removing the need to email the report and instead send it to a PHP endpoint. This is a great solution provided your server is setup to run PHP . If you don’twant to use PHP, don’t want to install PHP or if you are using a hosting service that does not run PHP then you’re out of luck.

Instead of convincing your web provider to install PHP you could create a WCF service, but that seems like a lot of overhead. You could also create an ASP.NET web page and put the error details into a query parameter, but that seems hokie. Luckily the Web API has been introduced. The Web API makes this easy to implement, easy to deploy, and easy to use. Web API allows you to send an object of information in a well known format. Overall, the Web API is just awesome.

The first step is to start with the minimal Web API project. Open the Global.asax file and add the following line inside the Application_Start method

RouteTable.Routes.MapHttpRoute("ErrorRoute", "{controller}/{id}", new { id = RouteParameter.Optional });

Right click on the on controllers folder and create a new ApiController.

image

Following Bjorn’s example, we need an ExceptionContainer class that will hold our exception information. I’ve added an additional property for the application name. This is handy if you have more than one app.

public class ExceptionContainer
{
    ///  <summary>  
    /// Gets or sets the message.  
    /// </summary>  
    public string Message { get; set; }
 
    ///  <summary>  
    /// Gets or sets the stacktrace.  
    /// </summary>  
    public string StackTrace { get; set; }
 
    /// <summary>
    /// The application the error was found.
    /// </summary>
    public string ApplicationName { get; set; }
}

Inside the controller we need one method that we can send exception info to. The Web API allows you to take advantage of the HTTP verbs and structure your API in terms of them. For this error reporting, the most logical verb is POST. We’re not trying to GET, update (PUT) or DELETE anything. Create a new Post method that returns an HttpResponseMessage and takes an ExceptionContainer as a parameter. In the method we’ll send an email.

public HttpResponseMessage Post(ExceptionContainer exception)
{
    if (exception == null) return new HttpResponseMessage(HttpStatusCode.PaymentRequired);
 
    var message = new System.Net.Mail.MailMessage
        {
            From = new System.Net.Mail.MailAddress("phoneApps@yourdomain.com"),
            Subject = "Error report: " + exception.ApplicationName,
            Body = exception.Message + Environment.NewLine + exception.StackTrace
        };
    message.To.Add("you@domain.com");
 
    System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("localhost", 25);
    // send credentials if your SMTP server requires them
    //client.Credentials = new NetworkCredential("user", "password");
    client.Send(message);
 
    return new HttpResponseMessage(HttpStatusCode.Created);
}

Deploy this up to your site and you’re ready to start sending application errors from your app.  Inside your app you simply need to package up the error and send to your server.

public void SendException(string uri, ExceptionContainer exception)
{
    try
    {
        JsonSerializerSettings settings = new JsonSerializerSettings();
        settings.NullValueHandling = NullValueHandling.Ignore;
        string postStr = JsonConvert.SerializeObject(exception, settings).Replace("\"", "'");
 
        WebClient client = new WebClient();
        client.Headers[HttpRequestHeader.ContentType] = "application/json";
        client.UploadStringAsync(new Uri(uri), postStr);
    }
    catch { }
}

Remember that you should ask the user if you can send error reports, or give them the option to turn it on or off.

Tags: , , ,

Creating a minimal Web API web project

by Shawn 10. May 2012 00:44

The ASP.NET web projects have a history of being bloated. Phil Haack created a Really Empty ASP.NET MVC 3 Project Template. The same is true for MVC4 and the new Web API. The “Empty” MVC 4 Application (using razor) has 37 references, 16 JavaScript files, 15 CSS files, 13 images, 3 razor files, and a partridge in a pear tree. This is far from empty. But it does give you everything you could need to build out your own MVC application. The Web API MVC 4 Application has all of that plus two controllers (one API and one view), and one more razor file.

I wanted to create a simple project that would allow me to take advantage of the awesomeness that Web API brings but without all the overhead of MVC or anything else. I asked Glenn Block if he knew about anything out there that talked about the smallest possible Web API project. This started a couple of educational conversions in which Glenn brought in other great Web API minds.  He quickly stated that I could use self host. For one, I was surprised by this answer because I had asked about the smallest package to put on a server. I had thought that self host was for when you are not on a server. He explained that worker role on Azure uses this because IIS is not present. At this point I had two answers from Glenn and quickly realized I know nothing about this stuff!

So, what is the minimal package needed to deploy a Web API “site” and why does it matter? The reason I wanted to know was to remove the need to upload 30+ assemblies to any server that I may deploy to. I did not want all of the JavaScript and CSS files and yadda yadda yadda.

This post will focus on getting the minimal package needed when using a web application, and not self hosted. A later blog will focus on self hosting on the server. First step, download the new ASP.NET MVC 4 beta or Visual Studio 11 beta. Open up Visual Studio and  create a new project. Select ASP.NET Empty Web Application from the Web item on the left.

image

In the Solution Explorer, remove all of the references except for System and System.Web. If you’re a GUI guy (and don’t always know the ID of the NuGet package you want) open the NuGet Package Manager and search for “aspnetwebapi” in the online section. Select the “Microsoft ASP.NET Web API” package.

image

If you’re a command line junkie, open the Package Manager Console and

PM> Install-Package Microsoft.AspNet.WebApi

Add a Global.asax file to the project and you’re done!

This package adds two more assemblies than the Microsoft.AspNet.WebApi.Core package. One of these is the System.Web.Http.WebHost assembly. This assembly provides five helpful classes for doing development. While this is not required, I do recommend it to make your life a little easier.

From here you have a base project to start building your Web API. I like to have my classes neatly filed away, so I still created a Controllers folder to store all of my controllers.

This leaves you with nine references, one Global.asax file and however many ApiControllers you need and that’s it (plus your web.config file of course)! You could remove some of the references from that for your very basic Web API sites, but most likely you’ll need them all.

I am also currently working out the kinks to a VSIX installer, you can find out on GitHub.

Tags: , ,

MVC | Web API

About the author

Shawn KendrotShawn Kendrot is a Technical Lead at Telvent, specializing in GIS (ArcGIS) Desktop and Silverlight.

Month List

Page List

DISCLAIMER

The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.