Saturday 31 December 2011

Analyzing routing in your MVC application

Routing and ASP.NET MVC woes !!!

So you have created a MVC application and worked on it a bit, and now your Global.asax contains calls to a setup of your RouteCollection that has got complex logic inside it and now you need to understand your routing better and perhaps fix that particular scenario where routing does not seem to work (keep in mind for instance that the first match algorithm is used when using your MVC routing table). How to understand those routes in a better way without staring at your code. How about interpreting it at realtime using a runtime debugger for just that case. First off, download the
ASP.NET MVC Routing Debugger Visualizer tool.

Go to the following url:
http://visualstudiogallery.msdn.microsoft.com/2993e666-4534-49c8-807f-e8bffcaee7e0

Keep in mind that this should be easily installed in Visual Studio 2010 using the Tools => Extension Manager dialog in DevEnv.

Now we need to "patch" your system to allow this tool to work.

First off edit the devenv.exe.config file to allow loading remote sources:
Open the file
C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe.config

Inside the runtime xml element node add the following:
<loadFromRemoteSources enabled="true" />

Just to double check, check that the dll is added to the following folder:
C:\Program Files\Microsoft Visual Studio 10.0\Common7\Packages\Debugger\Visualizers

There should now be a file called MvcRouteVisualizer.dll in this folder, this is the library which constitutes the ASP.NET MVC Route debugger visualizer tool.

Start the MVC application with debugging turned on and add a breakpoint in a MVC controller action, I tested this tool out with the HomeController About action in my basic templated ASP.NET MVC application for instance. Hit Ctrl+D+Q (quickwatch) and add a watch to the System.Web.Routing.RouteTable.Routes object (which is a collection of the routes to monitor for our app) and hit the available magnify icon button to the right of the value column of our watch window in our debugger.

If all now went well, you should have this nifty tool to display the routes in our MVC app. This way, if the routing seem to have gone berserk and you cant understand why your nice routing table is not correctly set up, MVC Route visualizer routing tool comes to your rescue.

Here is a screenshot of this great tool, happy coding!

Thursday 29 December 2011

Creating custom ActionResult

It is possible to inherit the ActionResult class and create a custom ActionResult.
The following class creates a new kind of ActionResult for spewing out the serialized string of an inputted data contract instance.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Runtime.Serialization;

namespace TestActionMethodSelectorAttribute.ActionResult
{

public class DataContractSerializedResult : System.Web.Mvc.ActionResult
{

private object data;

public DataContractSerializedResult(object data)
{
this.data = data;
}

public override void ExecuteResult(ControllerContext context)
{
var response = context.HttpContext.Response;
response.ContentType = "text/xml";
DataContractSerializer serializer = new DataContractSerializer(data.GetType());
serializer.WriteObject(response.OutputStream, data);
}
}

}


You will need to add a reference to the System.Runtime.Serialization assembly and namespace. We use DataContractSerializer to serialize the object to a string value. The stream in use is the context.HttpContext.Response.OutputStream, where context is the ControllerContext (current).

It is required to set the ContentType to "text/xml" to output xml.

Usage, adding a test method to homecontroller (ignore Hungarian notation, this is for demonstration purposes..) :


public DataContractSerializedResult About2()
{
return new DataContractSerializedResult(
new AgeNameDataContract
{
Age = 93,
Name = "Gamla Olga"
});
}


Then we get the xml outputted of the data contract passed in:



The morale of the story, to create a new kind of ActionResult:

- inherit from ActionResult
- implement abstract method ExecuteResult

Timing your MVC Actions

Add the following attribute to your MVC actions to view the timing of your mvc actions using System.Diagnostics.Stopwatch class.

This is another filter attribute example.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Diagnostics;

namespace TestActionMethodSelectorAttribute.Attributes
{
public class StopwatchAttribute : ActionFilterAttribute
{
private Stopwatch _stopWatch;

public StopwatchAttribute()
{
_stopWatch = new Stopwatch();
}

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
_stopWatch.Start();
}

public override void OnActionExecuted(ActionExecutedContext filterContext)
{
_stopWatch.Stop();
var response = filterContext.HttpContext.Response;
response.AddHeader("X-elapsed-milliseconds", _stopWatch.ElapsedMilliseconds.ToString());
}
}
}


Usage (homecontroller):


[Stopwatch]
public ActionResult About()
{
return View();
}


It is nice to output the elapsed time in millisecond in the http headers, since we then easily can monitor the values outside Visual Studio, in our browser: