Building OData Services With ASP.NET Web API-Part1

Open Visual Studio 2012 >> File >> New >> Project >> Select ASP.NET MVC4 Web Application Template >> Select Web API Template
1
2
It will add automatically OData dependencies for us.Also you can install OData dependencies by using Nuget as well.
3

Create a new controller named CustomersController by rightclicking the Controller folder.
9

 

 

 

 

Then add new class named Customer in the Model folder and add some properties like below
4
Also add one more folder named Domain and add a class named CustomerDataContext, It contains a method Customers which return some customers informations.
5

For setting the OData first i need to do is set up my routing that can be get in to the Customers controller based on OData routing scheme not traditional web api routing schemes.Go to the WebApiConfig class in the App_Start folder and add a helper method GetImplicitEdm for defining entity data model.
6
This method will return IEdmModel which is a interface abstraction on the top of entity data models.ODataModelBuilder class will create set most of the entity data models automatically for you.The main thing you tell to the builder is entity sets are involved and then call the GetEdmModel method associated with the builder class,this will find all the properties on the object,find the types of those properties,look for navigation properties relates other objects in the model. Also add one more route (marked as yellow above) other than the web api route by calling the extension method MapODataRoute which accepts the parameters such as name of the route,a route prefix similar to the api route prefix in the default web api route and then call our helper method GetImplicitEdm.
Then the next step is go to the customers controller and change our base class ApiController to EntitySetController which is generic type takes two arguments,first one is the type of the entity controller represents and second one is the type of key property in that customer object and override Get method of type IQueryble and return our Customers.
8

Run the application and browse the url like below.It will return all the customers.

10

Then i am going to take individual customers. To do that there is a separate override base class called GetEntityByKey and querying by using linq.Note that this is a protected method it expose the service operation is actually a different public method on our base class and the public method will call this one.
11

Go and run the application and browse the url like below.It will return the customer with name “Jameel”

12

Enjoy reading…

Difference between WCF Data Services & ASP.NET WebApi OData

WCF Data Services

  • For this you don’t actually need WCF Knowledge.Coding WCF data services looks like coding normal WCF services. You no need to create service contract and implement those service contracts and configuration also.You just derive from a dataservice class in often running very quickly.
  • WCF Data Services is the most complete implementation of the latest OData specification  from Microsoft.
  • Great for exposing whole data stores with little intervening logic.So you really want to expose a pipeline to the web or to a network for people to come in and query your data store and possibly perform update against it.
  • Complicated to use with non-LINQ provider data
  • Not very extensible

ASP.NET Web API OData

  • New Addition to Web API stack
  • Gives you more control over underlying data sources,model definition and routing conventions.
  • Easier programming model for intervening business logic
  • Can support multiple models per site,mix non-OData with OData services
  • Very extensible

Enjoy reading..

Introduction to ODATA

ODATA is a open standard protocol initiated and led by Microsoft but it is supported by different platforms vendors. You can find more about this protocol from http://www.odata.org/.General idea of ODATA is expose data over HTTP services for query or update.ODATA embraces REST architectural style.One thing we give up with REST in general is that if you have ever been expose to WCF, WCF includes metadata with the services and that means you could generate client proxies to call those services very easily.When you go to REST based services you could lose that.REST in general has no protocol for metadata but the ODATA includes metadata specification for services, that means for ODATA endpoint you can expose that metadata and has some client side code generation for consuming the endpoint.ODATA is broken down in to two parts
1.ODATA Query Syntax : URL syntax for expressing queries

  • Data Service URI
  • Entity set name
  • Navigation Property
  • Operators and functions

2.ODATA Formatting: ATOM publising Protocol or JSON formatting

  • application/atom+xml or application/json
  • JSON Verbose vs JSON Light

     ODATA also leverages HTTP verbs such as GET,POST,PUT,DELETE,PATCH,MERGE

ODATA Supported Platforms

  • WCF Data Services(Initial OData Microsoft platform)
  • Node.js,PHP,Java
  • SSRS(SQL Server Reporting Services)
  • Sharepoint
  • Windows Azure Table Storage
  • Windows Azure Data Marketplace
  • IBM WebSphere/DB2/Informix
  • ASP.NET WebApi

