MVC Application Using n-tier Architecture

Introduction

This article explains how to create a real time MVC Web Application using n-tier architecture. The complete article goes through a sample customer information solution.

Modules

  1. Create a SampleCustomerInformation database using SQL Server.

  2. Create an empty MVC web application (Presentation Layer) using Visual Studio 2013.

    a. Creating controllers, views and respective HTML and JavaScript required.

  3. Adding another project to the solution for processing the data from SQL Server. Create a C# library project (Data Access Layer).

    a. Add an entity data model to connect to the database.
    b. Create classes to process all the requests from Business Service Layer
    c. Write necessary methods to process the requests in business service layer.

  4. Add another project to the solution for writing business logic. Create a WCF Service Library:

    a. Add necessary service parameters to the project required to write business logic
    b. Write necessary operation contracts to make available for Presentation Layer
    c. Use all the available methods from Data Access Layer to process data in Service Layer.

  5. Add necessary references to the projects in the solution.

  6. Add a Service Reference to Presentation Layer.

    a. Use all the available methods from service layer and process the requests.

Technologies Used

  1. ASP.NET MVC 5
  2. SQL Server 2014
  3. C# v5
  4. jQuery 2.14
  5. HTML5
  6. CSS3

IDE: Visual Studio 2013

Using the code

Module 1:

Creating a SampleCustomerInformation database using SQL Server,
  1. /****** Object: Database [SampleCustomerInformation]******/  
  2. CREATE DATABASE[SampleCustomerInformation]  
  3.   
  4. Create table CustomerInformation  
  5. (  
  6.     SNO int not null identity(0, 1),  
  7.     CustomerIDint not null primary key, [First Namevarchar(50) not null, [Last Namevarchar(50) not null,  
  8.     Email varchar(60) null,  
  9.     Phone varchar(13) not null, [User Namevarchar(60) not null, [Passwordvarchar(12) not null)  
  10.   
  11. Create table CustomerLoginActivity  
  12. (  
  13.     SNO int not null identity(0, 1), [User Nameint not null, [Passwordvarchar(60) not null, [Login TimeDate not null  
  14. )  
Module 2:

Create an empty MVC web application (Presentation Layer) using Visual Studio 2013, creating controllers, views and respective HTML and JavaScript required. Here, I used ajax jQuery to send data from View to Controller.

Some of many properties which can be used on ajax request,

 

  1. Method: Specify the type of operation (ex-GET, POST).
  2. Url: specify the path of the method.
  3. Data: specify the data which needs to transferred from View to Controller for processing.
  4. Success: Can specify set of statements needs to be done when success.
  5. Failure: Can specify set of statements needs to be done when failure.

More information about jQuery Ajax can be found here: jQuery Ajax

HTML

  1. <html>  
  2.   
  3. <head>  
  4.     <title>Welcome</title>  
  5.     <script src="~/Scripts/jquery-2.1.4.min.js">  
  6.         </script>  
  7.         <script src="~/Scripts/HomeScript.js">  
  8.             </script>  
  9. </head>  
  10.   
  11. <body>  
  12.     <form style="float:left">  
  13.         <h4>Sign Up</h4>  
  14.         <table>  
  15.             <tr>  
  16.                 <td>First Name</td>  
  17.                 <td>  
  18.                     <input type="text" name="firstName" id="firstName" placeholder="First Name" value="" required />  
  19.                 </td>  
  20.             </tr>  
  21.             <tr>  
  22.                 <td>Last Name</td>  
  23.                 <td>  
  24.                     <input type="text" name="lastName" id="lastName" placeholder="Last Name" value="" required />  
  25.                 </td>  
  26.             </tr>  
  27.             <tr>  
  28.                 <td>Email</td>  
  29.                 <td>  
  30.                     <input type="email" name="email" id="email" placeholder="Email" value="" required />  
  31.                 </td>  
  32.             </tr>  
  33.             <tr>  
  34.                 <td>Phone Number</td>  
  35.                 <td>  
  36.                     <input type="text" name="phoneNumber" placeholder="Phone Number" id="phoneNumber" value="" />  
  37.                 </td>  
  38.             </tr>  
  39.             <tr>  
  40.                 <td>Password</td>  
  41.                 <td>  
  42.                     <input type="password" name="password" placeholder="Password" id="password" value="" />  
  43.                 </td>  
  44.             </tr>  
  45.             <tr>  
  46.                 <td>Confirm Password</td>  
  47.                 <td>  
  48.                     <input type="password" name="confirmPassword" placeholder="Confirm Password" id="confirmPassword" value="" />  
  49.                 </td>  
  50.             </tr>  
  51.             <tr>  
  52.                 <td></td>  
  53.                 <td>  
  54.                     <input type="submit" name="btnRegister" id="btnRegister" value="Register" />  
  55.                 </td>  
  56.             </tr>  
  57.         </table>  
  58.     </form>  
  59.     <div style="float:left">  
  60.                       
  61.     </div>  
  62.     <form style="float:left">  
  63.         <h4>Login</h4>  
  64.         <table>  
  65.             <tr>  
  66.                 <td>User Name</td>  
  67.                 <td>  
  68.                     <input type="text" name="userName" placeholder="Email" id="userName" value="" />  
  69.                 </td>  
  70.             </tr>  
  71.             <tr>  
  72.                 <td>Password</td>  
  73.                 <td>  
  74.                     <input type="password" name="loginPassword" placeholder="Password" id="loginPassword" value="" />  
  75.                 </td>  
  76.             </tr>  
  77.             <tr>  
  78.                 <td></td>  
  79.                 <td>  
  80.                     <input type="submit" name="btnLogin" id="btnLogin" value="Login" />  
  81.                 </td>  
  82.             </tr>  
  83.         </table>  
  84.     </form>  
  85. </body>  
  86.   
  87. </html>  
JavaScript
  1. $(document).ready(function()   
  2.  {  
  3.     $("#btnRegister").click(function()  
  4.     {  
  5.         RegisterCustomer();  
  6.     });  
  7.   
  8.     $("#btnLogin").click(function()  
  9.     {  
  10.         LoginCustomer();  
  11.     });  
  12. });  
  13.   
  14. functionRegisterCustomer()  
  15. {  
  16.     var firstName = $("#firstName").val();  
  17.     var lastName = $("#lastName").val();  
  18.     var email = $("#email").val();  
  19.     var phoneNumber = $("#phoneNumber").val();  
  20.     var password = $("#password").val();  
  21.     varconfirmPassword = $("#confirmPassword");  
  22.   
  23.     //Attributes in "data" of ajax request should match the arguments defined in the method in controller  
  24.     $.ajax({  
  25.         method: "POST",  
  26.         url: "../Home/RegisterCustomer",  
  27.         data:  
  28.       {  
  29.             firstName: firstName,  
  30.             lastName: lastName,  
  31.             email: email,  
  32.             phoneNumber: phoneNumber,  
  33.             password: password  
  34.         }  
  35.     }).done(function(msg)  
  36.         {  
  37.         if (msg == "success")  
  38.             alert("Login Successful");  
  39.         else  
  40.             alert("Login Failed: " + msg);  
  41.     });  
  42. }  
  43.   
  44. functionLoginCustomer()  
  45. {  
  46.     var userName = $("#userName").val();  
  47.     var loginPassword = $("#loginPassword").val();  
  48.   
  49.     $.ajax({  
  50.             method: "GET",  
  51.             url: "../Home/LoginCustomer",  
  52.             data: {  
  53.                 userName: userName,  
  54.                 loginPassword: loginPassword  
  55.             }  
  56.         })  
  57.         .done(function(msg)  
  58.          {  
  59.             alert("Login Activity Saved");  
  60.         });  
  61. }  
Module 3:

Adding another project to the solution for processing the data from SQL Server. Create a C# library project (Data Access Layer),

 

  • Create classes to process all the requests from Business Service Layer.
  • Write necessary methods to process the requests in business service layer.
    1. public class RegisterCustomerDataAccessLayer {#region Register Customer  
    2.     public bool RegisterCustomer(string firstName, string lastName, string email, string phoneNumber, string password)  
    3.     {  
    4.         try {  
    5.             using(var dbContext = new SampleCustomerInformationEntities())  
    6.             {  
    7.                 CustomerInformation newCustomer = new CustomerInformation();  
    8.                 newCustomer.CustomerID = 2;  
    9.                 newCustomer.First_Name = firstName;  
    10.                 newCustomer.Last_Name = lastName;  
    11.                 newCustomer.Email = email;  
    12.                 newCustomer.Phone = phoneNumber;  
    13.                 newCustomer.Password = password;  
    14.                 newCustomer.User_Name = email;  
    15.                 dbContext.CustomerInformations.Add(newCustomer);  
    16.                 dbContext.SaveChanges();  
    17.                 return true;  
    18.             }  
    19.         } catch (Exception ex)  
    20.         {  
    21.             throw new Exception(ex.Message);  
    22.         }  
    23.     }#endregion  
    24. }  
    25.   
    26. public class CustomerLoginDataAccessLayer  
    27. {#region Customer Login  
    28.     public bool LoginCustomer(string userName, string loginPassword)  
    29.     {  
    30.         try {  
    31.             using(var dbContext = new SampleCustomerInformationEntities())   
    32.             {  
    33.                 CustomerInformation customer = new CustomerInformation();  
    34.                 customer = dbContext.CustomerInformations.FirstOrDefault(x => x.User_Name == userName && x.Password == loginPassword);  
    35.                 if (customer != null)  
    36.                     return true;  
    37.                 else  
    38.                     return false;  
    39.             }  
    40.         } catch (Exception ex)  
    41.         {  
    42.             throw new Exception(ex.Message);  
    43.         }  
    44.     }#endregion  
    45. }  

Module 4:

Add another project to the solution for writing business logic. Create a WCF Service Library.

A Service Contract defines what all the methods or operations available to the client from service endpoint. A service contract is an interface and it tells the client what service can do.

An Operation Contract is defined within the service contract and it has return type and parameters. Those operation contracts are implemented in the class which extends the service interface. Client can use this method to do operations.

A Data Contract describes the information which needs to be exchanged and it can be used in any operation contract as a parameter or return type. Based on the parameters and return types the data will be serialized/de-serialized to or from (Binary ó XML).

A Data Member attribute needs to be applied all the members of the data contract to indicate it as a data member, which means it should be serialized.

More information about Service Contracts can be found here:  Designing Service Contracts.
More information about Data Contracts can be found here: Using Data Contracts.

  • Write necessary operation contracts to make available for Presentation Layer.
  • Use all the available methods from Data Access Layer to process data in Service Layer.

 

  1. [ServiceContract]  
  2. public interface IService1  
  3. {  
  4.     [OperationContract]  
  5.     RegisterCustomerRequest RegisterCustomer(RegisterCustomerRequest request);  
  6.   
  7.     [OperationContract]  
  8.     LoginCustomerRequest LoginCustomer(LoginCustomerRequest request);  
  9.   
  10.     // TODO: Add your service operations here  
  11. }  
  12.   
  13.   
  14.   
  15. public class Service1: IService1  
  16. {#region IService1 Members  
  17.  
  18.     # region Register Customer  
  19.     public RegisterCustomerRequest RegisterCustomer(RegisterCustomerRequest request)  
  20.     {  
  21.         try {  
  22.             var registerCustomerDal = new RegisterCustomerDataAccessLayer();  
  23.             var customer = registerCustomerDal.RegisterCustomer(request.FirstName, request.LastName, request.Email, request.PhoneNumber, request.Password);  
  24.             if (customer)  
  25.                 request.RegisterCustomerResponse = "Success";  
  26.             else  
  27.                 request.RegisterCustomerResponse = "Failure";  
  28.             return request;  
  29.         } catch (Exception ex)  
  30.         {  
  31.             throw new Exception(ex.Message);  
  32.         }  
  33.         throw new NotImplementedException();  
  34.     }#  
  35.     endregion  
  36.  
  37.     # region Login Customer  
  38.     public LoginCustomerRequest LoginCustomer(LoginCustomerRequest request)  
  39.     {  
  40.         try {  
  41.             var customerLoginDal = new CustomerLoginDataAccessLayer();  
  42.             var validateLogin = customerLoginDal.LoginCustomer(request.UserName, request.Password);  
  43.             if (validateLogin)  
  44.                 request.LoginCustomerResponse = "Login Successful";  
  45.             else  
  46.                 request.LoginCustomerResponse = "Login Failed";  
  47.             return request;  
  48.         } catch (Exception ex)  
  49.         {  
  50.             throw new Exception(ex.Message);  
  51.         }  
  52.         throw new NotImplementedException();  
  53.     }#endregion# endregion  
  54. }  
Module 6: Add a Service Reference to Presentation Layer,

To add a service reference,

 

  • Right click on the references folder in the client side.
  • Click Add Service Reference.
  • Service reference can be found by entering the endpoint url or by clicking Discover.
  • Select the necessary service references and all the service contracts and operation contracts available can be accessed.

    Detailed information about consuming web service can be found here:   Consuming Web Service.

Controller: Use all the available methods from service layer and process the requests,

  1. // GET: Home View  
  2. public ActionResult Home()  
  3. {  
  4.     return View();  
  5. }  
  6.   
  7. //This method is used to register new customer  
  8. //This method is passed as a url to the Ajax function RegisterCustomer()  
  9. public string RegisterCustomer(string firstName, string lastName, string email, string phoneNumber, string password)  
  10. {  
  11.     try {  
  12.         SampleCustomerInformationServiceReference.RegisterCustomerRequest request = new SampleCustomerInformationServiceReference.RegisterCustomerRequest();  
  13.         request.FirstName = firstName;  
  14.         request.LastName = lastName;  
  15.         request.Email = email;  
  16.         request.PhoneNumber = phoneNumber;  
  17.         request.Password = password;  
  18.   
  19.         var response = client.RegisterCustomer(request);  
  20.         return response.RegisterCustomerResponse;  
  21.     } catch (Exception ex)  
  22.     {  
  23.         throw new Exception(ex.Message);  
  24.     }  
  25.     return "";  
  26. }  
  27.   
  28. //This method is used to login a customer  
  29. //This method is passed as a url to the Ajax function LoginCustomer()  
  30. public string LoginCustomer(string userName, string loginPassword)  
  31. {  
  32.     try {  
  33.         SampleCustomerInformationServiceReference.LoginCustomerRequest request = new SampleCustomerInformationServiceReference.LoginCustomerRequest();  
  34.         request.UserName = userName;  
  35.         request.Password = loginPassword;  
  36.   
  37.         var response = client.LoginCustomer(request);  
  38.         return response.LoginCustomerResponse;  
  39.     } catch (Exception ex) {  
  40.         throw new Exception(ex.Message);  
  41.     }  
  42.     return "";  
  43. }