Building a .NET Web Application

Introduction

 
In my first two articles, we first looked at the four common types of .NET applications we may find out in the field. We briefly discussed these four types of applications and then in the second article, we looked at the design and architecture at a high level which would apply to all these applications in general terms. Next, we build the first type of application, the .NET desktop application. Today, we will look at the second and probably the most common type of application, the .NET web application.

Requirements for building this application

 
It is assumed the reader of this article has some basic knowledge and understanding of .NET development and C#, which is the programming language used for developing all the samples. In addition, the following tools would be required:
  1. SQL Server 2008 Express Edition
  2. SQL Server Management Studio
  3. Visual Studio 2019 Community Edition
All the above tools are free to download and use. We will be building the application using the .NET Core 3.1 and its related technologies. So, let’s begin. The advantage of using .NET Core over the .NET framework is that this solution can be deployed to Linux and Mac environments in addition to Windows.

The Data Source

 
The first step is to build the data source, where we would be saving the data. Here, I will create a new database called “EmployeeDB”. However, we will not be creating the Employee table, as this would be done using the Entity Framework Core and the Code First approach. This code would also be used to add the initial data, also known as seeding the database. This will all be done in the data access layer. So, let’s move directly to the data access layer.

The Data Access Layer

 
The data access layer would be created as a Web API application. A Web API application is an application that exposes functionality over an HTTP protocol via calls made to it and returns data, most commonly in the JSON format. This data can then be used in the application as required.
 
We start by creating a new ASP.NET Core Web application of type “API”. Also, remember to uncheck the “Configure for HTTPS” option and ensure “No Authentication” is selected for the Authentication. We will discuss authentication in some future articles.
 
Building The .NET Web Application 
 
Here, we have created a solution by the name of “EmployeeWeb” and a project by the name of “EmployeeDALWebApi”.
 
Now, we start to create the pieces of the data access layer. The first thing we need to create is the employee model class. This will be the model which will then be created in the database. Here, we create a new folder called “DataAccessLayer” and inside it another folder called “Models”. Inside this folder, we create a new class called “Employee” with the below code:
 
