Click here to Skip to main content
Click here to Skip to main content

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

, 10 Dec 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Vijay Tanwar
Software Developer (Senior) Nagarro Softwares
India India
I am vijay tanwar and i am a software engineer with passion of programming. I love to programming in c#, I love to warp up more and more things in few lines of code. my favirote languages are c# and javascript and both are fully object oriended. I always like to become the .net Architect.
Follow on   Twitter

Comments and Discussions

 
QuestionWhat would be the architecture diagram if we have a windows UI too? Pinmemberalborz moghadam29-Oct-13 4:13 
GeneralMy vote of 5 Pinmembergillindsay17-Dec-12 8:06 
GeneralMy vote of 2 PinmemberRobin Kumar10-Dec-12 20:16 
SuggestionMissing source code PinstaffSmitha Vijayan10-Dec-12 5:38 
GeneralRe: Missing source code PinmemberVijay Tamar10-Dec-12 6:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.141223.1 | Last Updated 10 Dec 2012
Article Copyright 2012 by Vijay Tanwar
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid