Jan 15, 2014

Cross Origin Resource Sharing

Cross-origin resource sharing (CORS) works by letting server indicate which origins are allowed to call them. When browser make a request to other domain it sends along an origin in the request header with the value of domain from where its coming from. If the server allows CORS, it will send response with header Access-Control-Allow-Origin which indicates if call is allowed. If this header is not present the the browser will not allow javascript to receive the response. In addition to the origin, CORS let server indicate which HTTP methods are allowed. CORS doesn’t prevent the call from being invoked on the server; rather, it prevents the calling JavaScript from receiving the results. 

Request Header
Origin:http://localhost:55724

Response Header
Access-Control-Allow-Origin: http://localhost:55724

Web API 2 supports CORS via NuGet package Microsoft.AspNet.WebApi.Cors. Here is how you can enable CORS for your api. This can done globally or at the controller level or at the action level.
 
 public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            //var cors = new EnableCorsAttribute("*", "*", "GET");
            config.EnableCors();
    
    
  [EnableCors("http://localhost:55725", "*", "GET")]
  public class ProductController : ApiController

Preflight Requests
For some CORS requests, the browser sends an additional request, called a “preflight request”, before it sends the actual request for the resource. The pre-flight request uses the HTTP OPTIONS method. If the preflight request succeeds, the browser sends the actual request.

Jan 10, 2014

IHttpActionResult

This is new feature to WebApi 2.0 In many ways this is similar to action result in asp.net mvc. There are some build in action result like mvc controller has view result, json result etc. Web api has OkResult, NotFoundResult, ExceptionResult,UnauthorizedResult,BadRequestResult, ConflictResult,RedirectResult,InvalidModelStateResult.
 
  public IHttpActionResult GetDetails(string name)
        {
            Product product = _productService.GetProduct(name);
            if (product == null)
                return NotFound();
            return Ok(product);
        }
This simplifies unit test, for example if you are using request object to create http response object then you need to do setup to unit test controller.

Routing With Attribute


This allows routing with Attribute on any action. This works for both Api as well as mvc controller. You can have multiple route to an action. This can also be applied at the controller level

[Route("Api/Product/{name:alpha}/Reviews")]
[Route("Api/Product/{id:int:min(1)}/Reviews")]
        public HttpResponseMessage GetReviews(int id)

[RoutePrefix("Api/Product")] : This will apply to all the routes in the controller

Following configuration change need to happen to make attribute route work
public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{name}", new {name = RouteParameter.Optional});

Notice MapHttpAttributeRoutes is before default route, this give opportunity for attribute route to be applied before default route.

Web Api Help Page

Install-Package Microsoft.AspNet.WebApi.HelpPage -Version 5.0.0

This will add following to the package config
<package id="Microsoft.AspNet.WebApi.HelpPage" version="5.0.0" targetFramework="net45" />

This install will not add any new assembly to the reference, but this will add Area HelpPage, with controller,model and view which will provide help page.

Documentation:
Update Project Property, build tab to check Xml Documentation file.
Open Areas->HelpPage->AppStart->HelpPageConfig file and uncomment
config.SetDocumentationProvider
Make sure it refers the same xml documentation file


Now open .../Help url

Nov 16, 2013

Update Mvc application from 4 to 5

Make sure you have back up of your project before you start updating your project.

Open Manage Nuget Package for the solution
Update Entity Framework
Update Asp.Net Mvc
Update Asp.Net Mvc web api2
Installed Microsoft.AspNet.WebHelpers

The idea is to update only top level package and it automatically updated other packages on which these packages were dependent on.

Update web.config
<add key="webpages:Version" value="3.0.0.0" />

And Update web.config in views folder for mvc version to 5

Compile your project and you should be ready to go at least I was able to update my project following these steps.

Nov 8, 2013

Deferred vs Eager loading in Entity Framework

In lazy loading related data isn't retrieved when entity is first read. These are automatically retrieved the first time when you attempt to access it.

 IEnumerable products = productContext.Products; 
 
 foreach (var p in products.ToList()) //Query tblProduct
 {
    var reviews = p.Reviews; //Query tblReview related to Product p, which will mean this query will be executed for each products
 }


Explicit loading is similar to Lazy loading except that related data retrieve doesn't happen automatically

 productContext.Configuration.LazyLoadingEnabled = false;
 IEnumerable products = productContext.Products;
 
 foreach (var product in products.ToList()) //Query tblProduct
 {
  productContext.Entry(product).Collection(x=>x.Reviews).Load(); //Query tblReview related to Product p
  productContainer.Entry(product).Collection(x=>x.Reviews).Query().Where(r=>r.Name.FirstName=="test").Load();
  var reviews = p.Reviews;  
 }

These are also known as deferred loading. Deferred loading can be used for cases where you have complex join or you are going to use related data only for subset of entity. Like you retrieve all product (may be 1000 in number) and display review only for the first product. For lazing loading you have to make sure that the ObjectContext instance has not been disposed, otherwise you will get exception, so the following will not work

 using (var productContainer = new ProductContainerCodeFirst())
 {
  products = productContainer.Products.ToList();
 }
 
