Category Archives: ASP.NET MVC

WebApi – Asp.Net “ROUTE” to “REST”

WHAT: Webapi is a framework to build Http services that uses standard https verbs like GET, POST, PUT and DELETE to achieve data operations. WCF already had a way (i didn’t like it though ūüôā )¬†to achieve this but there were things that developers may find cumbersome. Few of them are as mentioned below

  1. Web browsers need to do a lot of XML parsing and DOM manipulation for SOAP based services.
  2. Only WebHttpBinding supports http services and those configuration settings were really painful (at least for me).

“WebApi framework pretty much¬†utilizes existing Asp.Net routing framework which comes with framework 4.0”

WHY: Suddenly there is a huge demand of making our web applications available on different platforms/devices like mobiles,smart phones,tablets etc. Http services help us to provide seemless integration to our data access methodologies across all the platforms. One service for all devices and platform.

WHERE: It comes in-built with Asp.Net MVC 4.0 framwork. you can download it from http://www.asp.net/mvc/mvc4¬†. Though WebApi implementation (which I am using)¬†is not limited to MVC. Webforms can also enjoy the “Route to REST” :).

You should have Fiddler tool to¬†see how it works. Download it from http://www.fiddler2.com/fiddler2/¬†it is a web debugger proxy tool. You can simulate http calls using this tool. It won’t be necessary in my example though.

HOW:¬† Once you install MVC 4.0, you will notice a new project template called WebApi. It will give you basic methods and a working sample created for you. Though i would prefer to use “Empty” project type because as a beginner i wanted to see how it works.

  • Install MVC4.0
  • Open new project in VS 2010.
  • select Asp.Net MVC 4 web application.
  • Choose “Empty” project.
  • goto project properties -> Web -> StartAction -> Specific Page -> give “employees/”
  • assign a port like 9090
  • Global.asax.cs : Add the new namespaces mentioned in code. Now we need to define a route format¬†which we would use to access the endpoints which in our case is an action method.
using System.Web.Http;
using System.Web.Routing;
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapHttpRoute(
"EmployeeRoute",
"{controller}/{id}",
new {id = RouteParameter.Optional  });
}
  • this route defines that you can access this service by browing either http://localhost:9090/employees or http://localhost:9090/employees/1 . what it means is that for Get requests Id is¬†optional. When we don’t pass id we will get all employees¬†and if Id is specified you get only Employee with the same ID.
  • If you want to allow method names in url just need to modify your Route in Global.asax with¬†“{controller}/{action}/id”. it will allow your web methods to be accessed as resources.
  • Add “Employee” class with public ID and Name properties.

Add a controller name it “EmployeesController”. and paste the below code.

</li>
</ul>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Http;
using System.Net.Http.Headers;
namespace WebApiDemo.Controllers
{
public class EmployeesController : ApiController
{
static List<Employee> _employees = InitEmployeeCollection();
private static List<Employee> InitEmployeeCollection()
{
var empList = new List<Employee>();
empList.Add(new Employee { ID = 0, Name = "Praveen" });
empList.Add(new Employee { ID = 1, Name = "Narsi" });
empList.Add(new Employee { ID = 2, Name = "Ganesh" });
empList.Add(new Employee { ID = 3, Name = "Venu" });
return empList;

}

public IEnumerable<Employee> Get()
{
return _employees;
}

public Employee Get(int id)
{
var emp = (from e in _employees where e.ID == id
select e).FirstOrDefault();

if (emp == null)
{
//HttpResponseMessage is part .net 4.5
//return type should be HttpResponseMessage<Employee>
//var foundEmp = new HttpResponseMessage<Employee>(HttpStatusCode.NotFound );
// return httpstatuscode.notfound =  404
}
return emp;
}

// insert
public  Employee Post(Employee newEmployee)
{
newEmployee.ID  = _employees.Count() + 1;
_employees.Add(newEmployee );
//if success
//var foundEmp = new HttpResponseMessage<Employee>(HttpStatusCode.Created );
//return httpstatuscode.created i.e.  201
return newEmployee;
}

//edit
public Employee Put(Employee emp)
{
var changedEmp = (from e in _employees
where e.ID == emp.ID
select e).FirstOrDefault();
changedEmp.Name = emp.Name;
return changedEmp;
}

//delete
public void Delete(Employee empToDelete)
{
_employees.Remove(empToDelete);

}
}
}

