How to Diagnostics in ASP.NET Core 1.0

In this post we will Using Diagnostics in ASP.NET MVC 6 (Core 1.0), we will see how to easily sort out coding issue in a sample application.

The ASP.NET Core 1.0 release (currently in RC1) provides several new features as well as improvements to existing features. One such very useful feature is Diagnostics. ASP.NET Core a.k.a ASP.NET 5 simplifies diagnostics. In this article, we will go through the Diagnostics feature and see how to implement it in an ASP.NET MVC 6 application.

Implementing Diagnostics in ASP.NET MVC 6

This application is implemented using Visual Studio 2015 and ASP.NET Core 1.0.

  • Step 1: Open Visual Studio 2015 and create a new ASP.NET Web Application from Add New Project Click on OK and select Empty from ASP.NET 5 Templates. Click on OK to create the project.
  • Step 2: In this project, open the json file and add the following dependencies in the dependencies section
"Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
"Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final",
"Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
"Microsoft.AspNet.Tooling.Razor": "1.0.0-rc1-final",
"Microsoft.Extensions.CodeGenerators.Mvc": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.FileProviderExtensions": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final"

This will add the necessary references in the project.

  • Step 3: In the project, add a Models folder and in this folder add ModelClasses.cs. Add the following code in this class file
using System.Collections.Generic;
namespace ASPNET_Core_Diagnistics.Models
{
 public class Employee
 {
 public int EmpNo { get; set; }
 public string EmpName { get; set; }
 }
 public class EmployeesDatabase : List<Employee>
 {
 public EmployeesDatabase()
 {
 Add(new Employee() { EmpNo = 1, EmpName = "A" });
 Add(new Employee() { EmpNo = 2, EmpName = "B" });
 Add(new Employee() { EmpNo = 3, EmpName = "C" });
 Add(new Employee() { EmpNo = 4, EmpName = "D" });
 Add(new Employee() { EmpNo = 5, EmpName = "E" });
 Add(new Employee() { EmpNo = 6, EmpName = "F" });
 }
 }
 public class DataAccess
 {
 public List<Employee> Get()
 {
 return new EmployeesDatabase();
 }
 }
}

The above code contains the entity class of name Employee and the EmployeesDatabase class contains some Employee records in it. The DataAccess class contains Get() method and returns EmployeesDatabase class instance.

  • Step 4: In this folder, add a new folder of name In the Services folder, add the class file of name Services. Add the following code in it
using ASPNET_Core_Diagnistics.Models;
using System.Collections.Generic;
 
namespace ASPNET_Core_Diagnistics.Services
{
 public interface IService<T> where T :class
 {
 IEnumerable<T> Get();
 }
 
 public class EmployeeService : IService<Employee>
 {
 DataAccess ds;
 public EmployeeService(DataAccess d)
 {
 ds = d;
 }
 public IEnumerable<Employee> Get()
 {
 return ds.Get();
 }
 }
}

The above code contains an interface of name IService<T> where T is the type. The EmployeeService implements IService interface. The constructor of EmployeeService is injected with the DataAccess object.

  • Step 5: In the same project, add a Controllers folder and in this folder add a MVC Controller Class using Add > New Item > MVC Controller class. By default, the name of the controller class is HomeController, rename it to EmployeeController.
  • Step 6: In the cs we need to define the required configuration. We will use the inbuilt dependency injection feature of ASP.NET Core 1.0. Add the following code in the ConfigureServices() method of the Startup.cs class
public void ConfigureServices(IServiceCollection services)
{
 services.AddMvc();
 services.AddSingleton<IService<Employee>, EmployeeService>();
}
Step 7: To use MVC we need to define routing for the application, add the following code in the Configure() method of the Startup class
public void Configure(IApplicationBuilder app)
{
 app.UseIISPlatformHandler();
 app.UseStaticFiles();
 app.UseMvc(routes =>
 {
 routes.MapRoute(
 name: "default",
 template: "{controller=Employee}/{action=Index}/{id?}");
 });
}
  • Step 8: Now add a new folder of name Views to the project. In this folder add a new sub-folder of name Employee. In the Views folder, add a new MVC View Imports Page and add the following code in it
@using ASPNET_Core_Diagnostics;
@using ASPNET_Core_Diagnostics.Models;
@addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"

This will be used to execute new asp- attribute in MVC Views.

Step 9: In the Employee subfolder of Views folder, add a new MVC View of name Index.cshtml and add the following markup code in it

@model IEnumerable<ASPNET_Core_Diagnostics.Models.Employee>
@{
 ViewData["Title"] = "Index";
}
 
<h2>Index</h2>
<table class="table">
 <tr>
 <th>
 @Html.DisplayNameFor(model => model.EmpNo)
 </th>
 <th>
 @Html.DisplayNameFor(model => model.EmpName)
 </th>
 <th></th>
 </tr>
 
 @foreach (var item in Model)
 {
 <tr>
 <td>
 @Html.DisplayFor(modelItem => item.EmpNo)
 </td>
 <td>
 @Html.DisplayFor(modelItem => item.EmpName)
 </td>
 </tr>
 }
  • Step 10: Running the application

Run the application, the following result will be displayed

localhost

This shows a generic Error 500, let us find out the exact error. We can do this by using Microsoft.AspNet.Diagnostics. Add this namespace in the Startup.cs. In the Configure() method add the following code (highlighted)

public void Configure(IApplicationBuilder app,IHostingEnvironment environment)
{
 app.UseIISPlatformHandler();
 if (string.Equals(environment.EnvironmentName, "Development", StringComparison.OrdinalIgnoreCase))
 {
 app.UseDeveloperExceptionPage(); 
 }
 app.UseStaticFiles();
 app.UseMvc(routes =>
 {
 routes.MapRoute(
 name: "default",
 template: "{controller=Employee}/{action=Index}/{id?}");
 });
 
}

The above code uses an if statement to check the EnvironmentName, this is used to verify the current mode in which the application is running. Currently we are using development mode. The UseDeveloperException() extension method is used to render the exception during the development mode.

Run the application and the following result will be displayed:

localhost1

This shows the stack trace error. In our scenario it shows the Object reference is not set to an instance of object. It shows that the foreach loop is not working. This is the problem of the Index() action method of the EmployeeController. Change the code as following

public class EmployeeController : Controller
{
 IService<Employee> _service;
 public EmployeeController(IService<Employee> srv)
 {
 _service = srv;
 }
 // GET: /<controller>/
 public IActionResult Index()
 {
 var Emps = _service.Get();
 return View(Emps);
 }
}

We are injecting the IService<Employee> in the EmployeeController constructor. The Index() action method is calling the Get() method of the IService.

Run the following application, the following result will be displayed

localhost2

 

The above error shows the Unable to resolve the DataAccess error. To resolve this, let’s verify the code of EmployeeService class. In the constructor, we are passing the dependency of DataAccess but we have not registered it in the ConfgureServices() method. Add the following code in the ConfgureServices() method.

public void ConfigureServices(IServiceCollection services)
{
 services.AddMvc();
 services.AddScoped(typeof(DataAccess));
 services.AddSingleton<IService<Employee>, EmployeeService>();
}

We have added the DataAccess as a dependency in the application.

Comments are closed.

Top