Enjoy..Reading

REST Architectural Style

Introduction

REST stands for Representational State Transfer It is truly a different way of thinking about service design than traditional service oriented approaches.Instead of focusing on exposing operation or method for remote invocation you focus on exposing resources.Resources are something like a data collection.it is the easiest way  for think about it.You can certainly use rest services for command and control type scenarios.for example you might have  some remote piece of equipment you trying to control , it could be a scientific device you trying to come across with or any number of scenarios like that. You need to send a service call for make it happen. If you can think as a resource you are manipulating it comes in the REST architecture style.So that the resources are things you need to communicate with and way you communicate with representations of those resources that’s why the representation parts of the names come in.
Comparing REST and SOAP
REST is a architectural style and SOAP is nothing more than a message format and is protocol for how you structure a message doesn’t say anything about how you get the message from POINT A to POINT B.REST is fully embraces on HTTP protocol which is capable of expressing more than just how to structure a message.It also has headers,status code,verbs and other  things that allow you to express semantics about the communication itself.Now basically you can write number of elements to do with HTTP protocol that we can leverage fully embrace rest.
1
URI
In service oriented systems the URI only used to represents the service address,how you get the service location.and the soap message takes over from there to express all other aspects, what is that message represents,what action should be invoked and so on.In REST based system URI also express what resource you are trying to manipulate or communicate with.Additionally you can add parameters in to the URI you seen either URI parameters or querystring parameters and those can be passed in to the target service method that you are invoke on
the service itself.
HTTP verb
HTTP also has verbs associated with it. Doing soap based services only verb used is POST verb.In Rest you can leverage the full range of verbs such as GET,POST,PUT,DELETE.
HTTP Headers
HTTP also has headers associated with it . We can also include content negotiation saying that what the media types that client request and what the content type is. Additionally you can leverage HTTP messages have status code , the status code indicate the service status whether the call is success or not and also there are some other things can express in the headers such as security,ETags allow you to do caching in the client and also you can put custom headers in the HTTP messages also.
HTTP Body
Anything you want to serialize in the body there is a parameters in to the method or response or return type from that method but you can also encode in a particular way by using media types. Media types could be standardize once like application/json or application/xml and you can  put custom media types also.And there is Hyper media for example a customer has a collection of orders instead of embedding the order objects in the response you can embed links to related order objects you can also further actions you can take against that service such as URL to update that object or do you have read only access then you wouldn’t have to update link in the representations.So all of  these things comes together to form whole REST about.

Introduction to ASP.NET Web Api

Introduction

ASP.NET Web API is a new framework for building and consuming web API’s. It’s a simple http service generally not soap, it uses simple http protocol. ASP.NET Web API is created on the top of .NET Framework that reaches a broad range of clients, including browsers and mobile devices. The WCF and the ASP.NET MVC development team together works and bring the brand new ASP.NET Web API.

intro

When we use ASP.NET web Api?

  • Choose Web API when you want to create a resource-oriented services over HTTP that can use the full features of HTTP (like URIs, request/response headers, caching, versioning, various content formats).
  •  It also supports MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection.
  • Choose Web API when you want to expose your service to a broad range of clients including browsers, mobiles, iphone and tablets.

When I can Use WCF?

  •          Choose WCF when your framework are limited to .Net Framwork 3.5
  •          Choose WCF when you are working on SOAP based services

How to create a new Web Api project using Visual Studio 2010?

Here I am explaining you to step by step procedure for creating a simple ASP.NET Web API project.

Start Visual Studio and select New Project from the Start page. Or, from the File menu, select New and then Project. From the Templates pane select ASP.NET MVC4 Web Application.

2

In the New ASP.NET MVC 4 Project dialog, select Web API and click OK.

3

Next i am going to create a sample application which loads a list of employees using ASP.NET Web Api and jQuery

First Add a new controller by right clicking the controller folder in your application like below.

4

Select template as Empty API Controller like below and click Add.