Please notice that name of controller methods are named as Get(),Post(),Put() and Delete(). These are pretty much like http verbs and your framwork is able to understand the kind of http action user is trying for just by these names itself . You can also name it like GetEmployee() etc. You can also keep other names but then we have to map it with URI (not covered in this post).Code is nothing new, plain CRUD operations.

  • Build the application and try to run. you would see it hits http://localhost:9090/employees/¬† as you have mentioned this starting point in project properties. It will not render anything but it will try to open a file (use notepad) which willl contain Json format output.
  • There is no Id specified in the url so it takes you to Get() method.
  • which returns the employee list but in Json format. to read about Json in this context refer to my post on Json¬†.
  • if you type http://localhost:9090/employees/1¬† it will return employee id and ¬†name with id equal to 1. It will hit overloaded Get method with Id as parameter which will return Employee object in json format.

Now , your service is in place and you have tested using urls of course only Get verbs. To test Post and other requests you can use fiddler or developer tools (press F12).

Step by step instructions to use developer tools and basic tutorial is also available on MVC official website .

Now to consume this webservice as it is. you can read my post on consuming REST services you just need to change URI where your service is hosted.

Otherwise you can use this class to consume the service.

<pre>using System.Web.Services;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Net;
using System.Runtime.Serialization.Json;
public class ConsumerClient
{
public static List<Employee> Get()
{
WebClient proxy = new WebClient();
//DownloadData sends data to server using the specific URI defined for your webmethod.
byte[] data = proxy.DownloadData("http://localhost:9090/Employees/");
Stream stream = new MemoryStream(data);
// serializing the returned type which is Employee[]
DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(List<Employee>));
var lstEmp = obj.ReadObject(stream) as List<Employee>;

return lstEmp;

}

public static Employee Post(Employee emp)
{
Employee newItem = new Employee() { ID = 0, Name = emp.Name };
WebClient proxy = new WebClient();
proxy.Headers["Content-type"] = "application/json";
MemoryStream ms = new MemoryStream();

//serialize the input parameter
DataContractJsonSerializer serializerToUpload = new DataContractJsonSerializer(typeof(Employee));
serializerToUpload.WriteObject(ms, newItem);

// upload the data to call AddEmployee web method which returns Employee object.
byte[] data = proxy.UploadData("http://localhost:9090/Employees", "POST", ms.ToArray());
Stream stream = new MemoryStream(data);
// serialize the returned type
DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(Employee));
// read the returned type as Employee
var newEmployee = obj.ReadObject(stream) as Employee;
return newEmployee;
}
}</pre>

Above deserialization method is inbuilt with Dot net framework 4.0 though there are few other libraries which helps you deserialize the
json objects in an easier way. one of the best one i found is JSON.Net which is really easy to understand.
To read more on this please refer to My post on Json.Net .

I hope it helps you to start.
All the best!!

Advertisements

Unit testing using Visual Studio 2010 — WHY and HOW

As a developer, we have been asked about Unit testing¬†during interviews. Typical answer is “yeah! i know how to write a unit test case but did not get a chance to implement it.” ¬†what cliche! ūüôā .

Why Unit testing is important :¬† Apart from SDLC and following the best practices (from my experience nobody cares for unit test cases unless it is a established product). I still found one of the reasons why we may HAVE to perform unit testing for every application in future. Cloud Hosting¬†is making news all around the world and looking at it’s cost benefits companies are trying their best to adopt it asap. With remote hosting comes lot of rules imposed by the vendor who is hosting your application and Unit testing is one of them. for example SFDC (sales force dot com) applications need at least 70% unit testing¬†coverage of before they agree to host it on cloud. ¬†So it’s about time we need to take unit testing seriously.

Good news for visual studio developers is that It’s really easy to implement unit testing in VS2010. ¬†No plugins required for a test project.

Class Library : to unit test. I have a C# class library project. which has only one class  ProductRepository.cs. I am using entity framework to access database (makes life easy. right? :)).

</pre>
public class ProductRepository
 {
 public ProductRepository()
 {
 }
 private readonly static NorthwindEntities _db = new NorthwindEntities();

public static List<Product> GetAll()
 {
 return _db.Products.ToList();
 }

public static Product GetById(int productId)
 {
 return _db.Products.Where(p => p.ProductID == productId).SingleOrDefault();
 }
 }
<pre>

it has only two methods GetAll() and GetById(). You can change the implementation the way you need.

HOW to create a Unit Test using VS 2010: 

  1. Go to any class in library project. say ProductRepository class here.
  2. Go to any method name and Right Click and Select Create Unit Tests.

3.  It opens a wizard. It shows library with all types and its methods listed.  You can select types and methods you want to write unit test cases for.

4. ¬†Select Output project. It can be an existing Test project or Select –> “Create a new C# Test project”

5.  It creates all the test methods for selected methods in library earlier in the wizard.

6. ¬†Check out the Test method created for TestGetAll(). it prefixes “Test” ¬†to all the method names.


[TestMethod()]
 public void GetAllTest()
 {
 List<Product> expected = null;

// change it here and make a db call to populate expected object with the same data source.

//something like below using entity framework.

// expected = _dbContext.Products.ToList();

 List<Product> actual;
 // call library method
 actual = ProductRepository.GetAll();
 Assert.AreEqual(expected, actual);
 Assert.Inconclusive("Verify the correctness of this test method.");
 }

7.  Note that Test project does not copy the .config  settings. Though it will reference the main project so database access layer classes are still available in test methods. Connection strings need to be added manually in test project .config.

8.   Look at a better implementation of TestGetAll () method below.


[TestMethod()]
 public void GetAllTest()
 {
 var _db = new NorthwindEntities(); // declared in class library
 List<Product> expected = null;
 expected = _db.Products.ToList();

 var actual = ProductRepository.GetAll();
 Assert.AreEqual(expected.Count , actual.Count );

// comparing each item in collection

IEnumerator<Product> p1 = expected.GetEnumerator();
 IEnumerator<Product> p2 = actual.GetEnumerator();

while (p1.MoveNext() && p2.MoveNext())
 {
 Assert.AreEqual(p1.Current.ProductID, p2.Current.ProductID);
 Assert.AreEqual(p1.Current.ProductName, p2.Current.ProductName);
 Assert.AreEqual(p1.Current.SupplierID, p2.Current.SupplierID);
 Assert.AreEqual(p1.Current.UnitPrice, p2.Current.UnitPrice);
 }
 }

Above code can be changed as per our needs. If you just want to validate the count of collection or each element.

How to Run Unit Test Cases: 

You will notice that under Solution Items¬†there is a new file created¬†YourClassLibraryProjectName.vsmdi¬†. It will list out all the test methods. you can select the ones you want to run or Run all. Every time you make any changes in Test methods don’t forget to Refresh the .vsmdi file in Test editor.

Just Hit Run Test in Current context and check the results (Passed or Failed) in Test Results window. you should see something like the below.

It may look like coding twice for every method ūüôā but you got to do what you got to do. right?

I will go deeper in my next article “Unit Testing beyond Assert statements”.¬†

I hope it is useful!

Asp.Net MVC 3.0 with dependency injection using Ninject container.

I did not use the famous jargon “Inversion Of Control IOC” intentionally here so that developers who are taking a shot at implementing(or understanding the existing application) dependency injection in their MVC application are not¬†puzzled by the debate over comparing/relating IOC ¬†with DI.

For now, let’s settle on that ¬† “IOC is an architecture principle and DI is configurable piece of code which follows IOC.”

I am going to cover the much needed  WHY,WHERE and HOW of DI

WHY to use DI: Even though MVC represents Separation of Concerns quite strongly, yet controllers are tightly coupled to Data access model/service.

// using Entity framework here.
private NorthwindEntities _Db = new NorthwindEntities();
public ActionResult CustomerList()
 {
 var model = _Db.Customers.ToList();
 return View(model);
 }

In the above code, we have¬†NorthwindEntities entity framework context used for Data access. let’s say we need to change the data access methodology for some reason (trust me it happens more often than you assume), then we need to change controller codes all across the application. ¬†So, why not creating a way where controller can become loosely coupled with data access methodology.

Hence here are few situations when to use IOC – DI

  1. When we need our components to be loosely coupled.
  2. When Unit testing is important and database may not be ready in the beginning. Test Driven Development TDD.
