Click here to Skip to main content
15,881,757 members
Articles / Web Development / HTML

Realtime MVC Application using n-tier architecture

Rate me:
Please Sign up or sign in to vote.
2.85/5 (10 votes)
9 Jan 2016CPOL3 min read 43.5K   2.7K   23   5

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

  • Create a SampleCustomerInformation database using SQL Server
  • Create an empty MVC web application(Presentation Layer) using Visual Studio 2013
    • Creating controllers, views and respective HTML and javascript required
  • Adding another project to the solution for processing the data from SQL Server. Create a C# library project (Data Access Layer)
    • Add an entity data model to connect to the database.
    • Create classes to process all the requests from Business Service Layer
    • Write necessary methods to process the requests in business service layer
  • Add another project to the solution for writing business logic. Create a WCF Service Library
    • Add necessary service parameters to the project required to write business logic
    • 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
  • Add necessary references to the projects in the solution
  • Add a Service Reference to Presentation Layer
    • Use all the available methods from service layer and process the requests.

Technologies Used

  1. ASP.Net MVC5
  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

SQL
/****** Object:  Database [SampleCustomerInformation]******/
CREATE DATABASE [SampleCustomerInformation]

Create table CustomerInformation(
SNO int not null identity(0,1),
CustomerID int not null primary key,
[First Name] varchar(50) not null,
[Last Name] varchar(50) not null,
Email varchar(60) null,
Phone varchar(13) not null,
[User Name] varchar(60) not null,
[Password] varchar(12) not null)

Create table CustomerLoginActivity(
SNO int not null identity(0,1),
[User Name] int not null,
[Password] varchar(60) not null,
[Login Time] Date not null
)

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

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

More information about jQuery Ajax can be found here jQuery Ajax

HTML

HTML
<html>
<head>
    <title>Welcome</title>
    <script src="~/Scripts/jquery-2.1.4.min.js"></script>
    <script src="~/Scripts/HomeScript.js"></script>
</head>
<body>
    <form style="float:left">
        <h4>Sign Up</h4>
        <table>
            <tr>
                <td>First Name</td>
                <td><input type="text" name="firstName" id="firstName" placeholder="First Name" value="" required /></td>
            </tr>
            <tr>
                <td>Last Name</td>
                <td><input type="text" name="lastName" id="lastName" placeholder="Last Name" value="" required /></td>
            </tr>
            <tr>
                <td>Email</td>
                <td><input type="email" name="email" id="email" placeholder="Email" value="" required /></td>
            </tr>
            <tr>
                <td>Phone Number</td>
                <td><input type="text" name="phoneNumber" placeholder="Phone Number" id="phoneNumber" value="" /></td>
            </tr>
            <tr>
                <td>Password</td>
                <td><input type="password" name="password" placeholder="Password" id="password" value="" /></td>
            </tr>
            <tr>
                <td>Confirm Password</td>
                <td><input type="password" name="confirmPassword" placeholder="Confirm Password" id="confirmPassword" value="" /></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" name="btnRegister" id="btnRegister" value="Register" /></td>
            </tr>
        </table>
    </form>
    <div style="float:left">
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    </div>
    <form style="float:left">
        <h4>Login</h4>
        <table>
            <tr>
                <td>User Name</td>
                <td><input type="text" name="userName" placeholder="Email" id="userName" value="" /></td>
            </tr>
            <tr>
                <td>Password</td>
                <td><input type="password" name="loginPassword" placeholder="Password" id="loginPassword" value="" /></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" name="btnLogin" id="btnLogin" value="Login" /></td>
            </tr>
        </table>
    </form>
</body>
</html>

Javascript

JavaScript
$(document).ready(function () {
    $("#btnRegister").click(function () {
        RegisterCustomer();
    });

    $("#btnLogin").click(function () {
        LoginCustomer();
    });
});

function RegisterCustomer() {
    var firstName = $("#firstName").val();
    var lastName = $("#lastName").val();
    var email = $("#email").val();
    var phoneNumber = $("#phoneNumber").val();
    var password = $("#password").val();
    var confirmPassword = $("#confirmPassword");

//Attributes in "data" of ajax request should match the arguments defined in the method in controller
    $.ajax({
        method: "POST",
        url: "../Home/RegisterCustomer",
        data: {
            firstName: firstName,
            lastName: lastName,
            email: email,
            phoneNumber: phoneNumber,
            password: password
        }
    }).done(function (msg) {
        if (msg == "success")
            alert("Login Successful");
        else
            alert("Login Failed: " + msg);
    });
}

function LoginCustomer() {
    var userName = $("#userName").val();
    var loginPassword = $("#loginPassword").val();

    $.ajax({
        method: "GET",
        url: "../Home/LoginCustomer",
        data: {
            userName: userName,
            loginPassword: loginPassword
        }
    })
    .done(function (msg) {
        alert("Login Activity Saved");
    });
}

 

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
C#
public class RegisterCustomerDataAccessLayer
    {
        #region Register Customer
        public bool RegisterCustomer(string firstName, string lastName, string email, string phoneNumber, string password)
        {
            try
            {
                using (var dbContext = new SampleCustomerInformationEntities())
                {
                    CustomerInformation newCustomer = new CustomerInformation();
                    newCustomer.CustomerID = 2;
                    newCustomer.First_Name = firstName;
                    newCustomer.Last_Name = lastName;
                    newCustomer.Email = email;
                    newCustomer.Phone = phoneNumber;
                    newCustomer.Password = password;
                    newCustomer.User_Name = email;
                    dbContext.CustomerInformations.Add(newCustomer);
                    dbContext.SaveChanges();
                    return true;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        #endregion 
}

public class CustomerLoginDataAccessLayer
    {
        #region Customer Login
        public bool LoginCustomer(string userName, string loginPassword)
        {
            try
            {
                using (var dbContext = new SampleCustomerInformationEntities())
                {
                    CustomerInformation customer = new CustomerInformation();
                    customer = dbContext.CustomerInformations.FirstOrDefault(x => x.User_Name == userName && x.Password == loginPassword);
                    if (customer != null)
                        return true;
                    else
                        return false;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        #endregion
    }

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

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.

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

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
C#
 [ServiceContract]
   public interface IService1
   {
       [OperationContract]
       RegisterCustomerRequest RegisterCustomer(RegisterCustomerRequest request);

       [OperationContract]
       LoginCustomerRequest LoginCustomer(LoginCustomerRequest request);

       // TODO: Add your service operations here
   }



public class Service1 : IService1
   {
       #region IService1 Members

       #region Register Customer
       public RegisterCustomerRequest RegisterCustomer(RegisterCustomerRequest request)
       {
           try
           {
               var registerCustomerDal = new RegisterCustomerDataAccessLayer();
               var customer = registerCustomerDal.RegisterCustomer(request.FirstName, request.LastName, request.Email, request.PhoneNumber, request.Password);
               if (customer)
                   request.RegisterCustomerResponse = "Success";
               else
                   request.RegisterCustomerResponse = "Failure";
               return request;
           }
           catch (Exception ex)
           {
               throw new Exception(ex.Message);
           }
           throw new NotImplementedException();
       }
       #endregion

       #region Login Customer
       public LoginCustomerRequest LoginCustomer(LoginCustomerRequest request)
       {
           try
           {
               var customerLoginDal = new CustomerLoginDataAccessLayer();
               var validateLogin = customerLoginDal.LoginCustomer(request.UserName, request.Password);
               if (validateLogin)
                   request.LoginCustomerResponse = "Login Successful";
               else
                   request.LoginCustomerResponse = "Login Failed";
               return request;
           }
           catch (Exception ex)
           {
               throw new Exception(ex.Message);
           }
           throw new NotImplementedException();
       }
       #endregion
       #endregion
   }

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

C#
// GET: Home View
       public ActionResult Home()
       {
           return View();
       }

       //This method is used to register new customer
       //This method is passed as a url to the Ajax function RegisterCustomer()
       public string RegisterCustomer(string firstName, string lastName, string email, string phoneNumber, string password)
       {
           try
           {
               SampleCustomerInformationServiceReference.RegisterCustomerRequest request = new SampleCustomerInformationServiceReference.RegisterCustomerRequest();
               request.FirstName = firstName;
               request.LastName = lastName;
               request.Email = email;
               request.PhoneNumber = phoneNumber;
               request.Password = password;

               var response = client.RegisterCustomer(request);
               return response.RegisterCustomerResponse;
           }
           catch (Exception ex)
           {
               throw new Exception(ex.Message);
           }
           return "";
       }

       //This method is used to login a customer
       //This method is passed as a url to the Ajax function LoginCustomer()
       public string LoginCustomer(string userName, string loginPassword)
       {
           try
           {
               SampleCustomerInformationServiceReference.LoginCustomerRequest request = new SampleCustomerInformationServiceReference.LoginCustomerRequest();
               request.UserName = userName;
               request.Password = loginPassword;

               var response = client.LoginCustomer(request);
               return response.LoginCustomerResponse;
           }
           catch (Exception ex)
           {
               throw new Exception(ex.Message);
           }
           return "";
       }

For demo please download the project and run locally. 

License

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


Written By
Software Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionNot a Real Time project Pin
Sachin kc4-Mar-17 17:56
Sachin kc4-Mar-17 17:56 
GeneralMy vote of 1 Pin
lejuif12-Jan-16 0:59
lejuif12-Jan-16 0:59 
Question[My vote of 1] This is not "Real Time" Pin
Member 1041007611-Jan-16 11:13
Member 1041007611-Jan-16 11:13 
QuestionRealtime Pin
Júnior Pacheco10-Jan-16 13:53
professionalJúnior Pacheco10-Jan-16 13:53 
GeneralMy vote of 4 Pin
Ujjval Shukla9-Jan-16 20:55
Ujjval Shukla9-Jan-16 20:55 

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.