After Thought

Archive for May 2009

Switch between View Result and Json Result without sweat in FubuMVC

with 3 comments

Kazi Manzur Rashid wrote a great post on Adaptive Rendering in MVC that is used to return the result based on the request using the same action method. The clear advantage here is that you avoid duplicating your code in the action method just to cater to different request types (like ViewResult, JsonResult).

Chad Myers recently added a feature to FubuMVC that makes adaptive rendering seamless. We will continue to use FubuMvcSampleApplication to demonstrate this feature. First let us add the action convention wire_up_JSON_URL and behaviour output_as_json_if_requested to ControllerConfiguration.Configure() method that is called from our BootStrapper class. Adding wire_up_JSON_URL will simply add another URL (*.json) for every action. For example, if we have a save action, this will add another url save.json during the setup. Now our action responds to url save as well as save.json. output_as_json_if_requested overrides the conventional result and displays a Json result if it is a Json request.

// Action conventions
x.ActionConventions(convention =>

// Default behaviour for all actions
x.ByDefault.EveryControllerAction(action =>

// add a behaviour to output as Josn if it is a json request
x.ByDefault.EveryControllerAction(action =>

We will now go ahead and implement our action method. For simplicity sake, we will implement a Display action that simply returns UserDetails for the given UserId. Let us add a small piece in action method for the sake of demonstration that populates the Message with either Json Result or View Result based on where the request is coming from.

public UserEditViewModel Display(UserEditViewModel userEditViewModel)
  User user = _userRepository.GetUser(userEditViewModel.UserId);
  return new UserEditViewModel(user)
    Message = userEditViewModel.IsAjaxRequest() ? "Json Result" : "View Result"

Now let us add a view Display.aspx to demonstrate this feature.

<%= this.FormFor((UserController controller) => controller.Display(null))%>
 <legend>User Details</legend>

Enter john_doe or user2

 <%= this.TextBoxFor(user => user.UserId).ElementId("UserId").Required().WithLabel("UserId")%>
 <input type="button" id="DisplayUsingJson" name="DisplayUsingJson" value = "Display Details Using Json" />                    
 <%= this.SubmitButton("Display", "Display").Class("button") %>

 <%= this.TextBoxFor(user => user.LastName).ElementId("LastName").ReadOnly().WithLabel("Last Name") %>

 <%= this.TextBoxFor(user => user.FirstName).ElementId("FirstName").ReadOnly().WithLabel("First Name") %>                    


Enter a user_id and click on Display button to display user details using default behaviour (View Result).


Add the following javascript (uses jquery) that is fired when a user clicks on Display Details using Json button.

function Display() {
 var user = {};
 user.UserId = $("#UserId").val();

 $.getJSON("Display.json", user, function(user) {

Clicking on Display Details using Json button calls the action method Display using the other url “Display.json” that is used by Fubu to identify where the request is coming from.


We just saw how easy it is to switch between JsonResult or ViewResult. It is features like these, that make FubuMvc a very effective and powerful alternative to MVC. I have added the above feature to FubuMVCSampleApplication project and you can download the source code here.


Written by shashankshetty

May 25, 2009 at 7:20 pm

Using ExcelMapper

with 5 comments

ExcelMapper is a tool to create and access data from excel (*.xls and *.xlsx) as a collection of strongly typed objects.  Here is  brief description on how to use it:

BuildDtosFromExcel.exe is an exe file used to generate an assembly of strongly typed objects. Each class is equivalent to a worksheet in an excel file. For instance, User tab in excel is mapped to User class and each of the columns is mapped to properties in the User class.


To create a User class, run the following command:

BuildDTOsFromExcel User.xlsx

The command generates ExcelToDTOMapper.DTO.dll assembly that contains User class as shown below:

 namespace ExcelToDTOMapper.DTO
   public class User
     public System.Double Id { get; set; }
     public System.String LastName { get; set; }
     public System.String FirstName { get; set; }
     public System.DateTime DateOfBirth { get; set; }

If you want to create an assembly of different name, you can pass an [optional] assembly name. You can get the complete usage of BuildDTOsFromExcel by running BuildDTOsFromExcel /?.

You can now add this assembly as a reference to your project along with ExcelMapper.dll, Microsoft.Practices.ServiceLocation (available in the download) to access data from Excel.


Finally, add the following piece of code in your application.


  IRepository repository = ServiceLocator.Current.GetInstance<IRepository>();

  foreach (User user in repository.Get<User>("Excel\\Users.xlsx", "User"))
     Console.WriteLine("Hello {0} {1}", user.FirstName, user.LastName);

ExcelMapper.SetUp() should be done only once in the whole application. If you are using StructureMap as your IoC tool, then you can add the ExcelMapperRegistry in your BootStrapper code as show belo:

public static void Initialize()
   ObjectFactory.Initialize(x =>
          x.Scan(s =>

If your running on a 64 bit machine, remember to compile your code in x86 platform. Executing the above code results in the following output:


Since repository.Get<User>(“Excel\\Users.xlsx”, “User”) returns IEnumerable<User>, you can use Linq.

Written by shashankshetty

May 9, 2009 at 2:56 pm

Reading excel spread sheet as strongly typed objects

with one comment

Recently, I was working on a prototype application that required data to be read from many different Excel spreadsheets (both xls and xlsx versions) each containing a large number of worksheets.  I started with the usual way of creating one DTO (Data Transfer Object) for each worksheet and then pulling the data from Excel through OleDBReader. It became repetitive to do the same thing over and over for every single worksheet. After quick thought, I decided to write a simple tool that can solve this problem of data access (as I didn’t want to spend a lot of time just building the infrastructure) .

The end result is a tool that can generate an assembly containing Strongly Typed DTO’s by querying the excel (as I didn’t want to create them manually) that can then be included as a reference in our project and a library that provides methods to query the excel data through a single repository class. By abstracting out the DTO generation and accessing data from excel, I can now concentrate on building the prototype application that can deliver some business value.

Code for this is available on Git Hub:

Download the BuildDTOsFromExcel.exe and ExcelMapper.dll with an example usage here.

You can read a brief description on how to use ExcelMapper here

We can definitely improve this tool further, but it works if you are looking for a quick solution to query the excel sheets. If you are interested in improving this tool, please feel free to comment.

Written by shashankshetty

May 8, 2009 at 9:25 pm