Pages

I've migrated my blog

Thanks for visiting my blog. I am no longer maintaining this and I've migrated the blog to my personal domain . If you would like to follow my blog kindly use my new RSS feed

Friday, June 1, 2012

A hybrid application using ASP.NET MVC3 and Node.js

Each and every technology has its pros and cons and there is no silver bullet!

If you would ask me what you have learnt in your profession so far, I would say the above line as the first one. One technology / platform / language is good at solving one kind of problems and bad at solving other kind of problems. The key is leveraging existing platforms with languages targeted at specific problems and applications to solve the business problems in hand.

Three months ago I have come across an excellent presentation from Neil Ford “10 ways to improve your code”. As a 8th way he talks about “Polyglot Programming”. Its about picking the right tool to do the right job. I am inspired by this presentation and started exploring the “right tools”.

In the pursuit of “Right tools”, I’ve come across the young awesome framework node.js which is really cool and perfect for real-time applications. On the other hand frameworks like ASP.NET MVC3 is not meant for creating real-time applications and they address different set of other problems.

In this blog post, I going to share my recent exploration on leveraging node.js in an ASP.NET MVC3 application using a “Chat” feature. Though we can achieve it using SignalR, I’ve preferred node.js as it is a right tool for the chat feature IMO also I wanted to get my hands dirty in creating a hybrid application.


The Node.js Part

image

The chat server that we are going to use in the MVC3 application has been created using socket.io which makes web-socket programming insanely easy!
Its listen for three events
  • join – It will be triggered when a new user joined the chat and it broadcast the user name to all the connected users
  • message – It willed be triggered when an user send a message in the chat application and broadcast it to the other users
  • disconnect – It willed be triggered when an user closes the chat or closes the browser
That’s it bang!


The ASP.NET MVC3 side

image

The controller side of Chat just renders the “Index view”. The index view has the following javascript code, and it completes the client side part of the chat application

image


Chat feature in Action

imageimage
image
image
image
image


Summary

The objective behind this blog post is just to share the knowledge that I’ve gained in my recent exploration and its just a proof of concept of how to leverage node.js in an MVC3 application. The bottom-line is “Identify and pick the right tool to do the right job”. If you want to play with the source code, don’t forget to clone the repository in my git-hub page.  

Saturday, May 19, 2012

Jade Visualizer using Node.js and Socket.io

Hurrah! Finally I made it

“None of my inventions came by accident. I see a worthwhile need to be met and I make trial after trial until it comes. What it boils down to is one per cent inspiration and ninety-nine per cent perspiration”  - Thomas Alva Edison

Today I’m very glad and excited to announce my little contribution to the open source community called “Jade-Visualizer” a web-based visualizer/translator which targets the beginners of Jade (A widely used Node.js view engine) to learn it effectively.

Its the inspiration from good bloggers, kindled me to start writing blogs and Its the inspiration from many people who are all contributing to the open source community, encouraged me to kick start my contribution through this tiny web-app. This is my first step towards a great journey of more than 1000 miles and I hope it would lay a firm foundation.

What is Jade?

Jade is a high performance template engine for Node.js and the default rendering engine for the express framework. If you are from the ASP.NET MVC background (like me), its similar to Razor view engine. Unlike razor, Jade is less verbose and easier to read.

Why Jade-Visualizer ?

W3schools is my starting point and reference when it comes to basics of web development. I have learned and toyed with JavaScript, html, css in my early days using the “Try it yourself” feature available in their website. It is very intuitive to use and we can learn effectively by actually getting our hands dirty. Also, the immediate output of what we do would certainly help us (helped me!) to understand things much better.

I am a kind of “Show me the code” programmer, would love to play with code rather than learning by just theory. When I am learning Jade, I found it very interesting as I never exposed to haml kind of syntax. To learn it, I’ve created a sample web-page in node.js and for each feature in Jade, I’ve modified the jade page and understand its behaviour by seeing the html source in the browser.

One day after toying with Jade for quite some time, I’ve went to bed and it strikes. “How nice it would be to have a “Try it yourself” kind of feature for learning jade ?”  and hence Jade-Visualizer

How to use Jade-Visualizer ?

Jade-Visaulizer is a single-page app, with only three parts.

1. The Jade Template – A textarea to play with the jade-template

image

2. Data – Want to mix some data with the jade template ? It is for you. Enter some hacky data in JSON format in it and start toying!

image

3. Output – Excited about what would be the generated output ? This part will help you to feed your brain.

