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

N-Tier development with ASP.NET MVC, WCF, and LINQ

, 5 Jan 2009
Rate this:
Please Sign up or sign in to vote.
This article presents a demo bug-tracking application built on ASP.NET MVC, WCF, and LINQ to SQL.

Introduction

This article is about a possible way to implement an N-Tier architecture for ASP.NET MVC (Model View Controller), using WCF (Windows Communication Foundation = replacement for .NET Remoting) and LINQ to SQL. This article will not go in depth explaining the ins and outs of MVC, WCF, and LINQ (there's already enough stuff which explains these technologies ...); instead, I'll be showing a possible way to implement these features in an N-Tier environment, by means of a simple bug-tracking demo application.

Requirements of the Bug-Tracking Demo Application

First, we should state the requirements of our demo application. These are quit straightforward, as mentioned beneath:

  • We want the application to produce a list of currently added bug-tracking tickets.
  • We want the possibility that a user can add a ticket to the system, which evolves adding a ticket date, selecting a user to whom we grant the ticket, adding a ticket date, and letting the user add some comments.
  • Before adding a new ticket to the system, we want to be sure that the user has supplied a valid date, selected a ticket type and user, and added some comments for the ticket.

Architectural Overview

architecture.jpg

The .NET Solution consists of three main projects:

  • BtDataLayer: Contains the model classes and the data access routines.
  • BtWcfService: Contains the services which the presentation layer may call.
  • BugTracking: Contains the presentation layer (ASP.NET MVC app).

Another project not mentioned on the diagram above is CommonLib, which contains the commonly used routines (like a business base class which each model class derives from, method for cloning objects, and a business rule validator engine).

Using the Code

The Data Access Layer (BtDataLayer)

  • The model classes (BugTracker.dbml):
  • bugtrackrelations.jpg

    These are the LINQ-TO-SQL classes retrieved from the SQL-Server Bugtracker database (database template included in the Zip file). As this model should be remotable, the serialization mode on the datacontext should be set to Unidirectional.

  • The Data Access Code (btDataManger.cs):
  • We want to be able to load a user-list so we can select a user for whom the ticket applies to:

    public static List<user> GetUserList()
    {
       // Create the DataContext to retrieve the Users from.
       BugTrackerDataContext db = new BugTrackerDataContext();
    
       // Return a list of Users.
       return db.Users.ToList<user>();
    }

    We want to be able to load a tickettype list, so we can select the type of ticket (BUG, INFO, etc ...) for the ticket:

    public static List<tickettype> GetTicketTypeList()
    {
       // Create the DataContext to retrieve the Ticket Types from.
       BugTrackerDataContext db = new BugTrackerDataContext();
    
       // Return a list of TicketTypes.
       return db.TicketTypes.ToList<tickettype>();
    }

    We want to be able to retrieve all the current tickets from our ticket table:

    public static IEnumerable<ticket> GetTickets()
    {
       // Create the DataContainer to retrieve the tickets.
       BugTrackerDataContext db = new BugTrackerDataContext();
                
       // Return a List of Tickets
       return db.Tickets;
    }

    Finally, we want to have the possibility to persist a newly added ticket (one at a time for the demo application, but we make the method all-purpose, so it can accept many added or modified objects):

    public static bool PersistTickets(ref TicketList p_tickets)
    {
        // Only persist if any tickets to add or modify.
        if (p_tickets == null || p_tickets.Count == 0)
            return false;
    
        // Create the persistence datacontext
        BugTrackerDataContext db = new BugTrackerDataContext();
    
        // Persist any new or modified tickets.
        foreach (Ticket t in p_tickets)
        {
            if (t.TicketId == 0)
            {
                db.Tickets.InsertOnSubmit(t);
    
            }
            else
            {
                db.Tickets.Attach(t, t.IsDirty);
            }
        }
    
        try
        {
            db.SubmitChanges(ConflictMode.ContinueOnConflict);
    
            // Reset the isDirty flag.
            foreach (Ticket t in p_tickets)
            {
                t.IsDirty = false;
            }
    
        }
        catch (ChangeConflictException ex)
        {
            throw ex;
        }
    
        return true;
    }

The Service Layer

The purpose of our WCF enabled service layer is to make the model and data-access routines (to foresee the model of data ...) available to the presentation layer.

Our service layer consists mainly of two routines:

  • The service contract (which contains the routines which can be called by our Web App).
  • [ServiceContract]
    public interface IBtService
    {
        [OperationContract()]
        IEnumerable<user> GetUserList();
    
        [OperationContract()]
        IEnumerable<tickettype> GetTicketTypeList();
    
        [OperationContract()]
        bool PersistTickets(ref TicketList p_tickets);
    
        [OperationContract()]
        IEnumerable<ticket> GetTickets();
    }
  • The Service Implementation, which implements our contract and calls the datalayer.
  • public IEnumerable<user> GetUserList()
    {
        return BtDataManager.GetUserList();
    }
    
    public IEnumerable<tickettype> GetTicketTypeList()
    {
        return BtDataManager.GetTicketTypeList();
    }
    
    public bool PersistTickets(ref TicketList p_tickets)
    {
        return BtDataManager.PersistTickets(ref p_tickets);
    }
    
    public IEnumerable<ticket> GetTickets()
    {
        return BtDataManager.GetTickets();
    }

The Presentation Layer

The presentation layer contains our ASP MVC application. As already mentioned above, I will not go in depth on MVC, as there is already a lot of info available on the net. But it is important to know that MVC contains three main items, namely the Model (which represents our class, a validation logic, and is remotely available through the Service Layer), the View (our webpage), and the Controller (which basically "hooks" the Model to the View).

The Views and the Controllers

Our demo application hosts the following MVC enabled web pages:

Ticket.aspx

ticket.jpg

With this page, the user can add a bug-ticket to the system. The HomeController is responsible for rendering the page. While interacting with the page, there are two actions involved, one for creating a new ticket (the "GET") version, and one for persisting a new ticket (when the user hits the Submit button: the POST version).

[AcceptVerbs("GET")]
public ActionResult Ticket()
{
    this.LoadSelectionLists();

    // Get the userlist
    var userList = new SelectList(_userList, "UserId", "Username");
    ViewData["UserId"] = userList;

    // Get the tickettypelist
    var ticketTypeList = new SelectList 
    (_ticketTypeList, "TicketTypeId", "TicketTypeDescription");
    ViewData["TicketTypeId"] = ticketTypeList;

    return View();
}

When the user selects "Create Ticket" in the index page, we must create a new page where the user may enter the ticket details. As the user should have the possibility to select a user and ticket type for the ticket, these data are loaded from the service and added to the viewstate of the form:

private void LoadSelectionLists()
{
    // Get a proxy to the data service provider
    BtServiceRef.BtServiceClient proxy = new   
    BugTracking.BtServiceRef.BtServiceClient();

    // Get the userlist
    _userList = proxy.GetUserList();
    
    // Get the tickettypelist
    _ticketTypeList = proxy.GetTicketTypeList();
   
}

On the other hand, the post version is executed when the user hits the "Submit" button. We will create a ticket object, map the properties to the field properties of the form, validate the objects data (see the source code of the model for detailed validation information as validation data is stored in the model classes), and persist the newly added ticket through the service to the database.

[AcceptVerbs("POST")]
public ActionResult Ticket(FormCollection p_form)
{
    // Create placeholder for the ticket to add.
    var TicketToCreate = new Ticket();

    
    try
    {
        // Map the controls of the View to the PlaceHolder.
        this.UpdateModel(TicketToCreate, new[]  
        { "UserId", "TicketTypeId", "Comment", "GrantedToDate" });
        
        // Force Validation
        TicketToCreate.Validate();

        // First check if any validation Errors Exist on the newly 
           added ticket
        if (TicketToCreate.HasErrors)
        {
            
            // View Validation Errors

            foreach(DictionaryEntry entry in  
            TicketToCreate.ValidationErrors)
            {

                ViewData.ModelState.AddModelError(entry.Key.ToString
                (), entry.Value.ToString());
            }
            
            throw new InvalidOperationException();
        }
        else
        {
            // Create the WCF Remote service and let the service 
               persist the new ticket.
            BtServiceRef.BtServiceClient proxy = new 
            BugTracking.BtServiceRef.BtServiceClient();
            Ticket[] newTicketList = new Ticket[] { TicketToCreate };
            proxy.PersistTickets(ref newTicketList);
        }
       
    }
    catch
    {
        this.LoadSelectionLists();

        var userList = new SelectList(_userList, "UserId", "Username");
        ViewData["UserId"] = userList;

        var ticketTypeList = new SelectList  
        (_ticketTypeList, "TicketTypeId", "TicketTypeDescription");
        ViewData["TicketTypeId"] = ticketTypeList;


        // Show possible validation errors.
        return View(TicketToCreate);
    }
    
    // Return to main page.
    return RedirectToAction("Index");
}

There are two comboboxes on the ticket.aspx form: one for user selection and one for ticket type selection. As shown in the code above, we load the user and ticket type records from the service and add them as ViewData of the ticket page. Next, we have to bind the ViewData as mentioned below (you can also notice how we execute the bindings for validation purpose):

dropdown.jpg

Index.aspx

When loading the application in the browser, the index page is the first page shown. We get a list of current tickets in the database and the possibility to add a new ticket to the system:

indexpage.jpg

Again, the HomeController is responsible for rendering the page, the action involved is:

public ActionResult Index()
{
    ViewData["Title"] = "Home Page";
    ViewData["Message"] = "Welcome to ASP.NET MVC Bugtracker !";

    // Create a proxy to the WCF service.
    BtServiceRef.BtServiceClient proxy = 
       new BugTracking.BtServiceRef.BtServiceClient();

    // Get all tickets from the DataLayer.
    return View(proxy.GetTickets());
}

As we will show the current tickets in this page, we first create a reference to our service. This service calls the GetTickets() method of our data layer data-access class and adds it as input parameter of the view. Next, to be sure that our Index Page is aware of the loaded ticket-list, the BtDataLayer.Ticket type should be added as an attribute to the derived ViewPage:

indexpage_classdef.jpg

Finally, in the HTML code of our index.aspx page, we can loop through our loaded ticket list and place each ticket in a data row:

tickets_in_table.jpg

You may have noticed that I display the UserId and TickeTypeId instead of the user name and ticket type description. If you want to view, for example, the username instead of the ID, you should use: t.User.UserName, but this will return an error, as the user is not loaded with the tickets. You can change this by altering the data access method and adding data load options for the user and ticket type. In this case, the related user and ticket type objects will be loaded too.

Final Word

Voilà, that's all to mention. This article showed a possible way to separate logical layers and pass data between boundaries using new technologies such as WCF and LINQ-to-SQL. Finally, it showed a possible presentation layer, using the newest ASP.NET MVC technology. Special thanks goes to the people running the ASP.NET website www.asp.net and also special thanks goes to Beth Massi: http://blogs.msdn.com/bethmassi/, for explaining LINQ-to-SQL and N-Tier through WCF in a well structured and clear view.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Emmanuel Nuyttens
Architect REALDOLMEN
Belgium Belgium
Working in the IT-Branch for more then 15 years now. Starting as a programmer in WinDev, moved to Progress, shifted to .NET since 2003. At the moment i'm employed as a Microsoft Dynamics AX Interfacing Architect at RealDolmen (Belgium). In my spare time, i'm a die hard mountainbiker and together with my son Jarne, we're climbing the hills in the "Flemish Ardens" and the wonderfull "Pays des Collines". I also enjoy "a p'tit Jack" (Jack Daniels Whiskey) or a "Duvel" (beer) for "l'après VTT !".

Comments and Discussions

 
QuestionOh luck PinmemberAdrian Co1-Jul-13 2:14 
GeneralMy vote of 5 Pinmemberhebsiboy23-May-13 19:18 
GeneralMy vote of 4 PinmemberHimanshu Thawait25-Feb-13 8:52 
GeneralMy vote of 1 PinmemberPradeep Mareddi26-Oct-12 2:25 
GeneralMy vote of 1 Pinmemberrituranjan Gupta4-Oct-12 3:10 
QuestionMissing CommonLib Pinmemberamitnitinshah23-Jul-12 20:56 
Question32237 no common lib folder included. PinmemberHarryy8821-May-12 21:50 
QuestionMissing CommonLib project and contents Pinmembertraci dukes2-May-12 8:10 
QuestionHelp.! Pinmemberjoshad27-Apr-12 5:48 
Generalno commonlib proj... Pinmemberrobon.zhou5-Mar-12 22:20 
GeneralQuestion PinmemberDevUK3-May-11 0:14 
GeneralCommonLib.dll Pinmembervipalpatel161-Dec-10 0:41 
GeneralMy vote of 1 PinmemberVickyC#30-Oct-10 14:18 
GeneralMy vote of 5 PinmemberMoorzeee4-Aug-10 2:48 
GeneralBreaks Pinmemberkwilder20-Mar-10 9:33 
GeneralRe: Breaks PinmemberAli S Syed25-Oct-10 5:20 
GeneralDatabase and run time problems Pinmembertticom3-Mar-10 13:00 
GeneralRe: Database and run time problems PinmemberMember 14273407-Jul-10 2:43 
QuestionAble to open BTDataLayerProject only PinmemberTic120-Aug-09 0:33 
GeneralCommonLib PinmemberEmmanuel Nuyttens23-Jun-09 9:12 
GeneralCommonLib dll is in the downloaded zip file [modified] Pinmemberbrittoa18-Jun-09 13:40 
GeneralMy vote of 1 PinmemberVipul11-Jun-09 3:16 
GeneralRe: My vote of 1 PinmemberMember 431337218-Jun-09 1:38 
QuestionCommonLib PinmemberAnne Spalding30-Apr-09 5:16 
AnswerRe: CommonLib PinmemberHimanshu Thawait25-Feb-13 8:51 
QuestionBusiness/Data layer coupling Pinmembergojuro14-Apr-09 10:27 
AnswerRe: Business/Data layer coupling Pinmemberlustuyck29-Apr-09 3:02 
AnswerRe: Business/Data layer coupling PinmemberEmmanuel Nuyttens23-Jun-09 9:32 
GeneralRe: Business/Data layer coupling PinmemberKamran Shahid2-Nov-09 7:00 
GeneralWhere these error generated? [modified] Pinmemberavt2k630-Nov-12 11:12 
QuestionWhere is the CommonLib [modified] Pinmembergojuro14-Apr-09 10:09 
QuestionWhat about scenario whit Transaction ? Pinmemberneppo7528-Mar-09 7:05 
AnswerRe: What about scenario whit Transaction ? PinmemberEmmanuel Nuyttens23-Jun-09 9:24 
QuestionMissing CommonLib.csproj PinmemberTournesol26-Mar-09 5:06 
GeneralPresentation Layer referencing Data Layer PinmemberRoshambo19-Jan-09 21:48 
GeneralRe: Presentation Layer referencing Data Layer Pinmembermanu197119-Jan-09 23:47 
GeneralCommonLib Missing PinmemberRoshambo19-Jan-09 18:49 
GeneralSample DB missing PinmemberTodd Smith5-Jan-09 7:42 
GeneralRe: Sample DB missing Pinmemberbluetx18-Nov-09 4:44 
GeneralCommonLib missing PinmemberTodd Smith5-Jan-09 7:37 

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 | Mobile
Web04 | 2.8.140718.1 | Last Updated 5 Jan 2009
Article Copyright 2009 by Emmanuel Nuyttens
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid