[Dev Tip] CORS on REST WCF

Yesterday I encountered the following question in the MSDN forums about calling a cross-domain WCF RESTful service from Chrome.

The problem with doing the above is because there is a cross-domain call to a WCF service. When you are using Chrome, the browser tries to find out if it can do the call by sending a cross-origin resource sharing (CORS) request, as explained in this article. In IE, you will most likely get a cross-domain exception.

After searching the web a bit, I found that the immediate solution is to change the supported HTTP method of the operation to “*”, and to add the special cross-origin headers to the outputted response, like so:

WebOperationContext.Current.OutgoingResponse.Headers.Add(
  “Access-Control-Allow-Origin”, “*”); WebOperationContext.Current.OutgoingResponse.Headers.Add(
  “Access-Control-Allow-Methods”, “POST”); WebOperationContext.Current.OutgoingResponse.Headers.Add(
  “Access-Control-Allow-Headers”, “Content-Type, Accept”);

There are two problems with this solution:

  1. You need to repeat these lines in each of your service methods.
  2. The service method is called twice, once for the “preflight” request (the request with the OPTIONS HTTP verb), and a second time for the invocation itself.

So I took the time and written a special endpoint behavior that can be attached to any webHttpBinding based endpoint.

The code does the following:

1. Every response message gets the “Access-Control-Allow-Origin” header with the value of “*”, to tell the client that the service allowed the request from the client.

2. If the client sends a request to the service with the verb OPTIONS (this is referred to as a “preflight” request), the service will automatically return a 200 (ok) response with the required headers: “Access-Control-Allow-Headers” and “Access-Control-Allow-Methods” (in addition to the allow-origin header). Clients that look for the “allow” headers in the response will then send the original required request to the service.

The benefits of using this behavior is:

  1. The code that returns the message with the headers is located in the behavior itself – no need to place it in each service method.
  2. The behavior catches the OPTIONS request, and does not require running the service method twice.
  3. You do not need to change any part of your service contract or service implementation. The behavior is only needed to be applied using configuration.

To implement this behavior I used a message inspector that checks the request and changes the response, and an operation invoker that wraps the unhandled operation invoker. The custom operation invoker handles the OPTIONS message requests, which otherwise would have caused the service to return an error message (because no method is set to handle “Options” requests).

The endpoint behavior can be attached to the endpoint through configuration, like so:

<behaviors>

<endpointBehaviors>

<behavior name=”webSupport”>

<webHttp />

<CorsSupport />

</behavior>

</endpointBehaviors>

</behaviors>

<extensions>

<behaviorExtensions>

<add name=”CorsSupport” type=”WebHttpCors.CorsSupportBehaviorElement, WebHttpCors, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null” />

</behaviorExtensions>

</extensions>

<services>

<service name=”Service.JSonService”>

<endpoint address=”http://localhost:8080″ behaviorConfiguration=”webSupport” binding=”webHttpBinding” contract=”Service.IJSonService” />

</service>

</services>

Or, if you are using IIS to host your services, I also created a service host factory that creates a WebServiceHost and adds the behavior to every webHttpBinding based endpoint created by the host. To use it in your .svc file, just write something like this:

<%@ ServiceHost Language=”C#” Debug=”true” Service=”Service.JSonService, Service”Factory=”WebHttpCors.CorsWebServiceHostFactory, WebHttpCors” %>

You can download the behavior code + two sample hosts (IIS and self-hosted) that shows how to use the behavior from my skydrive.

To test the two hosts, open the webform1.aspx and change the target URL to access the IIS/self-hosted service.

Enjoy.

REF: http://blogs.microsoft.co.il/idof/2011/07/02/cross-origin-resource-sharing-cors-and-wcf/

With js:

IE was ok with it. Firefox was not ok with it.

Then you gotta remember that handle their .Send() requests differently (inside JQUERY).

It all makes sense now.

//JavaScript snipplet

if (window.XMLHttpRequest) {

    returnObject = new XMLHttpRequest();

} else if (window.ActiveXObject) {

    returnObject = new ActiveXObject("Microsoft.XMLHTTP");

} else {

msg = "Your browser doesn't support AJAX!";

}

Here are some key words, phrases that I’ve been googling/binging that finally led me somewhere.

    Result: [Exception... "Component returned failure code: 0x80040111 (NS_ERROR_NOT_AVAILABLE) [nsIXMLHttpRequest.statusText]" nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)" location: "JS frame :: http://localhost:53692/test/WCFCallTestViaJQ14.htm :: HandleJQueryError :: line 326" data: no]


XMLHttpRequest Send "NS_ERROR_FAILURE"

JQuery Ajax WCF Self Hosted CORS JSON

Ref: http://stackoverflow.com/questions/7234599/cors-support-within-wcf-rest-services

Source Code: https://mega.co.nz/#!NppCwJ4D!S6sUVFYU-_qpK7Flml-i0QMod8V9Qq7vyWbkek8KVp4

[Dev Tip] REFACTORING THE ASP.NET MVC APPLICATION TO THE ONION ARCHITECTURE

Source Code on GitHub

Background

Any application should be fairly tested before it shipped to the customer. Biggest challenge in the testing is tightly coupled behavior of the UI with the Application Logic and further to the Database logic .Good testable systems are the one in which presentation layer does not directly depends on the application logic and the database logic. Application logic should be independent of UI such that both can be tested independent of each other. For example you should not call DBContext methods on click event of a button from the UI. If you do so, then the UI is tightly coupled with the database layer and any change in the database logic will impact the UI. Other disadvantage is that to unit test the database logic you need the UI. Testing of various components of the application is as important as building the components of the application. You should able to do the Unit Testing without the need of the database. Now let us assume, you are creating an ASP.NET MVC application and you have written all the database codes (fetching records or inserting etc.) in the controller itself. Your application may be up and running but in this pattern, you cannot unit test the controller without database. Other problem could be, you may have duplicate the database codes in different controllers and certainly you would not like that. There are challenges with duplicate codes. One change in database logic may require you to do multiple changes in the code. Other problem is your controller is aware of the underlying database source and if in future you change the data source, the controller will be affected and again this is not the best practice to create an ASP.NET MVC application. These problems are not only restricted to MVC but can exist in any kind of applications which is having database logic tightly coupled with the application itself.

Let us summarize problems we discussed above:

  • Duplicate database access codes
  • Hard to maintain the codes
  • Difficulties in Unit Testing
  • Hard to replace type of data sources
  • Tough to put centralized database access related policy

Usual approach we follow is the Layered Architecture. In layered architecture the presentation layer is transitively depends on the database layer and that does not solve the problem we discussed earlier in an absolute way.

Onion Architecture is the preferred way of architecting application for better testability, maintainability and dependability on the infrastructures like databases and services. This term was first coined by Jeffery Palermo in his blog back in 2008.

Learn more about the Onion Architecture in the series of blog posts by Jeffery Palermo

  • In the Onion Architecture layers talk to each other using the Interfaces. Any concrete implantation would be provided to application at the run time.
  • Any external dependency like database access and the web service call are part of the external layers
  • UI is part of the external layers
  • Objects representing domain are part of the internal layers or they are the centers
  • External layers can depend on the layers internal to it or central to it
  • Internal layer should not depend on the external layers.
  • Domain object which is at the core or center can have access to the both the UI and the database layers.
  • All the coupling are towards the center
  • Codes which may change often should be part of the external layers

I would recommend you to watch Steve Smith course on same topic at Pluralsight for better understanding on the concepts of the Onion Architecture. I will not go much into discussion of Onion architecture and jump into showing you refactoring ASP.NET MVC application to use the Onion Architecture.

Create N-Tier application using C# by Steve Smith

Setup

Let us implement Repository Pattern in MvcMovieRTM ASP.NET MVC Application. You can download this app from official Microsoft site here . After downloading, open the app in Visual Studio and in Package Manager Console run the command update-database. Go ahead and press F5 to run the application. Navigate to Movie Controller and you should able to see list of movies, can edit, delete and create new movie. We are going to refactor this application to adhere the Repository Pattern. Before we move ahead, let us examine the code in MoviesController.

image

As you see in the above code snippet that inside the controller we are directly accessing the database. All logics to fetch data from database is written right inside the controller and that makes the controller and the database access tightly coupled to each other. You cannot unit test Index action in isolation of database.

Refactoring to Repository Pattern

Follow the following steps to refactor the existing application:

Create two class library projects and give them name as MvcMovie.Infrastructure andMvcMovie.Core. In the project MvcMovie.Infrastructure all database related operation will be placed. In this example Entity Framework is used. So all Entity Framework dependency will be part of MvcMovie.Infrastructure project.

Setting up Infrastructure Project

Let’s start with moving the MovieDBContext class to the MvcMovie.Infrastructure project. Infrastructure project will contain all the database related classes and the operations. Since application is using Entity framework, we need to add the Entity framework reference in Infrastructure project. From Nuget manager add Entity framework package in the project. MovieDBContext class will look like as follows:

MovieDBContext.cs

1
2
3
4
5
6
7
8
9
10
11
using System.Data.Entity;
namespace MvcMovie.Infrastructure
{
    public class MovieDBContext : DbContext
    {
        public DbSet<Movie> Movies { get; set; }
    }
}

Next create MovieRepository class in the Infrastructure project. This class will contain all the database operations. Essentially we will move operations which are directly working with MovieDbContext class from the MoviesController to MovieRepository class. After moving the Entity framework codes the MovieRepository class will look like follows:

MovieRepository.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using MvcMovie.Core;
using System;
using System.Collections.Generic;
using System.Data.Entity;
namespace MvcMovie.Infrastructure
{
    public class MovieRepository : IMovieRepository, IDisposable
    {
        MovieDBContext db = new MovieDBContext();
        public IEnumerable<Movie> GetMovies()
        {
            
                return db.Movies;
            
        }
        public void Add(Movie m)
        {
          
                db.Movies.Add(m);
                db.SaveChanges();
           
        }
        public void Edit(Movie m)
        {
            
                db.Entry(m).State = EntityState.Modified;
                db.SaveChanges();
            
        }
        public void Remove(int id)
        {
                Movie movie = db.Movies.Find(id);
                db.Movies.Remove(movie);
                db.SaveChanges();
            
        }
        public void Dispose()
        {
            db.Dispose();
        }
    }
}

