17 January 2018

If I Could Tell Only One Thing

If I could give one advice to fellow developer(s) without knowing anything about their background or skill level it would be to turn on Break When Thrown for all CLR exceptions. I have witnessed developers less experienced and more experienced lose too much time trying to pinpoint the location where exception gets thrown.

How to enable the setting

Find it under Debug -> Windows -> Exception Settings

Debug -> Windows -> Exception Settings image

and ensure that checkbox next to Common Language Runtime Exceptions is checked.

Exception Settings window

Now, whenever an exception is thrown, Visual Studio will break and show the line where exception has happened.

Be aware that this setting, together with Just My Code unchecked, might break on a few exceptions which are caught and handled in .NET Framework or referenced libraries.

Impact of the setting

To illustrate difference in debugging experience, let’s look at a sample console application, first without checkbox checked and then with checkbox checked.

using System;

namespace Calculator
{
    class Program
    {
        static void Main(string[] args)
        {
            var result = ComplicatedCalculation();

            Console.ReadLine();
        }

        private static int ComplicatedCalculation()
        {
            try
            {
                return ComplicatedSubCalculation();
            }
            catch
            {
                // log
                throw;
            }
        }

        private static int ComplicatedSubCalculation()
        {
            try
            {
                return SimpleCalculation(7);
            }
            catch
            {
                // log
                throw;
            }
        }

        private static int SimpleCalculation(int arg)
        {
            throw new NotImplementedException();
        }
    }
}

When running this code with debugging (F5) Visual Studio breaks on outermost throw statement.

Not very obvious that it is SimpleCalculation that is in fact not implemented. Also, when looking at the exception here, there is no data available about original call stack which is very useful since it includes values of method parameters.

Often, top level code is wrapped in try .. catch .. so that the application can survive unplanned exceptions.

static void Main(string[] args)
{
    try
    {
		var result = ComplicatedCalculation();

		Console.WriteLine("Result is:" + result);
	}
	catch (Exception e)
	{
		Console.WriteLine(e);
	}
		
	Console.ReadLine();
}

After running the application now, we get the following console output:

So, exception has occurred and all the data is here - file name and line number where the exception is thrown. But in real life, this can be buried in log files and we might even be unaware that the exception has happened. Then it looks more like this:

Now, let’s check the checkbox and run the application:

Debugger helpfully stops on first exception and argument values are available.

Side note

Sometimes, this little gem automatically unchecks itself, so for quicker access shortcut Ctrl+Alt+E is rather useful.

03 October 2017

Who knew than JSON.parse() requires double quotes

The other day we were trying to get a small app off the ground. Sometimes even the simplest things which should obviously work, just don’t work.

The code in question was creating a small object:

var s = '{';
s = s + 'width : 17,';
s = s + 'length : 20';
s = s + '}';

var o = JSON.parse(s);

But after executing, o did not contain an object at all.

(As I write this, call to JSON.parse(s) fails with an exception in Chrome. I am fairly certain that during the development there was no exception.)

After unsuccessfully trying out a few things, a search on the internet revealed that property names must be double quoted. This was a bit surprising, since one can easily asume that whatever Javascript code is valid, it will still be valid when passed as a string into JSON.parse()

Turns out JSON has special syntax which prescribes double quotes.

20 October 2016

Supporting client side AngularJS routing in ASP.NET MVC without a controller

For our AngularJS application, we have perused ASP.NET MVC/WebAPI template. It creates a scaffolding with lots of stuff which is really helpful in the beginning. As our app matured we began to realize that the additional stuff is just a hindrance. Whoever uses WebGrease today? Ditto for Bootstrap installed as a NuGet package.

So we went about tidying up: removing NuGet packages, cleaning up web.config etc. At one point, we wanted to remove HomeController since all it does is serve index.html for requested URLs

Recommendations found online concerning AngulerJS client side routing can generally be divided in two categories:

  • use a HomeController and
  • use URL rewriting

URL rewriting, while powerful, somehow also seems out of place. Not to mention that it relies on regular expressions, of which we are no experts.

Further attempts to force routes.MapRoute to route all URLs to index.html failed since ASP.NET MVC is controller oriented and apparently has to have a controller.

But then, while reading a rather thorough overview of ASP.NET routing, a method MapPageRoute popped up. Our index.html is a page, so maybe this is right. On first attempt, server failed complaining

Server Error in '/' Application.

There is no build provider registered for the extension '.html'

A (bit dirty) fix for this was to rename index.html to index.aspx

public static void RegisterRoutes(RouteCollection routes)
{
	routes.MapPageRoute(
        routeName: "CatchAll",
        routeUrl: "{*anything}",
        physicalFile: "~/app/index.aspx");
}

With this in place, we were able to get rid of HomeController.

A better solution would be to separate front end and Web API in two projects. Front end can then be hosted on whichever web server.