Click here to Skip to main content
15,867,453 members
Articles / Security

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

Rate me:
Please Sign up or sign in to vote.
4.62/5 (5 votes)
10 Dec 2012CPOL3 min read 39.3K   1.9K   41   5
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  

Image 1

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.

C#
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.

C#
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

XML
<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. 

C#
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.

C#
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)


Written By
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.

Comments and Discussions

 
QuestionWhat would be the architecture diagram if we have a windows UI too? Pin
alborz moghadam29-Oct-13 3:13
alborz moghadam29-Oct-13 3:13 
GeneralMy vote of 5 Pin
gillindsay17-Dec-12 7:06
professionalgillindsay17-Dec-12 7:06 
GeneralMy vote of 2 Pin
Robin Kumar10-Dec-12 19:16
Robin Kumar10-Dec-12 19:16 
SuggestionMissing source code Pin
Smitha Nishant10-Dec-12 4:38
protectorSmitha Nishant10-Dec-12 4:38 
GeneralRe: Missing source code Pin
Vijay Tanwar10-Dec-12 5:34
Vijay Tanwar10-Dec-12 5:34 
I have updated the article and also uploaded the source code and published the article, but when i click on download link, it open the another window with Download eShopping.zip - 5 MB and get stopped in the middle, please tell me the solutions.

Thanks
Vijay Tamar

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

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