Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

N - tier project with WCF OData service, Entity Framework, MVC3.0, Ninject DI, jSOn.net and Automapper

0.00/5 (No votes)
10 Dec 2012 1  
N-Tier application with WCF Odata service and Entity Framework.

Brief Introduction

This article try to explain unit testable, Decoupled, deployment flexible n-tier architecture. This architecture will also explain Repository pattern in MVC 3.0. It also describe how to inject dependencies using Ninject DI container, How to bind ViewModels to Model using Auto mapper, and create mobile ready site using CSS3.0 media queries.

Using the code

The project has been is created in Visual Studio 2010 with MVC 3.0 with Entity Framework 4.1 and I have also used third party libraries like AutoMapper, jSon.net, and Ninject.

Before you continue with this sample project you need to follow the below steps.

Install the Northwind database in SQL server (in my case I am using SQL Server Express 2008 R2) you can install the Northwind database in older versions also. Install the Ninject DI Container using this command( Install-Package Ninject) in Nuget package manager console. Install the AutoMapper using this command (Install-Package AutoMapper -Pre ) in Nuget package manager console. Modify the NorthwindEntities database connection string in Web.config file in eShopping UI project. If you have done every thing correctly just run the project.

Architecture of this project

There are five layers in this project 

  1. eShopping.eShoppingDB Persistent layer
  2. eShopping.Business Domain Layer or business layer
  3. eShopp.ing.Entities Business entities layer 
  4. eShopping UI layer 
  5. AuthenticationProvider  

AuthenticationProvider (AuthenticationProvider)

I have added the BasicAuthenticationProvider class to simulate the Authentication functionality, and following method return the true if user authenticated successfully, and set the current user to IPrincipal in current http context.

public static bool Authenticate(HttpContext context)
{
    if (!HttpContext.Current.Request.Headers.AllKeys.Contains("Authorization"))
        return false;

    string authHeader = HttpContext.Current.Request.Headers["Authorization"];

    IPrincipal principal;
    if (TryGetPrincipal(authHeader, out principal))
    {
        HttpContext.Current.User = principal;
        return true;
    }
    return false;
}
private static bool TryGetPrincipal(string authHeader, out IPrincipal principal)
{
    var creds = ParseAuthHeader(authHeader);
    if (creds != null && TryGetPrincipal(creds, out principal))
        return true;

    principal = null;
    return false;
}

Business Layer(eShopping.Business)

I am accessing WCF OData service using Data Service Context class and DbSContext is the instance of DataServiceContext class. DbSContext will always send the encrypted authorization header when sending request to WCF OData services to get the data. I have used to RijndaelManaged algorithm to encrypt the authorization header.

public static DataServiceContext DbSContext; static GlobalObjects()
{                
     DbSContext = new DataServiceContext(CommonVariables.DbServiceUrl);       
    DbSContext.SendingRequest += newEventHandler<sendingrequesteventargs>(OnSendingRequest);       
}

internal static void OnSendingRequest(object sender, SendingRequestEventArgs e)
{
    var creds = Encryption.EncryptString("Administrator") + 
                     Encryption.EncryptString("SecurePassword"); 
    var bcreds =Encoding.ASCII.GetBytes(creds); 
    var base64Creds = Convert.ToBase64String(bcreds);        
    e.RequestHeaders.Add("Authorization","Basic " + base64Creds); 
}

WCF OData Service (eShopping.DataService)

I have created a IHttp Module (BasicAuthenticationModule) to authenticate the OData requests from business layer, if user and password do not match, the service will return Unauthorized 404 error message.

I have register this module (BasicAuthenticationModule) in the web.config file

<httpModules>
 <add name="BasicAuthenticationModule" 
   type="eShopping.DataService.Authentication.BasicAuthenticationModule"/>
</httpModules>

When WCF OData service receive the request and then application calls the registered module to authenticate the request. 

public void Init(HttpApplication context)
{
    context.AuthenticateRequest += new EventHandler(context_AuthenticateRequest);
}
#endregion


void context_AuthenticateRequest(object sender, EventArgs e)      
{
     HttpApplication application = (HttpApplication)sender; 
     if(!BasicAuthenticationProvider.Authenticate(application.Context))       
     {              
       application.Context.Response.Status = "401Unauthorized";
       application.Context.Response.StatusCode = 401;
       application.Context.Response.AddHeader("WWW-Authenticate","Basic");
       application.CompleteRequest();
     } 
}

Business entities layer (eShopping.Entities)

I have placed the entities in one place to maintain the consistency and to remove duplicity. This will help in sharing the same entities in multiple projects like in Database layer, Business layer and UI layer.

UI layer (eShopping)

I have used the Ninjected DI as default Dependency injector, and Automapper to map the Models using view models. 

I have registered the AutoMapper in Global.asax file.

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
    ControllerBuilder.Current.SetControllerFactory(new eShoppingControllerFactory());
    InitializeAutoMapper();
}
private void InitializeAutoMapper()
{
    Mapper.CreateMap<customerview,>();
    Mapper.AssertConfigurationIsValid();
}

Disclaimer 

The project is solely based on my self study, knowledge and research, not based on any other project. I have used the term like eShopping but its totally demo term and does not relate to any practically working project. I have used the Microsoft Northwind database which is publically available sample database from Microsoft. I have not implemented a feature for eShopping like shopping, viewing products as they should be, my motive is only to describe n-tier architecture, and most commonly used open source tool with ASP.NET MVC3.0, like Ninject and AutoMapper. I have not added the unit test in this project, so if you want you can add unit test to this project. Please feel free to contact me to add some more functionality to this.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here