image

Don’t forget to click the “Translate” button to view the html Smile

Behind the Scene

Curious about what are all the things behind this app ? Here is the list

Why Node.js ?

There are lot of fuss about Node.js in the industry. Will it scale ? Is it insanely fast ? JavaScript on server side ? Will it work out?. I am not going to answer for these questions and I am not a expert too! I believe a simple google search will help you much much better than me. Then why this section in this blog post ? Let me explain

I would like to add an another flavour to Node.js by putting my words on why you should learn Node.js especially if you are from a .net background like me

  • I’m using Ubuntu to play with node.js – Node has helped me to come out from windows and inspired me to work with Linux for the first time in my life
  • I’m using Vim to write node.js apps – Awesome editor! I am regretting myself for not using this so far. Its my default editor even in windows now 
  • I’m using Github as a version control to store my nodejs katas
  • I’ve full control over my apps in node.js – Its helping me to learn some of the under the hood stuff which I never learnt before. Source code of Jade-Visualizer is an excellent example for this. I am using my own module to serve the static files. Yes, I’m re-inventing the wheel. But I am learning, That’s good for myself!
  • I’m a part of vibrant community – I’m having a sense of belonging feeling
  • I’m getting better at javascript – I love this tricky language and its really twisting my programming brain
  • I’m getting exposed to various frameworks, tools, datastores, techniques, skills every day which I like very much
  • Last but not least, its helping me to contribute back to the community

Note: Its just my personal views, I’m just sharing what are all benefits that I am reaping by virtue of Node.js.

Summary

I would like to conclude this blog post by dedicating the “jade-visualizer” to all the open-source contributors in the planet. Its you who inspired me! Hearty thanks to one and all Smile

Friday, April 13, 2012

An interesting JSON Model Binding behaviour in ASP.NET MVC3

Introduction

Model Binding is one of the coolest feature in ASP.NET MVC3. Like a magic wand, your form element values, JSON values, also query string values automatically get converted to the equivalent C# object and makes the life of the developer easier.

The default behaviour of MVC3 model binding works well in more common scenarios. But in certain cases it wont work as expected, and in such situations we need to write custom model binders. Two weeks before while I was working with model binding on JSON values, I’ve encountered an interesting behaviour of JSON model binding.

If a JSON property contains a string, it get bind to a string property of the equivalent C# object. But if that same JSON property contains a empty string, while model binding, the equivalent C# object’s property is assigned to null and not to empty string! The same happened with arrays. If it contains elements, it get bind without any problems. But if the array is empty it get bind to null!!

In this blog post, we are going to get rid of this intriguing behaviour by writing a Custom JSON model binder. Hope it would be useful and save you some hairs Smile 

The Sample Application – “MyMobileStore”

In this blog post we are going to see a small application called “MyMobileStore”. This sample app has two features. One will help you to search the mobiles in the “MyMobileStore” by using the company name and the mobile types. An another feature will help you to find out the sales details of the mobiles from a given company for the specified mobile types.

Show me the code

Core classes

MobileStore.Models 

As mentioned earlier, the two features of “MyMobileStore” are exposed as controller action methods as below

MobileStore.Controller

Both action methods uses a parameter of type “MobileFilter” which actually holds the filter criteria for finding out the mobiles. It has two properties, the companyname of the mobile and the collection of mobile types (Normal, DualSim or SmartPhone)

MobileStore.MobileFilter

The SearchMobiles action method retrieves all the mobiles from the repository and filter it first by the company name and then by the mobile types. One small tweak, if the mobile types count is more than 3, it would take only the first 3 types (Added for demo purpose). I just left the logic of SalesDetails action method blank to keep it simple. Both actions returns a JSON result to make them consumed by ajax.

(Note: I’ve violated some design principles in the sample code as I just wanted to make this blog post as simple as possible)

The Problem (Opportunity in my language)

In a good world, if the user selected either or both the company name and the mobiles types to be filtered, then our controller in “MyMobileStore” will happily accepts them as a parameter and continue its work without any mishaps.

GoodWorld

But in the bad world, if the user missed out either the company names or the mobiles types or both, ASP.NET MVC3 treat them as nulls which might cause null reference exception and breaks the functionality!!

BadWorld

NullException

(Now you might have understood why I added a tweak in the number of mobile types Smile)

Possible Solutions

  1. Perform null check inside the “SearchMobiles” action method and assign empty array.
  2. Write a Custom Model Binder for “MobileFilter” and perform the null check inside the model binding logic