So, rather than instantiating the database context object we should pass an interface to the controller. This reduces extra work to create a test/mock data for testing. Even the database is not ready we can test our action methods easily as all  controller needs is an Interface.
WHERE to use DI:
  1. Initialization of controllers should be changed. controller’s constructor should accept interface to a repository (ICustomerRepository).
  2. In Global.asax and under Application_Start event setup the binding to interface.
 HOW to use:  piece of code to implement.
Interface and Repository classes
</pre>
</div>
<div>
public interface ICustomerRepository
 {
List<Customer> GetAll();
 }

// entity framework data access

public class CustomerEFRepository : ICustomerRepository
 {
 #region ICustomerRepository Members

public List<MVC_IOC_DI.EF.Customer> GetAll()
 {
 NorthwindEntities _db = new NorthwindEntities();
 return _db.Customers.ToList();
 }

#endregion
 }

// Sql to Linq data access

public class CustomerLinqRepository : ICustomerRepository
 {
 #region ICustomerRepository Members

public List<Customer> GetAll()
 {
 NorthwindLinqDataContext _db = new NorthwindLinqDataContext();
 return _db.Customers.ToList();
 }

#endregion
 }

// Home Controller

public class HomeController : Controller
 {
 private readonly ICustomerRepository irepository;

public HomeController(ICustomerRepository repository )
 {
 irepository = repository ;
 }

// right click on this method and Add View (as List template) strongly typed to Customer object.
public ActionResult CustomerList()
 {
 var model = irepository.GetAll() ;
 return View(model);
 }

}</div>
<div>
Ninject IOC container related code:  You can download Ninject libraries for MVC3.0 from http://nuget.org/packages/Ninject.MVC3 . If you are using VS2010 just go to NuGet Package manager and search for Ninject and install it (Nuget really rocks :))
</div></div>
<div>
<pre><div>
using Ninject;
using Ninject.Syntax;</div>
<div></div>
<div>//You would need a dependency resolver class to instruct MVC about the binding/mapping you need to specify in //global.asax.</div>
<div>

public class NinjectDependencyResolver : IDependencyResolver
 {
 private readonly IResolutionRoot _resolutionRoot;

public NinjectDependencyResolver(IResolutionRoot kernel)
 {
 _resolutionRoot = kernel;
 }

public object GetService(Type serviceType)
 {
 return _resolutionRoot.TryGet(serviceType );
 }

public IEnumerable<object> GetServices(Type serviceType)
 {
 return _resolutionRoot.GetAll(serviceType);
 }

}

</div>
<pre>// call this method ins Application_Start event</pre>
private void SetupDependencyInjection()
 {
 // create Ninject DI kernel
 IKernel kernel = new StandardKernel();

// register repository with specific data access repository DI container
 kernel.Bind<ICustomerRepository>().To<CustomerLinqRepository>();
// Later you may change it to EF data access easily.
//kernel.Bind<ICustomerRepository>().To<CustomerEFRepository>();
// Tell mvc to use our DI Ninject container
 DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
 }
<pre>

Here is the summary of the whole implementation.

  1. Include Ninject libraries in your application.
  2. Write Interface for each entity repository. — ICustomerRepository
  3. Write repository classes which implements the interface. —¬†CustomerEFRepository or¬†CustomerLinqRepository
  4. Controller should have interface as a class variable.
  5. Write a constructor for the controller which accepts this interface as parameter.
  6. Write a dependency resolver class for Ninject container. Which will change the dafualt way of how the MVC  resolves the dependency.
  7. Map the bindings in Application_Start event of Global.asax.cs.
These steps are for a very basic implementation of DI in MVC 3. 

For a beginner, it is a good start. Once the skeleton is ready, it’s easy to put on some fat :).

I hope it is useful.


Jquery to scroll down or up OnClick of an anchor tag

Recently i was working on an MVC master detail grid UI. There is a master grid which shows link to detail grid. When you click on the link of any row, a detail grid appears below the master grid. So the issue was detail grid did not have focus onclick of master link. which was very much desired by the user.

Here is a the small piece of jquery code which solved the problem. It not only scrolls down but also provides a decent animation effect while sliding down/up.


$(function () {
$(".productsLink").live('click', function () {
$('html,body').animate({scrollTop: $("#products").offset().top }, "slow");
});
});

Where products is the id of detail div.

Hope it helps!
Praveen