Once MovieRepository class is created refactor it to extract Interface from this class. You need to move extracted interface to the MvcMovie.Infrastructure project.

clip_image002

Visual Studio will extract the IMovieRepository interface and put it inside the MvcMovie.Infrastructure project. Move the IMovieRepository interface to the MvcMovie.Core project. IMovieRepository will look like follows in MvcMovie.Core project:

IMovieRepository.cs

1
2
3
4
5
6
7
8
9
10
11
12
using System;
using System.Collections.Generic;
namespace MvcMovie.Core
{
   public interface IMovieRepository
    {
        void Add(Movie m);
        void Edit(Movie m);
        IEnumerable<Movie> GetMovies();
        void Remove(int id);
    }
}

Do not forget to implement the IMovieRepository interface in the MovieRepository class. At this point of time if you go ahead and build the MvcMovie.Infrastructure project, you will get compile time errors. In solution explorer MvcMovie.Infrastructure project should look like follows:

clip_image002[6]

Setting up Core Project

Move Movie class from the MvcMovie project to the MvcMovie.Core project. To work with data annotations add reference of System.ComponentModel.DataAnnotaions in the MvcMovie.Core project. Movie class should look like follows in core project:

Movie.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
using System;
using System.ComponentModel.DataAnnotations;
namespace MvcMovie.Core
{
  public class Movie
    {
        public int ID { get; set; }
        [StringLength(60, MinimumLength = 3)]
        public string Title { get; set; }
        [Display(Name = "Release Date")]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        public DateTime ReleaseDate { get; set; }
        [RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
        [Required]
        [StringLength(30)]
        public string Genre { get; set; }
        [Range(1, 100)]
        [DataType(DataType.Currency)]
        public decimal Price { get; set; }
        [RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
        [StringLength(5)]
        public string Rating { get; set; }
    }
}

You should have the IMovieRepository interface and the Movie class inside the MvcMovie.core project. In solution explorer the MvcMovie.Core project will look as follows:

clip_image002[8]

Compile MvcMovie.Core project and add its reference to the MvcMovie and the MvcMovie.Infrastruture project. After adding reference of the MvcMovie.Core in the MvcMovie.Infrastructure project, you should able to successfully compile the MvcMovie.Infrastructure project.

Refactor MoviesController

Previously in the MoviesController class we were directly creating instance of the MovieDBContext and performing database operations. To follow Onion Architecture, controller will only know about the IMovieRepository and perform database operations using the IMovieRepository. Very first let’s create instance of the IMovieRepository

1
private IMovieRepository db = new MovieRepository() ;

Next any database operation will be performed on instance of MovieRepository. Some of the operations are as follows:

Fetch Genre

1
2
3
var GenreQry = from d in db.GetMovies()
               orderby d.Genre
               select d.Genre;

Fetch All Movies

1
2
var movies = from m in db.GetMovies()
                         select m;

Add Movie

1
db.Add(movie);

Edit Movie

1
db.Edit(movie);

Remove Movie

1
db.Remove(movie.ID);

Replace various database operations in MoviesController with the code as shown above. As of now you should successfully able to run the application.

Inverting the Dependency

We are directly creating instance of the MovieRepository in the MoviesController which makes Controller tough for Unit Test. In this scenario to test the Controller, you need the database. We can solve this problem by inverting the control using any DI Container. You are free to use any DI container of your choice, however I am using Microsoft provided Unity Container. To use it add the Unity reference using Nuget Package Manger. In Unity.Config (located in the App_Start) folder register the type as given below:

1
container.RegisterType<IMovieRepository, MovieRepository>();

Once type is registered you need to call the RegisterComponents() method of UnityConfig in the Application_Start() method of the Global.asax.cs as shown below:

1
UnityConfig.RegisterComponents();

As the last step refactor Controller as shown below:

clip_image002[10]

If you remember in beginning we were directly creating the instance of the MovieDBcontext inside controller hence the controller was fully dependent on database and was making it tough to test it in isolation.

MvcMovie application has been refactored to Onion Architecture. Next task you may want to do, is to download the code discussed in this post from GitHub and start writing test.

Source Code on GitHub

Summary

We have refactored the application adhering to the onion architecture. Domain objects like Movie is at the center of the architecture and are the part of internal layers. The Infrastructure project in which we are working with database and database logics are part of the external layers. They depend on the centeral layers like core. UI or in this case the MVC application is also an external layer and depndes on the Core project. All layers are interacting to each other using the interfaces rather than the concrete definitions. You can very easily write Unit Test against the controllers using Fake or Mock without hitting the datbase. In future you can easily change data access technology from Enity Framework to something else without affecting the UI and the Core.

Resources

Source Code on GitHub

Learn more about the Onion Architecture in the series of blog posts by Jeffery Palermo

REF: http://debugmode.net/2014/09/12/refactoring-the-asp-net-mvc-application-to-the-onion-architecture/

[Dev Tip] Decouple OWIN Authorization Server from Resource Server

Recently I’ve received lot of comments and emails asking how we can decouple the OWIN Authorization Server we’ve built in the previous posts from the resources we are protecting. If you are following the posts mentioned below you will notice that we’ve only one software component (API) which plays both roles: Authorization Server and Resource Server.

There is nothing wrong with the the current implementation because OAuth 2.0 specifications never forces the separation between the Authorization Server and the Resource Server, but in many cases and especially if you have huge resources and huge number of endpoints you want to secure; then it is better from architecture stand point to decouple the servers. So you will end up having a stand alone Authorization Server, and another stand alone Resource Server which contains all protected resources, as well this Resource Server will understand only the access tokens issued from the Authorization Server.

You can check the source code on Github.

OAuth 2.0 Roles: Authorization Server, Resource Server, Client, and Resource Owner

Before we jump into implementation and how we can decouple the servers I would like to emphasis onOAuth 2.0 roles defined in the specifications; so we’ll have better understanding of the responsibility of each role, by looking at the image below you will notice that there are 4 roles involved:

OAuth 2.0 Roles

Resource Owner:

The entity or person (user) that owns the protected Resource.

Resource Server:

The server which hosts the protected resources, this server should be able to accept the access tokens issued by the Authorization Server and respond with the protected resource if the the access token is valid.

Client Applications:

The application or the (software) requesting access to the protected resources on the Resource Server, this client (on some OAuth flows) can request access token on behalf of the Resource Owner.

Authorization Server:

The server which is responsible for managing authorizations and issuing access tokens to the clients after validating the Resource Owner identity.

Note: In our architecture we can have single Authorization Server which is responsible to issue access token which can be consumed by multiple Resource Servers.

Decoupling OAuth 2.0 OWIN Authorization Server from Resource Server

In the previous posts we’ve built the Authorization Server and the Resource Server using a single software component (API), this API can be accessed on (http://ngauthenticationAPI.azurewebsites.net), in this demo I will guide you on how to create new standalone Resource API and host it on different machine other than the Authorization Server machine, then configure the Resource API to accept only access tokens issued from our Authorization Server. This new Resource Server is hosted on Azure can be accessed on (http://ngauthenticationResourcesAPI.azurewebsites.net).

Note: As you noticed from the previous posts we’ve built a protected resource (OrdersController) which can be accessed by issuing HTTP GET to the end point(http://ngauthenticationAPI.azurewebsites.net/api/orders), this end point is considered as a resource and should be moved to the Resource Server we’ll build now, but for the sake of keeping all the posts on this series functioning correctly; I’ll keep this end point in our Authorization Server, so please consider the API we’ve built previously as our standalone Authorization Server even it has a protected resource in it.

Steps to build the Resource Server

In the steps below, we’ll build another Web API which will contain our protected resources, for the sake of keeping it simple, I’ll add only one secured end point named “ProtectedController”, any authorized request to this end point should contain valid bearer token issued from our Authorization Server, so let’s start implementing this:

Step 1: Creating the Resource Web API Project

We need to add new ASP.NET Web application named “AngularJSAuthentication.ResourceServer” to our existing solution named “AngularJSAuthentication”, the selected template for the new project will be “Empty” template with no core dependencies, check the image below:

Resourse Server New Project

Step 2: Install the needed NuGet Packages

This project is empty so we need to install the NuGet packages needed to setup our OWIN Resource Server, configure ASP.NET Web API to be hosted within an OWIN server, and configure it to only uses OAuth 2.0 bearer tokens as authorization middle ware; so open NuGet Package Manager Console and install the below packages:

The usage for each package has been covered on the previews posts, feel free to check this post to know the rational of using each package is used for.

Step 3: Add OWIN “Startup” Class

Now we want to add new class named “Startup”. It will contain the code below:

As we’ve covered in previous posts, this class will be fired once our Resource Server starts, as you noticed I’ve enabled CORS so this resource server can accept XHR requests coming from any origin.

What worth noting here is the implementation for method “ConfigureOAuth”, inside this method we are configuring the Resource Server to accept (consume only) tokens with bearer scheme, if you forget this one; then your Resource Server won’t understand the bearer tokens sent to it.

Step 3: Add “WebApiConfig” Class

As usual we need to add the WebApiConfig class under folder “App_Start” which contains the code below:

This class is responsible to enable routing attributes on our controller.

Step 4: Add new protected (secured) controller

Now we want to add a controller which will serve as our protected resource, this controller will return list of claims for the authorized user, those claims for sure are encoded within the access token we’ve obtained from the Authorization Server. So add new controller named “ProtectedController” under “Controllers” folder and paste the code below:

Notice how we attribute the controller with [Authorize] attribute which will protect this resource and only will allow HTTP GET requests containing a valid bearer access token sent in the authorization header to pass, in more details when the request is received the OAuth bearer authentication middle ware will perform the following:

  1. Extracting the access token which is sent in the “Authorization header” with the “Bearer” scheme.
  2. Extracting the authentication ticket from access token, this ticket will contain claims identity and any additional authentication properties.
  3. Checking the validity period of the authentication ticket.

Step 5: Hosting the Authorization Server and Resource Server on different machines

Until this step and if you are developing locally on your dev machine, if you tried to obtain an access token from your Authorization Server i.e. (http://AuthServer/token) and then send this access token to the secured end point in our Resource Server i.e. (http://ResServer/api/protected) the result for this request will pass and you will have access to the protected resource, how is this happening?

One your dev machine once you request an access token from your Authorization Server; the OAuth middleware will use the default data protection provider in your Authorization Server, so it will use the “validationKey” value in machineKey node stored in machine.config file to issue the access token and protect it. The same case applies when you send the access token to your Resource Server, it will use the same machineKey to decrypt the access token and extract the authentication ticket from it.

The same applies if you are planing on your production environment to host your Authorization Server and your Resource Server on the same machine.

But in our case I’m hosting my Authorization Server on Azure website using West-US region, and my Resource Server is hosted on Azure websites on East-US region so both are totally on different machines and they share different machine.config files. For sure I can’t change anything on machine.config file because it is used by different sites on the Azure VMs I’m hosting my APIs on it.

So to solve this case we need to override the machineKey node for both APIs (Authorization Server and Resource Server) and share the same machineKey between both web.config files.

To do so we need to generate a new machineKey using this online tool, the result after using the tool will be as the below: As advised by Barry Dorrans it is not recommend to use an online tool to generate your machineKey because you do not know if this online tool will store the value for your machineKey in some secret database, it is better to generate the machineKey by your self.

To do so I’ll follow the steps mentioned in article KB 2915218, Appendix A which uses Power Shell commands to generate machineKey, so after you open Power Shell and run the right command as the image below you will receive new machineKey
PowerShell MachineKey

Note: Do not use those for production and generate a new machineKey for your Servers using Power Shell.

After you generate it open the web.config file for both the Authorization Server (AngularJSAuthentication.API project) and for the Resource Server (AngularJSAuthentication.ResourceServer) and paste the machineKey node inside the <system.web> node as the below:

By doing this we’ve unified the machineKey for both Authorization Server and Resource Server (Only this API in case of Azure shared hosting or any other shared host) and we are ready now to test our implementation.

Step 6: Testing the Authorization Server and Resource Server

Now we need to obtain an access token from our Authorization Server as we did before in the previous posts, so we can issue HTTP POST to the end point (http://ngauthenticationapi.azurewebsites.net/token) including the resource owner username and password as the image below:

Obtain Access Token

If the request succeeded we’ll receive an access token, then we’ll use this access token to send HTTP GET request to our new Resource Server using the protected end point (http://ngauthenticationresourcesapi.azurewebsites.net/api/protected), for sure we need to send the access token in the Authorization header using bearer scheme, the request will be as the image below:

Consume Access Token

As you notice we’re now able to access the protected resource in our new Resource Server and the claims for this identity which obtained from the Authorization Server are extracted.

That’s it for now folks, hopefully this short walk through helped in understanding how we can decouple the Authorization Server from the Resource Server.

If you have any comment or question please drop me a comment

You can use the following link to check the demo application.

You can use the following link to test the Authorization Server (http://ngauthenticationAPI.azurewebsites.net),

You can use the following link to test the Resource Server (http://ngauthenticationResourcesAPI.azurewebsites.net) 

You can check the source code on Github.

REF: http://bitoftech.net/2014/09/24/decouple-owin-authorization-server-resource-server-oauth-2-0-web-api/

[Dev Tip] The Onion Architecture

Part 1 – begin:

I’ve spoken several times about a specific type of architecture I call “Onion Architecture”.  I’ve found that it leads to more maintainable applications since it emphasizes separation of concerns throughout the system.  I must set the context for the use of this architecture before proceeding.  This architecture is not appropriate for small websites.  It is appropriate for long-lived business applications as well as applications with complex behavior.  It emphasizes the use of interfaces for behavior contracts, and it forces the externalization of infrastructure.  The diagram you see here is a representation of traditional layered architecture.   This is the basic architecture I see most frequently used.  Each subsequent layer depends on the layers beneath it, and then every layer normally will depend on some common infrastructure and utility services.  The big drawback to this top-down layered architecture is the coupling that it creates.  Each layer is coupled to the layers below it, and each layer is often coupled to various infrastructure concerns.  However, without coupling, our systems wouldn’t do anything useful, but this architecture creates unnecessary coupling.

The biggest offender (and most common) is the coupling of UI and business logic to data access.  Yes, UI is coupled to data access with this approach.  Transitive dependencies are still dependencies.  The UI can’t function if business logic isn’t there.  Business logic can’t function if data access isn’t there.  I’m intentionally ignoring infrastructure here because this typically varies from system to system.  Data access changes frequently.  Historically, the industry has modified data access techniques at least every three years; therefore, we can count on needing to modify data access three years from now for any healthy, long-lived systems that’s mission-critical to the business.  We often don’t keep systems up-to-date because it’s impossible to do.  If coupling prevents easily upgrading parts of the system, then the business has no choice but to let the system fall behind into a state of disrepair.  This is how legacy systems become stale, and eventually they are rewritten.

I propose a new approach to architecture.  Honestly, it’s not completely new, but I’m proposing it as a named, architectural pattern.  Patterns are useful because it gives software professionals a common vocabulary with which to communicate.  There are a lot of aspects to the Onion Architecture, and if we have a common term to describe this approach, we can communicate more effectively.

The diagram to the left depicts the Onion Architecture.  The main premise is that it controls coupling.  The fundamental rule is that all code can depend on layers more central, but code cannot depend on layers further out from the core.  In other words, all coupling is toward the center.   This architecture is unashamedly biased toward object-oriented programming, and it puts objects before all others.

In the very center we see the Domain Model, which represents the state and behavior combination that models truth for the organization.  Around the Domain Model are other layers with more behavior.  The number of layers in the application core will vary, but remember that the Domain Model is the very center, and since all coupling is toward the center, the Domain Model is only coupled to itself.  The first layer around the Domain Model is typically where we would find interfaces that provide object saving and retrieving behavior, called repository interfaces.  The object saving behavior is not in the application core, however, because it typically involves a database.  Only the interface is in the application core.  Out on the edges we see UI, Infrastructure, and Tests.  The outer layer is reserved for things that change often.  These things should be intentionally isolated from the application core.  Out on the edge, we would find a class that implements a repository interface.  This class is coupled to a particular method of data access, and that is why it resides outside the application core.  This class implements the repository interface and is thereby coupled to it.

The Onion Architecture relies heavily on the Dependency Inversion principle.  The application core needs implementation of core interfaces, and if those implementing classes reside at the edges of the application, we need some mechanism for injecting that code at runtime so the application can do something useful.

The database is not the center.  It is external.   Externalizing the database can be quite a change for some people used to thinking about applications as “database applications”.  With Onion Architecture, there are no database applications.  There are applications that might use a database as a storage service but only though some external infrastructure code that implements an interface which makes sense to the application core.  Decoupling the application from the database, file system, etc, lowers the cost of maintenance for the life of the application.

Alistair Cockburn has written a bit about Hexagonal architecture.  Hexagonal architecture and Onion Architecture share the following premise:  Externalize infrastructure and write adapter code so that the infrastructure does not become tightly coupled.

I’ll be writing more about the Onion Architecture as a default approach for building enterprise applications.  I will stay in the enterprise system space and all discussion will reside in that context.  This gets even more interesting when there are multiple processes making up a single software system.

Part 1 – end

Part 2 – begin:

In part 1, I introduced an architectural pattern that I have named “Onion Architecture”.  The object-oriented design concepts are not new, but I’m pulling together a lot of techniques and conventions into a single pattern and giving it a name.  My hope is that the industry can use this name to communicate the architectural approach where appropriate.

Part 2:  Practical example:

CodeCampServer uses the Onion Architecture.  If you are looking for a full, working application as an example, please have a look.  The practical example I put before you is taken directly from CodeCampServer.  It is a narrow, vertical slice of an example.  I’m keeping the scope small as to be digestible.  I’ll start with a diagram so you can understand where all the code resides within the layers of the onion.

CodeCampServer uses the ASP.NET MVC Framework, so SpeakerController is part of the user interface.  This controller is coupled to the ASP.NET MVC Framework, and there is no getting around that.  SpeakerController depends on IConferenceRepository and IUserSession (and IClock, but we’ll omit that).  The controller only depends on interfaces, which are defined in the application core.  Remember that all dependencies are toward the center.

Turn your attention to the ConferenceRepository and UserSession classes.  Notice that they are in layers outside of the application core, and they depend on the interfaces as well, so that they can implement them.  These two classes each implement an interface closer to the center than itself.  At runtime, our Inversion of Controlcontainer will look at its registry and construct the proper classes to satisfy the constructor dependencies of SpeakerController, which is the following:

public SpeakerController(IConferenceRepository conferenceRepository,
                         IUserSession userSession, IClock clock)
    : base(userSession)
{
    _conferenceRepository = conferenceRepository;
    _clock = clock;
    _userSession = userSession;
}

At runtime, the IoC container will resolve the classes that implement interfaces and pass them into the SpeakerController constructor.  At this point in time, the SpeakerController can do its job.

Based on the rules of the Onion Architecture, the SpeakerController _could_ use UserSession directly since it’s in the same layer, but it cannot use ConferenceRepository directly.  It must rely on something external passing in an instance of IConferenceRepository.  This pattern is used throughout, and the IoC container makes this process seamless.

At the end of this series, I plan on publishing a full working system that adheres to the Onion Architecture pattern.  The systems we build for clients use this approach, but I’m not at liberty to discuss that code, so I will craft a reference application for those of you who prefer a concrete Visual Studio solution to digest.

Part 2 – end

Part 3 – begin:

In my previous installments, I described what has become my approach to defining the architecture for an application.  Based on feedback, I’ve modified my diagrams a bit to reduce ambiguity and emphasize key points.  The goal of part 3 of this series is to compare and contrast the Onion Architecture with traditional layered architecture.  I will flatten the Onion Architecture to see what it looks like compared to traditional layered architecture, and I will force the layered architecture into an onion.  Whereas the shape can be either, the structure of the actual application is radically different from what is commonly known and accepted.  I’ll define four tenets of Onion Architecture at the end.

I must stress again:  I am not claiming any breakthroughs in technology or technique.  I have learned from other industry thought leaders like Martin Fowler, Ward Cunningham, Kent Beck, Michael Feathers and others (especially those I’ve had the privilege to work with here in Austin, TX).  I’m putting forth the Onion Architecture as an architectural pattern by which we can communicate this radically different architectural approach.  Not “radically different as in new”.  Different as in not mainstream.

Let’s review.  Traditional layered architecture can look somewhat like the diagram depicted on the right.  Each layer communicates with the layer below it.  The UI talks to business logic, but it does not talk directly to data access, WCF, etc.  The layering approach does call out the need to keep certain categories of code out of the UI.  The big downfall is that business logic ends up coupled to infrastructure concerns.  Data Access, I/O, and Web Services are all infrastructure.  Infrastructure is any code that is a commodity and does not give your application a competitive advantage.  This code is most likely to change frequently as the application goes through years of maintenance.  Web services are still fairly new, and the first version in .Net, ASMX, is already deprecated in favor of WCF.  We can be assured that WCF’s days are numbered as well, so it is foolish to tightly couple the business logic to WCF.  Data access changes every two years or so, so we definitely don’t want to be tightly coupled to it.  For long-life, we would want our business logic to be independent of these infrastructure concerns so that as infrastructure changes, the business logic doesn’t have to.

Let’s review Onion Architecture.  The object model is in the center with supporting business logic around it.  The direction of coupling is toward the center.  The big difference is that any outer layer can directly call any inner layer.   With traditionally layered architecture, a layer can only call the layer directly beneath it.  This is one of the key points that makes Onion Architecture different from traditional layered architecture.  Infrastructure is pushed out to the edges where no business logic code couples to it.  The code that interacts with the database will implement interfaces in the application core.  The application core is coupled to those interfaces but not the actual data access code.  In this way, we can change code in any outer layer without affecting the application core.  We include tests because any long-lived application needs tests.  Tests sit at the outskirts because the application core doesn’t couple to them, but the tests are coupled to the application core.  We could also have another layer of tests around the entire outside when we test the UI and infrastructure code.

This approach to application architecture ensures that the application core doesn’t have to change as:  the UI changes, data access changes, web service and messaging infrastructure changes, I/O techniques change.

To the right, I have created a diagram which attempts to show what Onion Architecture would look like when represented as a traditionally layered architecture.  The big difference is that Data Access is a top layeralong with UI, I/O, etc.  Another key difference is that the layers above can use any layer beneath them, not just the layer immediately beneath.  Also, business logic is coupled to the object model but not to infrastructure.

To the left here I have attempted to represent traditionally layered architecture using concentric circles.  I have used black lines around the layers to denote that each outer layer only talks to the layer immediately toward the center.  The big kicker here is that we clearly see the application is built around data access and other infrastructure.  Because the application has this coupling, when data access, web services, etc. change, the business logic layer will have to change.  The world view difference is how to handle infrastructure.  Traditional layered architecture couples directly to it.  Onion Architecture pushes it off to the side and defines abstractions (interfaces) to depend on.  Then the infrastructure code also depends on these abstractions (interfaces).  Depending on abstractions is an old principle, but the Onion Architecture puts that concepts right up front.

Key tenets of Onion Architecture:

  • The application is built around an independent object model
  • Inner layers define interfaces.  Outer layers implement interfaces
  • Direction of coupling is toward the center
  • All application core code can be compiled and run separate from infrastructure

I encourage you to use the term “Onion Architecture” when speaking about architectures that adhere to the above four tenets.  I believe that this approach to architecture leads to long-lived systems that are easy to maintain.  Also, in my experience, this architecture yields dividends soon after a project starts since it makes the code a breeze to change.

Although I don’t call out an IoC container as a key tenet, when using a mainstream language like Java or C#, an IoC container makes the code fit together very easily.  Some languages have IoC features built-in, so this is not always necessary.  If you are using C#, I highly recommend using Castle Windsor or StructureMap.

Part 3 – end

Part 4 – begin:

In 2008, I coined a new pattern name called Onion Architecture.  You can read the previous parts here: part 1part 2part 3.  Over these four years, I’ve spoken about this pattern at user groups, conferences, and it’s even published in one of the chapters of ASP.NET MVC in Action from Manning.

I’ve been overwhelmed by the traction this pattern name has enjoyed.  Folks from all over the country have written about and have talked about the pattern.  Some of the ones I’ve noticed are here (please comment with more – I welcome it).

Back in 2008, I defined four tenets of Onion Architecture:

  • The application is built around an independent object model
  • Inner layers define interfaces.  Outer layers implement interfaces
  • Direction of coupling is toward the center
  • All application core code can be compiled and run separate from infrastructure

Although there has been significant adoption of this pattern, I have received countless questions about how to implement it in various environments.  I mostly get asked about how it relates to domain-driven design.  First, onion architecture works well with and without DDD patterns.  It works well with CQRS, forms over data, and DDD.  It is merely an architectural pattern where the core object model is represented in a way that does not accept dependencies on less stable code.

CodeCampServer was an original sample of onion architecture, but it also grew as a sample of how to do ASP.NET MVC in various ways, how to use Portable Areas, and how to use MvcContrib features like input builders.  If you are just looking for onion architecture, it has too much going on.  I have pushed a much simpler solution that represents onion architecture concepts.  I have intentionally not included a UI input form or an IoC container, which most people associate with onion architecture.  Onion architecture works just fine without the likes of StructureMap or Castle Windsor.  Please check out the code here and let me know if this presents a simple approach – that is the goal.

When there is enough interest, I will continue this series with more parts.  CQRS definitely deserves some addressing within this architecture, and so do object models that support task-based UIs.

Get the code here at my BitBucket repository.

Part 4 – end

Ref: http://jeffreypalermo.com/blog/the-onion-architecture-part-1/

Source code: https://mega.co.nz/#!5ppTVJIY!x4pDBusK15psNmaMcgm3pemq6gah0KlwX4tKBKN_gr0

[Dev tip] Difference between WCF and Web API and WCF REST and Web Service

Web Service

  1. It is based on SOAP and return data in XML form.
  2. It support only HTTP protocol.
  3. It is not open source but can be consumed by any client that understands xml.
  4. It can be hosted only on IIS.

WCF

  1. It is also based on SOAP and return data in XML form.
  2. It is the evolution of the web service(ASMX) and support various protocols like TCP, HTTP, HTTPS, Named Pipes, MSMQ.
  3. The main issue with WCF is, its tedious and extensive configuration.
  4. It is not open source but can be consumed by any client that understands xml.
  5. It can be hosted with in the applicaion or on IIS or using window service.

WCF Rest

  1. To use WCF as WCF Rest service you have to enable webHttpBindings.
  2. It support HTTP GET and POST verbs by [WebGet] and [WebInvoke] attributes respectively.
  3. To enable other HTTP verbs you have to do some configuration in IIS to accept request of that particular verb on .svc files
  4. Passing data through parameters using a WebGet needs configuration. The UriTemplate must be specified
  5. It support XML, JSON and ATOM data format.

Web API

  1. This is the new framework for building HTTP services with easy and simple way.
  2. Web API is open source an ideal platform for building REST-ful services over the .NET Framework.
  3. Unlike WCF Rest service, it use the full featues of HTTP (like URIs, request/response headers, caching, versioning, various content formats)
  4. It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection, unit testing that makes it more simple and robust.
  5. It can be hosted with in the application or on IIS.
  6. It is light weight architecture and good for devices which have limited bandwidth like smart phones.
  7. Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML or whatever format you want to add as a MediaTypeFormatter.

To whom choose between WCF or WEB API

  1. Choose WCF when you want to create a service that should support special scenarios such as one way messaging, message queues, duplex communication etc.
  2. Choose WCF when you want to create a service that can use fast transport channels when available, such as TCP, Named Pipes, or maybe even UDP (in WCF 4.5), and you also want to support HTTP when all other transport channels are unavailable.
  3. 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).
  4. Choose Web API when you want to expose your service to a broad range of clients including browsers, mobiles, iphone and tablets.

[Life] Useful tools

http://www.hanselman.com/blog/ScottHanselmans2014UltimateDeveloperAndPowerUsersToolListForWindows.aspx

Script to take ownership of folder (add to context menu):


Windows Registry Editor Version 5.00

;Adds Take Ownership command to the context menu in Vista
;Also provides "Administrators" group with Full Control permissions.

[-HKEY_CLASSES_ROOT\*\shell\runas]

[HKEY_CLASSES_ROOT\*\shell\runas]
@="Take Ownership"
"Extended"=""
"NoWorkingDirectory"=""

[HKEY_CLASSES_ROOT\*\shell\runas\command]
@="cmd.exe /c takeown /f \"%1\" && icacls \"%1\" /grant administrators:F"

[-HKEY_CLASSES_ROOT\Directory\shell\runas]

[HKEY_CLASSES_ROOT\Directory\shell\runas]
@="Take Ownership"
"Extended"=""
"NoWorkingDirectory"=""

[HKEY_CLASSES_ROOT\Directory\shell\runas\command]
@="cmd.exe /c takeown /f \"%1\" /r /d y && icacls \"%1\" /grant administrators:F /t"

[Infographic] 15 mẹo nhỏ chống mệt mỏi sau chuyến bay dài

header - lam sao de han che trieu chung met moi sau mot chuyen bay dai.

Hiện nay du lịch đã trở thành một ngành kinh tế mũi nhọn của hầu hết các quốc gia trên thế giới. Du lịch không chỉ đem lại lợi ích về kinh tế mà còn là cơ hội quảng bá truyền thống văn hoá của mỗi quốc gia.Du lịch phát triển kéo theo sự gia tăng của nhiều dịch vụ kèm theo như nhà hàng, khách sạn,…và giao thông đặc biệt là đường hàng không.

Di chuyển bằng máy bay đem lại nhiều sự tiện lợi cho du khách, tuy nhiên có một vấn đề mà hầu hết ai cũng gặp phải là sựmệt mỏi sau những chuyến bay đường dài. Mệt mỏi kéo dài do cơ thể không kịp thích nghi với sự thay đổi múi giờ gây ra ảnh hưởng không nhỏ đến việc tận hưởng kỳ nghỉ của mỗi du khách. Infographic dưới đây sẽ giới thiệu vài điều cơ bản cần lưu ý về triệu chứng mệt mỏi này và những mẹo nhỏ giúp hạn chế tác động của nó lên cơ thể.

[Submit] lam sao de han che trieu chung met moi sau mot chuyen bay dai.

Nguồn: graphs.net