Though the option 1 is a simple and straightforward thing, what would you do if the “SalesDetails” action method works with the mobile types collection. You certainly need to duplicate the null checking inside it also. Let us assume that we have some more action methods in our “MyMobileStore” which has “MobileFilter” as their parameter. Do you still duplicate the null check there ?. Think!!

If you do so, I am sorry my dear friend, you are violating the DRY principle and creating a broken window in your codebase! So, lets go ahead and write clean code by making use of Custom Model Binder for our “MobileFilter”.

The Pragmatic Solution – MobileFilterModelBinder

MobileFilterModelBinder

Our custom model binder is very simple, it just makes use of Default Model binding behaviour. After the default behaviour has been done, it checks for null values using Null-Coalescing operator and assign empty values if the values are null.

Don’t forget add the custom model binder in the Global.asax.cs file.

Global

Now our “MyAppStore” is robust enough to tackle the bad world!!

NoMoreBadWorld

Conclusion

In this blog post you have seen an exciting problematic behaviour of JSON model binding in ASP.NET MVC3 and a simple way to get rid of the default model binding problems. In my next blog post I would share my experiences in how to unit test this custom model binders. You can download the source code that I have used in this blog post from here.  

Sunday, March 4, 2012

Unit Testing Html Helpers in ASP.NET MVC3–The Cleaner Way

 

Would you like if your unit test have an assertion like this ?

image

IMHO having a unit test assertion like this with a long magical string value would become a maintenance problem with additional logic being added. It breaks with even minor changes like “adding an extra whitespace” though it is logically correct(Browsers ignores the whitespaces while rendering html)!. It is harder to debug to!!

How can we get rid of this long string assertion ? Is there any better way to do assertion against this long magical string ejected from a HtmlHelper ? One thing which strikes on my mind when I come across this problem is why don’t we parse the string as an xml and assert against the xml element instead. It might appear like laborious at the first sight, but by making use of XElement and extension methods we can easily do that. In the blog post we are going to see how can we implement this in a more cleaner way.

Okay.. Enough texts.. Its time to see some code!!

The first step is to convert the “html string” returned by the html helper to XElement. Generally most of the helpers returns MvcHtmlString, So, we can easily achieve this by writing an extension method called “ToXElement” on MvcHtmlString.

image   

That’s it! All set to redefine the way custom html helpers are being tested.

Fine, Let us see it in action. We will start with a handy HtmlHelper method called “Button” which would render a “Html button tag” and here is the test to assert it.

image

The first test uses the ToXElement extension method and assert against the XElement’s properties whereas the second test uses the “magical string with tags added” to do the assertion. Now you may feel what’s wrong with this guy the second test look clean to me, why he is making fuss about it. Yes you are correct, the second one looks clean. But it appears to be clean as the requirement in hand is very simple.

IMHO the custom html helpers that we are building in our real world application won’t be as simple as having a button tag with just plain caption in it.

Fine, lets see the real world. Voice from your team lead

Hey! the Button HtmlHelper you designed has did a tremendous job. Can you make a small change on it so that it would generate a button with a class attribute having the value ‘appbutton’ by default. We need it because it make the button styling consistent with rest of our application ”

Let us implement the feature by starting with the test for it

image

Now tell me is the second test clean ? I don’t think so. The generate html string is bit long now also having double quotes inside double quotes makes it hard to read. At the same time the first test remains robust and clean.

Still not convinced, okay just go up and see the very first test that we have wrote to test the button caption. Do you think the hard way test with the “long magical string” still pass ??

It would fail

Why ?? Here is the error message

image

Now what would you do, if you decided to persist with the “long magical string”, then your action would be editing the test as below

image

Nice job. Now tell me what is the difference between this one and the below one

image

Apart from the test method name everything is same. Is the test clean ? Is the test clearly saying what it is trying to assert ? What would happen if we got the requirement to add one more attribute or even more? Think !!

But at the same time the tests which written using XElement assertion would remain healthy and their test method name mean what it is testing

image

I leave it you to decide which one is cleaner.

Summary

Here is the implementation of “Button HtmlHelper” that we unit tested so far

image

My humble request to the readers of this blog post, please take care of your “Unit tests” and give some more importance to it. An hour spent upfront would save a day in future.  

“Beauty is in the eye of the beholder”, If you have a better idea to do the same, kindly leave a comment, I am open to learn from you.

Saturday, February 11, 2012