//The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
 foreach (var review in product.Reviews)

In Eager loading related data is retrieved when entity is read. This result in single join query that retrieve all the related data. This can be achieved by setting LazyLoadingEnabled = false or by removing virtual keyword when you declare the property.

 productContext.Configuration.LazyLoadingEnabled = false;
 products = productContainer.Products.Include(a => a.Reviews.Select(b => b.Address)).Include(a => a.Reviews.Select(b => b.Name)).ToList();
 
 foreach (var p in products) //Query tblProduct and tblReview
 {
    var reviews = p.Reviews; 
 }

In general, if you know you need related data for every entity retrieved, eager loading offers the best performance, because a single query sent to the database is typically more efficient than separate queries for each entity retrieved. Also during serialization, you would want to turn lazy loading off as a serialize accesses all properties which will mean it will trigger a query for each navigation property that it accesses The DbContext class performs lazy loading by default. To disable remove virtual keyword when you declare the property or set LazyLoadingEnabled to false.

Referenced POCO

    [Table("tblProduct")]
    public class Product
    {
  public string Name { get; set; }
        public  virtual List Reviews { get; set; }
    }

    
    [Table("tblReview")]
    public class Review
    {
        public int Id { get; set; }
        public string ReviewerName { get; set; }
        public virtual Name Name { get; set; }
    }

   [Table("tblName")]
    public class Name
    {
        public int Id { get; set; }
        public string LastName { get; set; }
        public string FirstName { get; set; }
    }

Oct 26, 2012

RESTful Service

1. Uses HTTP as a communication protocol for remote interactions.

2. Rather than singular service endpoint, we have many individual resource/URIs. So its resource oriented architecture.

3. URIs (resources) supports multiple HTTP verbs (GET,PUT,POST,DELETE,HEAD,OPTION) and HTTP response codes.

GET, HEAD, and OPTIONS - Safe methods that aren't intended to have side effects
GET,PUT,DELETE,HEAD,OPTION - Idempotent,can be repeated multiple times without harm.
POST - Server define actual function, cannot be considered safe/idempotent by clients.

Refer to following specification for detail of HTTP Method RFC 2616 §9

HTTP defines a suite of standard response codes that specify the result of processing the request.
Successful 2xx
Redirection 3xx
Client Error 4xx
Server Error 5xx

The HTTP specification also defines a suite of headers that can be used to negotiate behavior between HTTP clients and servers. These headers provide built-in solutions for important communication concepts like redirection, content negotiation, security (authentication and authorization), caching, and compression.

Few Examples

GET http://<host>/ExploringMvc/api/Product?id=1 HTTP/1.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: gzip,deflate,sdch
Cache-Control: private, max-age=60, s-maxage=0
Content-Length: 3495
Content-Type: text/html; charset=utf-8
Content-Type: application/json; charset=utf-8
Date: Mon, 29 Oct 2012 00:42:54 GMT
Expires: Thu, 01 Dec 1994 16:00:00 GMT
ETag: 792373472
Last-Modified: Mon, 29 Oct 2012 00:55:44 GMT
If-Match: "xyzzy"
If-Modified-Since: Mon, 31 Oct 2012 00:42:54 GMT

Refer to following specification for detail of HTTP Header RFC 2616 §14

Resource can support multiple media type which can be negotiated between client/server.

4. Response contains number of hypermedia controls for different things to do next. This allows the server to change its URI scheme without breaking clients. The reason it’s called the “Web” is because resources can contain hyperlinks  to other resources, thereby creating a Web of resources.

From RPC-style to RESTful
Unlike RPC-style, you no longer focus on designing methods. Instead, you focus on the resources that make up your system, their URIs, and their representations and then you decide which of HTTP Verb you’ll support for each resource. So you short of move from Verbs to Nouns. If I am designing RPC-style service my focus will be on following operations
GetProductList()
GetProduct(int id)
AddProduct(Product product)
DeleteProduct(int id)
UpdateProduct(Product product)

If you notice that all above operations is for Product resource. So moving from RPC-style to RESTful, my focus will shift to Product resource. And then I will decide which of HTTP Verbs I need to support.

In RPC, Contract is service description document. All of service endpoint,operation, data type argument return, exception are defined in self contained application protocol defination

In REST,

  • contract is uniform interface.Action/Error semantics are specified by uniform interface.
  • Input and output are tied to media type specification.
  • State transitions are specified by hype mdeia
  • no service/operation, only resources and standard control data element such as http verb
  • no data type, no argument, no return value, they are simply media type, which are sequence of bytes from view point of uniform interface.
  • in rest hyper media driven workflow enable relationship between client/server to be much more dynamic in the sense that component can be moved around like resources can be added without breaking client.
  • generating proxy is not simple as in case of REST
  • in a truly RESTful architecture, the concept of statelessness implies that all relevant application states must be supplied with each and every request.By relevant, it is meant that whatever is required by the REST API to process the request and serve an appropriate response.


Reference:
http://martinfowler.com/articles/richardsonMaturityModel.html
http://www.w3.org/Protocols/rfc2616/rfc2616.html