Building The .NET Web Application
  1. using System;  
  2. using System.ComponentModel.DataAnnotations;  
  3. using System.ComponentModel.DataAnnotations.Schema;  
  4. namespace EmployeeDALWebApi.DataAccessLayer.Models {  
  5.     public class Employee {  
  6.         [Key]  
  7.         [DatabaseGenerated(DatabaseGeneratedOption.Identity)]  
  8.         public int Employee_ID {  
  9.             get;  
  10.             set;  
  11.         }  
  12.         [Required]  
  13.         [Column(TypeName = "nvarchar(50)")]  
  14.         public string First_Name {  
  15.             get;  
  16.             set;  
  17.         }  
  18.         [Required]  
  19.         [Column(TypeName = "nvarchar(50)")]  
  20.         public string Last_Name {  
  21.             get;  
  22.             set;  
  23.         }  
  24.         [Required]  
  25.         [Column(TypeName = "smalldatetime")]  
  26.         public DateTime Date_Birth {  
  27.             get;  
  28.             set;  
  29.         }  
  30.         [Column(TypeName = "nvarchar(100)")]  
  31.         public string Street_Address {  
  32.             get;  
  33.             set;  
  34.         }  
  35.         [Required]  
  36.         [Column(TypeName = "nvarchar(50)")]  
  37.         public string City {  
  38.             get;  
  39.             set;  
  40.         }  
  41.         [Required]  
  42.         [Column(TypeName = "char(2)")]  
  43.         public string Province {  
  44.             get;  
  45.             set;  
  46.         }  
  47.         [Required]  
  48.         [Column(TypeName = "smalldatetime")]  
  49.         public DateTime Date_Joining {  
  50.             get;  
  51.             set;  
  52.         }  
  53.         [Column(TypeName = "smalldatetime")]  
  54.         public DateTime ? Date_Leaving {  
  55.             get;  
  56.             set;  
  57.         }  
  58.     }  
Please note that the following NuGet packages are required for the solution: 
Building The .NET Web Application
 
As we will be using the Entity Framework Core technology, we need to create the Context class which is used to communicate with the underlying data store. Hence, we will next create a class called “EmployeeContext” in the “DataAccessLayer” folder. 
  1. using Microsoft.EntityFrameworkCore;  
  2. using EmployeeDALWebApi.DataAccessLayer.Models;  
  3. using System;  
  4. namespace EmployeeDALWebApi.DataAccessLayer {  
  5.     public class EmployeeContext: DbContext {  
  6.         public EmployeeContext(DbContextOptions options): base(options) {}  
  7.         public DbSet < Employee > Employees {  
  8.             get;  
  9.             set;  
  10.         }  
  11.     }  
  12. }  
Now before we can create the table in the database using the Code First approach, we need to specify the database connection. This is done in the appsettings.json file, as shown below:
  1. {  
  2.     "Logging": {  
  3.         "LogLevel": {  
  4.             "Default""Information",  
  5.             "Microsoft""Warning",  
  6.             "Microsoft.Hosting.Lifetime""Information"  
  7.         }  
  8.     },  
  9.     "ConnectionString": {  
  10.         "EmployeeCS""Data Source=localhost\\SQLEXPRESS;Initial Catalog=EmployeeDB;Integrated Security=True"  
  11.     },  
  12.     "AllowedHosts""*"  
  13. }  
Also, remember to update the “Startup.cs” file as mentioned later in this article section. We can run the below commands and create the table in the EmployeeDB database:
 
Building The .NET Web Application
 
After this, we will see that a Migrations folder is created that has classes related to migration and a rollback for this migration as well.
 
Building The .NET Web Application
 
Next, we will add the code to create the initial data also known as seeding the database. See the below changes to the EmployeeContext class:
  1. using Microsoft.EntityFrameworkCore;  
  2. using EmployeeDALWebApi.DataAccessLayer.Models;  
  3. using System;  
  4. namespace EmployeeDALWebApi.DataAccessLayer {  
  5.     public class EmployeeContext: DbContext {  
  6.         public EmployeeContext(DbContextOptions options): base(options) {}  
  7.         public DbSet < Employee > Employees {  
  8.             get;  
  9.             set;  
  10.         }  
  11.         protected override void OnModelCreating(ModelBuilder modelBuilder) {  
  12.             modelBuilder.Entity < Employee > ().HasData(new Employee {  
  13.                 Employee_ID = 1,  
  14.                     First_Name = "John",  
  15.                     Last_Name = "Doe",  
  16.                     Date_Birth = new DateTime(1980, 10, 01),  
  17.                     Street_Address = "100 Street West",  
  18.                     City = "Toronto",  
  19.                     Province = "ON",  
  20.                     Date_Joining = new DateTime(2020, 01, 15)  
  21.             });;  
  22.         }  
  23.     }  
  24. }  
Next, we do another migration called “SeedEmployeesTable”. Now, we have a table created with an initial record, as shown below:
 
Building The .NET Web Application
 
The next step will be to create a repository pattern to access the context to maintain and view the data. This will be done by creating the below classes in a new folder called “Repositories”. Please note that here we will have only one repository as we only have one table:
  1. using System.Collections.Generic;  
  2. namespace EmployeeDALWebApi.Repositories {  
  3.     public interface IDataRepository < TEntity > {  
  4.         IEnumerable < TEntity > GetAll();  
  5.         TEntity Get(long id);  
  6.         void Add(TEntity entity);  
  7.         void Update(TEntity dbEntity, TEntity entity);  
  8.         void Delete(TEntity entity);  
  9.     }  
  1. using System.Collections.Generic;  
  2. using System.Linq;  
  3. using EmployeeDALWebApi.DataAccessLayer.Models;  
  4. using EmployeeDALWebApi.DataAccessLayer;  
  5. using System;  
  6. namespace EmployeeDALWebApi.Repositories {  
  7.     public class EmployeeRepository: IDataRepository < Employee > {  
  8.         readonly EmployeeContext _employeeContext;  
  9.         public EmployeeRepository(EmployeeContext context) {  
  10.             _employeeContext = context;  
  11.         }  
  12.         public IEnumerable < Employee > GetAll() {  
  13.             return _employeeContext.Employees.ToList();  
  14.         }  
  15.         public Employee Get(long id) {  
  16.             throw new NotImplementedException();  
  17.         }  
  18.         public void Add(Employee entity) {  
  19.             throw new NotImplementedException();  
  20.         }  
  21.         public void Update(Employee employee, Employee entity) {  
  22.             throw new NotImplementedException();  
  23.         }  
  24.         public void Delete(Employee employee) {  
  25.             throw new NotImplementedException();  
  26.         }  
  27.     }  
  28. }  
The final step in the data access layer will be to create a controller class and add actions to it. This is done by creating a new controller class under the “Controllers” folder as shown below:
  1. using System.Collections.Generic;  
  2. using Microsoft.AspNetCore.Mvc;  
  3. using EmployeeDALWebApi.Repositories;  
  4. using EmployeeDALWebApi.DataAccessLayer.Models;  
  5. namespace EmployeeDALWebApi.Controllers {  
  6.     [Route("api/employee")]  
  7.     [ApiController]  
  8.     public class EmployeeController: ControllerBase {  
  9.         private readonly IDataRepository < Employee > _employeeRepository;  
  10.         public EmployeeController(IDataRepository < Employee > employeeRepository) {  
  11.                 _employeeRepository = employeeRepository;  
  12.             }  
  13.             [HttpGet]  
  14.         public IActionResult Get() {  
  15.             IEnumerable < Employee > employees = _employeeRepository.GetAll();  
  16.             return Ok(employees);  
  17.         }  
  18.     }  
  19.  
As you might have noticed, we are using the dependency injection of .NET Core to pass the “EmployeeContext” to the employee repository and to pass the “EmployeeRepository” to the employee controller. Hence, these need to be configured in the “Startup.cs” file, as shown below:
  1. using Microsoft.AspNetCore.Builder;  
  2. using Microsoft.AspNetCore.Hosting;  
  3. using Microsoft.Extensions.Configuration;  
  4. using Microsoft.Extensions.DependencyInjection;  
  5. using Microsoft.Extensions.Hosting;  
  6. using EmployeeDALWebApi.DataAccessLayer;  
  7. using Microsoft.EntityFrameworkCore;  
  8. using EmployeeDALWebApi.Repositories;  
  9. using EmployeeDALWebApi.DataAccessLayer.Models;  
  10. namespace EmployeeDALWebApi {  
  11.     public class Startup {  
  12.         public Startup(IConfiguration configuration) {  
  13.             Configuration = configuration;  
  14.         }  
  15.         public IConfiguration Configuration {  
  16.             get;  
  17.         }  
  18.         // This method gets called by the runtime. Use this method to add services to the container.  
  19.         public void ConfigureServices(IServiceCollection services) {  
  20.             services.AddDbContext < EmployeeContext > (opts => opts.UseSqlServer(Configuration["ConnectionString:EmployeeCS"]));  
  21.             services.AddScoped < IDataRepository < Employee > , EmployeeRepository > ();  
  22.             services.AddControllers();  
  23.         }  
  24.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  25.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {  
  26.             if (env.IsDevelopment()) {  
  27.                 app.UseDeveloperExceptionPage();  
  28.             }  
  29.             app.UseRouting();  
  30.             app.UseAuthorization();  
  31.             app.UseEndpoints(endpoints => {  
  32.                 endpoints.MapControllers();  
  33.             });  
  34.         }  
  35.     }  
  36. }  
Please note that the “AddDbContext” must be done before the migrations can be run to create the employee table and add the initial data.
 
Now that the data access layer is complete, we can run the solution and browse to “api/employee”. We will see the below screenshot in our browser:
 
Building The .NET Web Application
Next, we move to the business logic layer.

The Business Logic Layer

 
This layer will be the one to make the call to the data access layer and get data from it. Next, it will transform it as required and then forward it to the front end or presentation layer. It is in this layer that any business logic is written. However, for this application, we only need to do some simple tasks, like calculate the age of the employee from the date of birth, etc.
 
We create a new Class Library project for .NET Core called “EmployeeBAL” and create the following inside it:
  1. using System;  
  2. namespace EmployeeBAL {  
  3.     public class EmployeeUI {  
  4.         public int Employee_ID {  
  5.             get;  
  6.             set;  
  7.         }  
  8.         public string Employee_Name {  
  9.             get;  
  10.             set;  
  11.         }  
  12.         public int Age {  
  13.             get;  
  14.             set;  
  15.         }  
  16.         public string Address {  
  17.             get;  
  18.             set;  
  19.         }  
  20.         public DateTime Date_Joining {  
  21.             get;  
  22.             set;  
  23.         }  
  24.         public DateTime ? Date_Leaving {  
  25.             get;  
  26.             set;  
  27.         }  
  28.     }  
  29. }  
  1. using System.Collections.Generic;  
  2. using System.Threading.Tasks;  
  3. namespace EmployeeBAL {  
  4.     public interface IEmployeeBAL {  
  5.         Task < List < EmployeeUI >> GetAllEmployees();  
  6.     }  
  7.  
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net.Http;  
  5. using System.Threading.Tasks;  
  6. using Newtonsoft.Json;  
  7. namespace EmployeeBAL {  
  8.     public class EmployeeBAL: IEmployeeBAL {  
  9.         public async Task < List < EmployeeUI >> GetAllEmployees() {  
  10.             using(var client = new HttpClient()) {  
  11.                 client.BaseAddress = new Uri("http://localhost:54611/api/");  
  12.                 var result = await client.GetAsync("employee");  
  13.                 var response = await result.Content.ReadAsStringAsync();  
  14.                 var data = JsonConvert.DeserializeObject < List < EmployeeStore >> (response);  
  15.                 var employeesUI = data.Select(e => new EmployeeUI {  
  16.                     Employee_ID = e.Employee_ID,  
  17.                         Employee_Name = e.First_Name + " " + e.Last_Name,  
  18.                         Age = GetAge(e.Date_Birth),  
  19.                         Address = e.Street_Address + ", " + e.City + ", " + e.Province,  
  20.                         Date_Joining = e.Date_Joining,  
  21.                         Date_Leaving = e.Date_Leaving  
  22.                 }).ToList();  
  23.                 return employeesUI;  
  24.             }  
  25.         }  
  26.         private int GetAge(DateTime Birth_Date) {  
  27.             return Convert.ToInt32(((DateTime.Now - Birth_Date).TotalDays) / 365);  
  28.         }  
  29.         public class EmployeeStore {  
  30.             public int Employee_ID;  
  31.             public string First_Name;  
  32.             public string Last_Name;  
  33.             public DateTime Date_Birth;  
  34.             public string Street_Address;  
  35.             public string City;  
  36.             public string Province;  
  37.             public DateTime Date_Joining;  
  38.             public DateTime ? Date_Leaving;  
  39.         }  
  40.     }  
  41. }  
You might wonder why we created a class “EmployeeStore” here. This is to store the data we receive from the data access layer without keeping any direct connection between it and the business access layer. Please remember to change the base address according to the address of your data access layer Web API.
 

The Front End or Presentation Layer

 
We now create the front end or presentation layer. Here, we will create an MVC Core application, as shown below:
 
Building The .NET Web Application
 
Building The .NET Web Application
 
Building The .NET Web Application
Here, we will not create a new controller or view. Instead, we will modify the Home Controller, as shown below:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Diagnostics;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6. using Microsoft.AspNetCore.Mvc;  
  7. using Microsoft.Extensions.Logging;  
  8. using EmployeeWebApp.Models;  
  9. using EmployeeBAL;  
  10. namespace EmployeeWebApp.Controllers {  
  11.     public class HomeController: Controller {  
  12.         private readonly ILogger < HomeController > _logger;  
  13.         private readonly IEmployeeBAL _employeeBAL;  
  14.         public HomeController(ILogger < HomeController > logger, IEmployeeBAL employeeBAL) {  
  15.             _logger = logger;  
  16.             _employeeBAL = employeeBAL;  
  17.         }  
  18.         public async Task < IActionResult > Index() {  
  19.             var employees = await _employeeBAL.GetAllEmployees();  
  20.             var employee = employees.FirstOrDefault();  
  21.             return View(employee);  
  22.         }  
  23.         public IActionResult Privacy() {  
  24.                 return View();  
  25.             }  
  26.             [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]  
  27.         public IActionResult Error() {  
  28.             return View(new ErrorViewModel {  
  29.                 RequestId = Activity.Current?.Id ? ? HttpContext.TraceIdentifier  
  30.             });  
  31.         }  
  32.     }  
  33.  
Add the following changes in the “Views/Home/Index.cshtml” file, as shown below:
  1. @model EmployeeBAL.EmployeeUI  
  2.   
  3. @{  
  4. ViewData["Title"] = "Home Page";  
  5. }  
  6.   
  7. <div class="text-center">  
  8.     <h1 class="display-4">Employee Details</h1>  
  9.     <div class="form-group">  
  10.         <hr />  
  11.         <dl class="row">  
  12.             <dt class="col-sm-2">  
  13.                 <label asp-for="Employee_ID" class="col-md-2 control-label"></label>  
  14.             </dt>  
  15.             <dd class="col-sm-10">  
  16. @Html.DisplayFor(model => model.Employee_ID)  
  17. </dd>  
  18.             <dt class="col-sm-2">  
  19.                 <label asp-for="Employee_Name" class="col-md-2 control-label"></label>  
  20.             </dt>  
  21.             <dd class="col-sm-10">  
  22. @Html.DisplayFor(model => model.Employee_Name)  
  23. </dd>  
  24.             <dt class="col-sm-2">  
  25.                 <label asp-for="Address" class="col-md-2 control-label"></label>  
  26.             </dt>  
  27.             <dd class="col-sm-10">  
  28. @Html.DisplayFor(model => model.Address)  
  29. </dd>  
  30.             <dt class="col-sm-2">  
  31.                 <label asp-for="Age" class="col-md-2 control-label"></label>  
  32.             </dt>  
  33.             <dd class="col-sm-10">  
  34. @Html.DisplayFor(model => model.Age)  
  35. </dd>  
  36.             <dt class="col-sm-2">  
  37.                 <label asp-for="Date_Joining" class="col-md-2 control-label"></label>  
  38.             </dt>  
  39.             <dd class="col-sm-10">  
  40. @Html.DisplayFor(model => model.Date_Joining)  
  41. </dd>  
  42.             <dt class="col-sm-2">  
  43.                 <label asp-for="Date_Leaving" class="col-md-2 control-label"></label>  
  44.             </dt>  
  45.             <dd class="col-sm-10">  
  46. @Html.DisplayFor(model => model.Date_Leaving)  
  47. </dd>  
  48.         </dl>  
  49.     </div>  
  50. </div>   
As we are using dependency injection to pass the “EmployeeBAL” class into the controller, we need to specify this in the “Startup.cs” file:
  1. using Microsoft.AspNetCore.Builder;  
  2. using Microsoft.AspNetCore.Hosting;  
  3. using Microsoft.Extensions.Configuration;  
  4. using Microsoft.Extensions.DependencyInjection;  
  5. using Microsoft.Extensions.Hosting;  
  6. namespace EmployeeWebApp {  
  7.     public class Startup {  
  8.         public Startup(IConfiguration configuration) {  
  9.             Configuration = configuration;  
  10.         }  
  11.         public IConfiguration Configuration {  
  12.             get;  
  13.         }  
  14.         // This method gets called by the runtime. Use this method to add services to the container.  
  15.         public void ConfigureServices(IServiceCollection services) {  
  16.             services.AddScoped < EmployeeBAL.IEmployeeBAL, EmployeeBAL.EmployeeBAL > ();  
  17.             services.AddControllersWithViews();  
  18.         }  
  19.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  20.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {  
  21.             if (env.IsDevelopment()) {  
  22.                 app.UseDeveloperExceptionPage();  
  23.             } else {  
  24.                 app.UseExceptionHandler("/Home/Error");  
  25.             }  
  26.             app.UseStaticFiles();  
  27.             app.UseRouting();  
  28.             app.UseAuthorization();  
  29.             app.UseEndpoints(endpoints => {  
  30.                 endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");  
  31.             });  
  32.         }  
  33.     }  
  34. }  
Before we run the application, ensure that we set the solution to run multiple projects, as we need to start the Web API and MVC Core application at the same time, shown below:
 
Building The .NET Web Application
 
We now run the application and should see the web application display the employee data as below in the browser:
 
Building The .NET Web Application
The complete solution should look like the below screenshot:
 
Building The .NET Web Application
 

Summary

 
We have just covered a simple .NET web application, where we went through the different layers to store the data, read the data, convert data to our requirements and then present it to the end-user. This was all done using the latest .NET Core MVC, Web API and Entity Framework Core technologies. We also used dependency injection, middleware or the request pipeline and tag helpers in the razor view of the MVC Core application. In the next article, we will look to move this application to the cloud in a Microsoft Azure environment.