Unit Testing Custom Model Binders in MVC3

 In my previous post we have seen a way to do unit testing with Sessions in MVC3 using Custom model binders. In this blog post we are going to see how to do unit test the model binder itself.
One remarkable thing which everybody hails in MVC3 is its extensibility and its testability. You can extend/customize the components in the framework and also you can unit test them with ease.
Before getting into unit testing the custom model binder, Lets have a closer look at the BindModel method

image

In the BindModel method we are making use of Session property in the HttpContext object which is in turn a property of the ControllerContext object that is passed to the BindModel method as a parameter by the MVC3 framework. In order to unit test this method we need to have to control over the HttpContext property of the ControllerContext and the Session property of the HttpContext.

How to get control over those properties ? Thanks to a constructor of ControllerContext

image

ControllerContext uses the constructor dependency injection to get rid of the direct dependency on HttpContextBase and we are going to exploit this to do unit testing. Using a mocking framework we can easily create a mock of HttpContetBase and drive the unit test.

The Session property of the HttpContextBase is of type HttpSessionStateBase which can also be mocked.
Here is the complete implementation of Test fixture class which unit test the CartModelBinder class that we have seen in the previous post using the mocking library Moq.

CartModelBinderTests

I hope the test code is self-explanatory.

Thursday, February 2, 2012

Unit Testing with Sessions in ASP.NET MVC3

Introduction


While talking to my friend regarding his project, he told me about how he is doing unit testing which involves sessions in ASP.NET MVC3. His team is actually using a “HttpSimulator” which simulates the web request and then the do unit test by verifing the session by interacting with the simulator. When digging further I have come to know that this way of unit testing session objects are influenced from the “ASP.NET Webforms”. It reminds me the talk of Neil Ford on Function Programming. In that video he talks about an analogy called “Axe and Chain Saw” to explain our way of thinking as

When we give a chain saw to people who were cutting trees by axe, they would tend to use chain saw in the same way as the use Axe. Which is obviously inefficient. So we should understand at the capabilities of the tool in our hand before we using it”. 

ASP.NET MVC3 is far better than Web Forms when it comes to unit testing. We don’t need to use a simulator to test against our sessions. There is a better way to do this MVC3 and in this blog post we are going to explore it.

Time for Code

Shopping Cart is the first thing that strikes our mind when we want to quote an example for using Http session. So, I am going to show an app called “MyShop” a mini shopping site through which I am going to explain the concepts involved. The application flow would be as follows


image
image


Models

The models are simple, straight forward and self explanatory.
image
image

I’ve tried my level best to keep the model as simple as possible. So, Cart in MyShop will have only two public methods. One to add a product to the Cart’s Line and another one to retrieve all the products inside the Cart’s line.


The CartController Version 1.0

image

In this CartController version 1.0 we have two public methods Index and AddToCart which are dependent on HttpSession object. This dependency inside the methods is actually preventing us from unit testing the CartController in simple way and we have no choice other than implementing a “Http Simulator” to unit test these two methods. As I said before there is better to do is! Here we go!!


The CartController Version 2.0

image

No more Sessions!!.. Yeah.. We have got rid of the dependency on the session object by adding a new parameter called cart. Now you can use easily unit test the CartController as follows

image

Okay we made it easy for unit testing by moving the dependency out of the method and introduced the cart as the parameter. But how does my MVC3 framework will know the cart parameter should come from session object ?… Good Catch!! and here comes the magic called custom ModelBinder


ModelBinder – A brief background

Model binding is an exciting feature in MVC3 framework which automatically creates the C# objects directly from Http request and pass it to the Action methods in controller as parameter values. It uses a default model binder which looks at the form values, query string values that are submitted with the Http Request and create the model object.


CartModelBinder

In our case, we need to have a object of Cart which is populated from the Session object and not from the HttpRequest. The default model binder used by MVC3 has no idea about session object. So, Its our responsibility to tell to the MVC3 framework

Hey! If there is any parameter of type Cart in controller action method, then use my own custom model binder called CartModelBinder to create the object

There are two steps to do the above said operation

1. Creating the custom model binder by inheriting the IModelBinder interface

image

2. Registering our custom model binder in the Global.asax.cs file

image

That’s all.. MVC3 takes care of rest


Summary

In this blog post we have explored how we can get rid of “Http Simulator” to unit test the controllers which involves Session objects using custom model binder. You can download the working example of “MyShop” showcased in this blog post from here. Refer my next blog post to check out how to do unit testing with the custom model binder itself.