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.
a. 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).
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.
- 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.
- Add necessary references to the projects in the solution.
- Add a Service Reference to Presentation Layer.
a. Use all the available methods from service layer and process the requests.
Technologies Used
- ASP.NET MVC 5
- SQL Server 2014
- C# v5
- jQuery 2.14
- HTML5
- CSS3
IDE: Visual Studio 2013
Using the code
Module 1:
Creating a SampleCustomerInformation database using SQL Server,
- /****** Object: Database [SampleCustomerInformation]******/
- CREATE DATABASE[SampleCustomerInformation]
-
- Create table CustomerInformation
- (
- SNO int not null identity(0, 1),
- CustomerIDint 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>
-
- <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">
-
- </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
- $(document).ready(function()
- {
- $("#btnRegister").click(function()
- {
- RegisterCustomer();
- });
-
- $("#btnLogin").click(function()
- {
- LoginCustomer();
- });
- });
-
- functionRegisterCustomer()
- {
- var firstName = $("#firstName").val();
- var lastName = $("#lastName").val();
- var email = $("#email").val();
- var phoneNumber = $("#phoneNumber").val();
- var password = $("#password").val();
- varconfirmPassword = $("#confirmPassword");
-
-
- $.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);
- });
- }
-
- functionLoginCustomer()
- {
- 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.
- 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.
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.
- [ServiceContract]
- public interface IService1
- {
- [OperationContract]
- RegisterCustomerRequest RegisterCustomer(RegisterCustomerRequest request);
-
- [OperationContract]
- LoginCustomerRequest LoginCustomer(LoginCustomerRequest request);
-
-
- }
-
-
-
- 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,
-
- public ActionResult Home()
- {
- return View();
- }
-
-
-
- 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 "";
- }
-
-
-
- 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 "";
- }