6

Add a new class library project by right clicking the solution and named it an Employee.Domain and create three folder named

Abstract, Repositories and Entities like below.

8

 

 

 

 

This project is responsible for storing all the business functionalities by using Repository Pattern.

Add new entity model class by right clicking Entities class named it as Employee.cs and the following properties.

namespace Employee.Domain.Entities

{
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
}

Add a new interface in this project by right clicking the Abstract folder and named it as IEmployeeRepository.cs and add a property like below.

using System.Collections.Generic;
namespace Employee.Domain.Abstract
{
public interface IEmployeeRepository
{
List<Entities.Employee> GetEmployees();
}
}

Add a concrete implementation class by right clicking the Repositories folder and named it as EmployeeRespository.cs and implement the above interface (IEmployeeRepository)

using System.Collections.Generic;
using System.Linq;
using Employee.Domain.Abstract;
namespace Employee.Domain.Repositories
{
public class EmployeeRepository:IEmployeeRepository
{
private readonly EmployeeDataContext _employeeDataContext;
public EmployeeRepository()
{
_employeeDataContext=new EmployeeDataContext();
}

//method for loading all the employees

public List<Entities.Employee> GetEmployees()
{
return _employeeDataContext.Employees.ToList();
}
}
}

Configuring EntityFramework 5.0.0

     To install EntityFramework, run the following command in the Package Manager Console

You can get the Package Manager Console from

9

Select the default project as Employee.Domain and Run the following command in this console.

Add new EmployeeDataContext class in Employee.Domain project and the following property

using System.Data.Entity;
namespace Employee.Domain
{
public class EmployeeDataContext:DbContext
{
public EmployeeDataContext(): base("name=EmployeeDataContext")
{
}
public DbSet<Entities.Employee> Employee { get; set; }
}
}

Create db ,named it as Company and create a new table

11

 

 

 

 

 

Setting connection string in web.config of web project and set the datasource of Company database like below.

<connectionStrings>

<add name=”EmployeeDataContext” connectionString=”Data Source=JAMEEL\SQLR2EXPRESS; Initial Catalog=Company; Integrated Security=True; MultipleActiveResultSets=True;Pooling=False;”

providerName=”System.Data.SqlClient” />

</connectionStrings>

Modify the Web Api configuration which is in the App_Start folder of the web project. In this I have add two custom routing for accessing the web api url by using and controller/action.

public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "ApiByAction",
routeTemplate: "api/{controller}/{action}",
defaults: new { action = "Get" }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}

Next iam adding our web API method for loading all the employees in to the view. Add new action named GetEmployees in EmployeeController which is responsible for return Employees as Json.

public class EmployeeController : ApiController
{
private readonly IEmployeeRepository _employeeRepository;
public EmployeeController()
{
_employeeRepository=new EmployeeRepository();
}
public List<Employee.Domain.Entities.Employee>  GetEmployees()
{
return _employeeRepository.GetEmployees();
}
}

Next add new plain html page and load the Employee results as table structure by using jQuery.

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<html xmlns=”http://www.w3.org/1999/xhtml”&gt;

<head>

<title></title>

<script src=”Scripts/jquery-1.7.1.min.js” type=”text/javascript”></script>

<style type=”text/css”>

table, td, th
{
border: 1px solid green;
}
th
{
background-color: green;color: white;
}
</style>
</head>
<body>
<div id=”Employees”>
</div>
<script type=”text/javascript”>
$.getJSON(“/api/Employee/GetEmployees”, function (data) {
var table = “<table><tr><th>Name</th><th>Age</th><th>Address</th></tr>”;
var finalHtml = “”;
$.each(data, function (i, item) {
finalHtml = finalHtml + ‘<tr><td>’ + item.Name + ‘</td><td>’ + item.Age + ‘</td><td>’ + item.Address + ‘</td></tr>’;
});
table = table + finalHtml + ” </table>”;
$(‘#Employees’).html(table);
});
</script>
</body>
</html>

Hope you got a basic overview of WebApi and how to create a sample Web API and consuming by the client.