Mocking User.Identity.Name

One of the other issue you might encounter while unit testing your Controller is when you dealing with Identity. Consider the following action method.

public async Task<BarResponse> Foo(BarRequest user)
{
    if (ModelState.IsValid)
    {
        try
        {
            var userName = User.Identity.Name;
            // Do Task
            return new BarResponse{
                
            };
        }
        catch (Exception ex)
        {
            return new BarResponse { ErrorMessage = ex.Message};
        }
    }
    else
    {
        var errrorMessages = ModelState.Values.SelectMany(x => x.Errors.Select(c => c.ErrorMessage));
        return new BarResponse { ErrorMessage = string.Join(Environment.NewLine, errrorMessages), modelState = ModelState };
    }
}

One of the issues is how do one mock the User.Identity.Name. The trick lies in creating a Test instance of DefaultHttpContext and replace with Controller’s context. Let’s write an Unit Test for the above code.

var user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]
{
    new Claim(ClaimTypes.Name, "anuviswan"),
    
}, "mock"));
userController.ControllerContext.HttpContext = new DefaultHttpContext() { User = user };

Guess what, I spend atleast 5 hours for figuring out this. Some of the harder days in life.

Writing Unit Test for Model Validation

It is a pretty common pattern to validate your Web Action model using ModelState.IsValid method. For example,

public async Task<UpdateUserProfileResponse> UpdateUser(UpdateUserProfileRequest user)
{
    if (ModelState.IsValid)
    {
        // Valid Model, do your job
    }
    else
    {
        // Send response indicating invalid model
    }
}

A pretty useful pattern, as it makes use of the DataAnnotations to validate and provide meaning messages. One question though that raises is, how do you unit test such a pattern ? The trick lies in emulating the ModelState. You could do with minimal code. For example,

protected void MockModelState<TModel,TController>(TModel model, TController controller) where TController: ControllerBase
{
    var validationContext = new System.ComponentModel.DataAnnotations.ValidationContext(model, null, null);
    var validationResults = new List<ValidationResult>();
    Validator.TryValidateObject(model, validationContext, validationResults, true);
    foreach (var validationResult in validationResults)
    {
        controller.ModelState.AddModelError(validationResult.MemberNames.First(), validationResult.ErrorMessage);
    }
}

With that in place, you could now write Unit Test for your controller as the following

var userController = new UserController(Mapper, mockUserProfileService.Object, null, null);
MockModelState(request,userController);
var result = await userController.UpdateUser(request);

That’s all you need.

Exception Handling in Web API (Part 1): Exception Filter

The Web World, especially Web Services is fast moving towards the more abstract simpler Web API. This article is not focused on comparing Web Service and Web API, but rather it focuses on Exception Handling in Web API.

By default,  the most common exception that an API Controller raises are translated into an HTTP Status Code 500 (Internal Server Error) (HTTP Status Code ). But what if we want to customize the Error Code ? There are couple of ways to achieve it, the first part of this article focuses on Exception Filters.
An Exception Filter is probably the easiest way to handle the exception efficiently and it would handle any exception which the controller throws except for the HttpResponseException (Why HttpResponseException is not handled by Exception Filter will be discussed later).
The simplest way to create you own customized Exception Filter is to derive from ExceptionFilterAttribute Class under System.Web.Http.Filters namespace and override the OnException Method
An Example of Exception Filter is shown below.
public class DemoExceptionFilter : ExceptionFilterAttribute
{
public override void OnException( HttpActionExecutedContext ExecutedContext)
{
if (ExecutedContext.Exception is NotImplementedException)
{
ExecutedContext.Response = new HttpResponseMessage (HttpStatusCode.ServiceUnavailable);
ExecutedContext.Response.ReasonPhrase += " : Function Not Implemented";
}
base.OnException(ExecutedContext);
}
}
The code is pretty self explanatory. I have modified all the NotImlementedException to change the Http Status Code to 503 (Service Unavailable). I have also appended “Function Not Implemented”  message to the Reason Phrase . The next obvious step is to ensure our Exception Filter is used by the WebAPI Pipeline. To ensure that the DemoExceptionFilter is used globally, all we need to do is to add it to the list of filters in WebApiConfig. We use the Filters.Add Method in HttpConfiguration to do the same. For Example,
	public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Filters.Add(new ExceptionManagement.DemoExceptionFilter());
        }
That’s it !!!. Now every Exception your APIController throws , with the exception of HttpResponseException , would have to go through your DemoExceptionFilter. To test the code, I have thrown an exception from my controller as seen in example below.
    public class ValuesController : ApiController
    {
        // GET api/values
        public IEnumerable  Get()
        {
            throw new NotImplementedException ();
        }

        // GET api/values/5
        public string Get( int id)
        {
            return "value" ;
        }
     }
     
Now run your application and check the response in Fiddler.
 NotImplemented
Wasn’t that easy ? Yes, but Exception Filters has its own short-comings, which would be explained in the next part. Happy Coding !!

Hello World in Ext JS and ASP.Net MVC4

Javascript based frameworks has been evolving of late and one of the prominent among them is External Javascript, better known as Ext JS. Unlike some of its competitors like Angular JS, Ext JS distinguishes itself with a rich suite of UI components. It is cross browser compatible. I am delving more into details of Ext JS, and as always, jumping right into the code.

For this post, we would be referring the online version of the ExtJS libraries.

Ok Tim to do some coding. Let’s start by creating a MVC application in Visual Studio.

image

Now open your ‘\Shared\_Layout.cshtml’ and add the following code in the ” section.

These lines refers and includes the CSS styles and ExtJS library. Like mentioned earlier in the post, we would be referring on-line version in this tutorial.  The next step is to add the script to call our Hello World Message box.

 

        Ext.onReady( function () {

            Ext.Msg.alert( “Alert” , “Hello world!” );

        });

 

Entire ‘ Section would look like

image

That’s it. You are done. Kick off the application and you will see your first application in ExtJS using Asp.Net

image