26 September 2010

ASP.NET MVC 2 Unit Testing

ASP.NET MVC frame work is designed to be very testing friendly. Here we are trying to understand the easy testing aspect of the MVC Framework.For that we are going to build our test application on top of the sample application that we tried out in part2. So recommended to have a look on that for a better understanding.

Why we need to do unit testing ?
Million dollar question! Testing is needed mainly because it's an automated way to make sure the piece of code is always behaving the way it is supposed to behave. This way we can make changes to the code and re factor pieces of the application without the fear of breaking something somewhere else in the application.This question looks silly but was the first one which came to my mind when I was writting this , hope the readeres excuse me!

Why testing is a pain with traditional ASP.NET web forms?
If you wrote unit testing in classic web application it really sucks.One of the reasons of the classic approach to developing web applications with .NET, the WebForm approach, is not easily testable: it's because the main class of ASP.NET, System.Web.UI.Page, has dependencies to HttpContext, HttpResponse, HttpRequest, HttpCookie and all the other objects coming from the fact that the Page is being executed inside a web server. And all these classes are "just" concrete classes, and cannot be replaced by fake implementations for the purpose of testing the web applications outside the context of the web server.

What makes ASP.NET MVC very good for TDD?
If the controller got a method call and it does not care about who called it then you could go and call inside of a test file and that how testing framework works. On top of this MVC made separation of components.

Code Sample?
We will discuss how to build three different types of unit tests. basically how to test the view returned by a controller action, how to test the View Data returned by a controller action, and how to test whether or not one controller action redirects you to a second controller action bla... bla... bla...
So in a nut shell  we need to test following things. 
  • Test Routes
  • Test Controller
  • Test Views.
  • Test Model
  • Test Functionality

Right click on controller folder under test project and add EmployeeControllerTest.cs.See the sample code that we need to add in this class.
[TestMethod]
public void EmployeeList_Action_Returns_View()
{
    // Arrange 
    var EmployeeController = new EmployeeController();
    // Act 
    var result = EmployeeController.EmployeeList();
    // Assert 
    Assert.IsNotNull(result, "Should have returned a ViewResult");
}
[TestMethod]
public void AddEmployee_Action_Returns_View()
{
  // Arrange 
  var EmployeeController = new EmployeeController();
  // Act 
  var result = EmployeeController.AddEmployee();
  // Assert 
    Assert.IsNotNull(result, "Should have returned a ViewResult");
}
[TestMethod]
public void TestCreateEmployee_Method()
{
   EmployeeDAL empDAL = new EmployeeDAL();
   List<EmployeeModel> employeeList = new List<EmployeeModel>();
   employeeList = empDAL.GetAllEmployees();
   // Assert 
   Assert.IsNotNull(employeeList, "Should have returned a Employee    Collection");
}
[TestMethod]
public void Add_Employee_Action_Returns_RedirectToRoute_Result()
{
   // Arrange 
   const string expectedRouteName = "EmployeeList";
   EmployeeModel emp = new EmployeeModel();
   emp.EmpName = "New Employee";
   var EmployeeController = new EmployeeController();
   // Act 
   var result = EmployeeController.Create(emp) as RedirectToRouteResult;
            // Assert 
   Assert.IsNotNull(result, "Should have returned a RedirectToRouteResult");
   Assert.AreEqual(expectedRouteName, result.RouteName, "Route name should have been {0}", expectedRouteName); 
}
Our all tests related to employee controller will be in this file.  And finally run the project and you are going to get the test results like this.

So as a conclusion we have seen some theories and code samples for building and testing MVC applications. These are the basic levels of information’s and we need to go more deep dives for better understandings. Anyway I am not quitting my  journey on MVC Framework here rather decide to take a long drive on it. In future MVC is going to rule in web development and as a developer I need to upgrade myself to this more and more. As always if you have any queries you are most welcome. 

25 September 2010

ASP.NET MVC 2 Code Sample

Sample Project
In the previous section we piece the theories together and tried to understand what is MVC and why we need to learn this programming architecture. So before reading this piece I would recommend you to go through the ASP.NET MVC Introduction Part 1 link for some basic theories. OK, now let's start with building a sample application. 

Prerequisites
If you are in VS 2008 you need to download ASP.NET MVC 2. Click here to download release candidate for .NET 3.5 and VS 2008.With VS 2010, it is already shipped and has an automated upgrade wizard that can automatically migrate your existing ASP.NET MVC 1 applications to ASP.NET MVC 2 for you. Also remember MVC 2.0 can be installed side-by-side with ASP.NET MVC 1.0 on the same machine.
Ok, let’s get start with. Open your VS IDE 2008 go to File > New Project > ASP.Net MVC give it a name I named it SampleMVC. A dialog box will prompt you to create test projects. If you are a bad programmer skip the test project.
Now have a look at the project structure that created by MVC frame work by default.

The structure of your Project
if you explore the solution that we created there are three main folders – Model, View, and Controller. Views are nothing more than .aspx pages. Other folders here are content folders which can hold resources files, images and Model folder can be represented by entity classes, can be also represented by data table’s data sets etc. This is more related if you are doing data driven based programs. Script file as name indicates can hold JavaScript files. And also you can see another test project if you selected the options for the same while creating project. To create more controller and views right click on the folder and will give you options to create both. So we are created our first ASP.NET application on MVC 2.0 framework!!! Let’s go home!
1. So take the homeController.cs now. In this controller class MVC framework has created 2 new ActionResults by default.One named Index, and one named About. These are nothing more than calling a View titling their names.
2. Inside Index we have a View Data, which is nothing more than a way for a controller to pass data to the view.
3. Inside the view of Index you see that there is that ViewData ["Message"] using the Html.Encode is just a way of accessing the ViewData.
Before that you might be noticed one interesting thing in the web URL something like http://localhost:1744/Home/About . If you have a classic asp.net back ground you might be asking where is the .aspx extension?  That is what MVC routing is coming to picture and we already discussed in part1.
Ok we are done with the basic stuff. Now let’s come out and think in terms of real time scenarios.See the screen shot for now.

How to do CURD operations?
Now being in this frame work we are going to see that how we can add a view, Model and controller by giving a sample CURD operation.
We will create a sample application which has following things.
  1. A basic view which has look up values from DB. - EmployeeList.(View1)
  2. Take the user inputs and save it to DB. - AddEmployee.(View2)
  3. Read the updated DB and display on EmployeeList.(View1)
To start with we need a data model. But we are not going to worry much on the data model as this framework is going to talk with all most all databases with almost same manner. To take with a simple example I am going to have an employee data model and save and retrieve to an xml file.
In order to add the new view first I am going to add a menu item for my employee view. Go to Site. Master files under shared folder and add this line.
In the Action link we need to specify what action it should take and what the routing values are.
Now we need to handle the action in Controller class, for keeping the modularity we are creating separate controller class called EmployeeController.cs. Microsoft recommends putting your Controller classes underneath the /Controllers directory, (also data model classes underneath your /Models directory, and your view templates underneath your /Views directory). 
Let’s go ahead and add our action in it as a method in the controller class and add a view of the same name what we have given for method. Rich MVC template will guide you all these actions. Now we have following classes ready in general.
  1. EmployeeDataModel.cs - It could be a simple data model.
  2. EmployeeDAL.cs - This class is to read/ write data model to xml file.
  3. EmployeeControoler.cs
  4. EmployeeList.aspx
We are not going to explain the files one and two as it is nothing but having an employee data model and read/write logic to xml file. But See the code in other file:
EmployeeController.cs
public ActionResult AddEmployee()
{
   EmployeeDAL empDAL = new EmployeeDAL();
   List<string> allRoles = new List<string>();
   allRoles = empDAL.GetAllRoles();
   EmployeeModel empData = new EmployeeModel();
   ViewData["Roles"] = new SelectList(allRoles);
   return View(empData);
}
[HttpPost]
public ActionResult Create(EmployeeModel employeeModel)
{
  if (ModelState.IsValid)
  {
    EmployeeDAL empDAL = new EmployeeDAL();
    EmployeeModel empData = new EmployeeModel();
    empData = (EmployeeModel)ViewData.Model;
    EmployeeController controller = new EmployeeController();
    empDAL.CreateEmployee();
    return RedirectToAction("EmployeeList");
   }
   else
   {
   return View("AddEmployee");
 }
}
Go ahead and press F5 to display the home page, the new menu item – Employee that we created and on click of Employee it will take you to the new screen. We are going to add the code now to display the employee List Employees below (EmployeeList.aspx):

Now we have a view which read data from model using controller. We are going to add one link button on click of that it should display another view to accept user inputs to add new employee. So go ahead and repeat the same steps and call from a link button on down. Do not forget to add subsequent events in controller class.
And the Add Employee.aspx file look like this:
So how this sample application works?
1. When we are giving http://localhost:2500/Employee/EmployeeList in the address bar the routing engine will look it in global.asax file and for matching our request we have a default routing {controller}/{action}/{id}.So if we receive a URL request of /Employee/EmployeeList, the routing rule will treat " Employee" as the name of the action, and the EmployeeList () method will be invoked to process the request , which will finally load the EmployeeList UI.
2. Now when the user gives new Employee details and click on save. This will call /Employee/Create message or Cretate () method on EmployeeController which will pass view object to data model and redirect the view back to EmployeeList view. Simple right?
So we have some bullet points here:
1. Create Routing and route table to route to controller.
2. Controller does some logics and invokes the message or method where these messages call a view files.
3. Controller says get me a object / model example Employee here, I do whatever I can and pass this to view.
3. Do create your model, it should be an object or ORM model or SQL or whatever. We are not much interested on that.
4. View looks like aspx page but not exactly same. Some people put code behind in view but remember it will break single responsibility principle. Once we add code behind we can do all the non sense there to break the MVC basic rules. Separation of controls is most important concept of MVC.

5. In MVC views job is only to display the data what controller passed.It is not supposed to do any calculations.For example If you want to do tax calculation inside a view..STOP, that is not view job.Do that calculation in controler in pass it back to view.
6. Controller does not know who has called. So this is one of the fundamental for testing frame work. Call your controller from testing and test your controller, model, functionality.
So on successful creation of this sample application I am sure you will be getting ideas on URL Routing basics, creating view/Controller, how to capture a user interaction and how the control updates the model and updates the view back. So now time to look in to test project which is automatically created by MVC framework for you for unit testing. Recommend you to go through the link.

18 September 2010

Introduction to ASP.NET MVC 2

What is ASP.NET MVC Framework?
ASP.NET MVC is a framework, created by Microsoft, is a lightweight, highly testable presentation framework that (as with Web Forms-based applications) is integrated with existing ASP.NET features, such as master pages and membership-based authentication that implements the model-view-controller pattern. Based on ASP.NET, it allows software developers to build a Web application as a composition of three roles: Model, View and Controller.
I was working on some web application which is based on classic ASP.NET which is so called Forms-Based Web Application. I would like to explore more on ASP.NET MVC Framework here and share my experience with code samples. The best way to learn something is to teach it to someone else! Unfortunately I don’t have any one to teach other than me!
I am splitting my research in to three parts:
1. ASP.NET MVC 2 Introduction – Part 1
2. ASP.NET MVC 2 Code Sample – Part 2
3. ASP.NET MVC 2 Unit Testing – Part 3
4. ASP.NET MVC 2 Advanced URL Routing
This way I think it will not boring for me as well as the readers. Ok we will start with some theories.

What is Model–View–Controller (MVC)?
Model–View–Controller (MVC) is a software architecture, currently considered an architectural pattern used in software engineering. I saw many time usually people confuse this one with design patterns and listing with factory pattern, Singleton pattern etc. But this pattern is going to come under presentation patterns. The Model-View-Controller (MVC) architectural pattern separates an application into three main components: the model, the view, and the controller. One of the most popular diagram of ASP.Net MVC 3 circles are displaying on rigt side.But it might not be a best representation to understand the concept.lets take another one on left side is more impressive to me.
So In simple words:
• Model - Encapsulates core application data and functionality domain Logic.
• View - obtains data from the model and presents it to the user.
• Controller - receives and translates input to requests on the model or the view
Ok. We will search for more details:
Models- Model objects are the parts of the application that implement the logic for the application's data domain. Often, model objects retrieve and store model state in a database. For example, a Customer object might retrieve information from a database, operate on it, and then write updated information back to a Customer table in a SQL Server database.
Views-Views are the components that display the application's user interface (UI). Typically, this UI is created from the model data. A Simple example would be an edit view of a Customer table that displays text boxes, drop-down lists, and check boxes based on the current state of a Product object. View does not handle user inputs.
Controllers- Controllers are the components that handle user interaction, work with the model, and ultimately select a view to render that displays UI. Basically this to capture user inputs events like mouse move, button click etc.
In an MVC application, the view only displays information; the controller handles and responds to user input and interaction. For example, the controller handles query-string values, and passes these values to the model, which in turn might use these values to query the database.Please see the simple diagrams above.
Now, being a classic Asp.net web form developer my first question was:

Is MVC replacement for Web Forms?
Oppps..Why I took this diagram.Now I need t explain the REST concepts too which I dont know much.Ok, we will limit the scope to MVC and lets discuss REST on another post.MVC is part of the ASP.Net framework. The ASP.Net framework is Microsoft's framework for building web applications. Microsoft has 2 frameworks built on top of this framework, which is ASP.Net MVC and the one many are familiar with ASP.Net Web Forms. ASP.Net MVC is an alternate but not a replacement for Web Forms.MVC is not replacement for ASP.NET Web Forms. Both methods will exist together and you are not forced to switch to MVC if you like Web Forms. You can even use MVC and Web Forms on the same site and share data between them.

Advantages of an MVC-Based Web Application
• It makes it easier to manage complexity by dividing an application into the model, the view, and the controller.
• It does not use view state or server-based forms. This makes the MVC framework ideal for developers who want full control over the behavior of an application.
• It uses a Front Controller pattern that processes Web application requests through a single controller. This enables you to design an application that supports a rich routing infrastructure. For more information, see Front Controller.
• It provides better support for test-driven development (TDD).
• It works well for Web applications that are supported by large teams of developers and for Web designers who need a high degree of control over the application behavior.

Advantages of a Web Forms-Based Web Application
• It supports an event model that preserves state over HTTP, which benefits line-of-business Web application development. The Web Forms-based application provides dozens of events that are supported in hundreds of server controls.
• It uses a Page Controller pattern that adds functionality to individual pages.
• It uses view state on server-based forms, which can make managing state information easier.
• It works well for small teams of Web developers and designers who want to take advantage of the large number of components available for rapid application development.
• In general, it is less complex for application development, because the components (the Page class, controls, and so on) are tightly integrated and usually require less code than the MVC model.

What is URL Routing?
One of the significant changes with MVC is that it does not going to use the typical concept of file name has 1:1 matching with physical existence as in traditional approach.Ok we will try to understand in a simple way, what happens in Classic method if you request a page named SomePage.aspx from the server. If the SomePage.aspx file does not exist, you get an ugly 404 – Page Not Found error. That means you have a 1:1 correspondence between a URL and a resource. The browser requests are mapped to pages.
The MVC Framework doesn't support classic post backs and view state and doesn't consider any URL as the endpoint to a physical server file to parse and compile to a class. When building an ASP.NET MVC application, there is no correspondence between the URL that you type into your browser's address bar and the files that you find in your application.Instead of mapping URLs to template files on disk, they map URLs directly to classes.  These classes are called "Controllers".Then the Controller class will typically call a separate "View" component that owns generating the actual HTML output for the request.The ASP.NET MVC Framework includes a very powerful URL mapping engine that provides a lot of flexibility in how you map URLs to Controller classes.We will discuss it more detail with code sample.So An ASP.NET Web Forms application is content-centric. An ASP.NET MVC application, in contrast, is application logic centric. In the end, the MVC Framework employs a centralized HTTP handler that recognizes an application-specific syntax for links. In addition, each addressable resource exposes a well-known set of operations. This is somthing key to ASP.Net MVC and We will try to understand this concept in part 2 with the code sample.For now please see the below diagram.
How MVC Support for Test-Driven Development
This is one of the important features In addition to managing complexity. Simple example, in a Web Forms-based ASP.NET Web application, a single class is used both to display output and to respond to user input. Writing automated tests for Web Forms-based ASP.NET applications can be complex, because to test an individual page, you must instantiate the page class, all its child controls, and additional dependent classes in the application. Because so many classes are instantiated to run the page, it can be hard to write tests that focus exclusively on individual parts of the application.

Where to use MVC and where to use Web Forms?
Well, to answering this, some types of Web applications will benefit from the MVC framework. Others will continue to use the traditional ASP.NET application pattern. Other types of Web applications will combine the two approaches; neither approach excludes the other. So to it is very important to understand deeply both frame work in order to understand where to use. There was a simple comparison, I read somewhere - the MVC Framework and Web Forms have in common more or less what cars and motorcycles share it seems! Both can take you somewhere else, but with different speed, comfort, sense of freedom, size of the trunk. I think we are clear now. But I have few bullet points here as a developer’s view.
• Classical Asp.net use page controller pattern (Functionality in individual pages).
• Use web forms when you want built in state management and post back mechanism.
• There is a huge pool of server controls in asp.net. So use web forms for it.
• When you are in a rapid application development of small applications use web forms.
• Less coding is required in classic Asp.net.
• Use ASP.Net MVC when you need complete control over application. There will not be any default view state or post back.
• When you want to control the complexity of presentation engine use ASP.Net MVC.
• When you need a Test driven development (TDD) use ASP.NET MVC.

Can we mix ASP.Net and ASP.Net MVC in an application?
Yes. We already mentioned this point above. Want to emphasis the bullet points here.
• ASP.NET MVC sits on top of ASP.NET 3.5.
• It does not replace ASP.Net 3.5 libraries or functionalities.
• Migration from Classic asp.net to asp.net MVC is possible by adding MVC libraries and routing data.
• URL routing HTTP module in web.config decides who gets to process the request. If route found then ASP.Net MVC else web forms.

Ok sir. Tired of reading theories? Me too. Now time to look inside and make sure our understandings are correct. Once we started samples we will have more questions. And it is the best way to learn things. So how to start with? How do we create simple ASP.NET MVC applications? What are the installable required? Lot of questions already coming to mind. I would recommend you to come with me to read part Part 2 which contains code sample for working with simple ASP.NET MVC application. And as always, open for suggestions and inputs.