Introduction to Dapper.NET ORM in ASP.NET 5

Standard

Dapper.NET is an open source, high performance Micro-ORM supporting Sql Server, MySQL, Sqlite, SqlCE, Firebird etc, from Stack Overflow team. Drapper provides extension methods for IDbConnection, so you require an instance of IDbConnection to use Dapper. To use Dapper, you need to include Dapper in the project.json file. In this post I am using Repository pattern and injecting the repository to the controller via constructor injection.

Here is the project.json file, the EntityFramework.SqlServer reference is required to use IDbConnection interface.

{
  "dependencies": {
    "Microsoft.AspNet.Diagnostics": "1.0.0-beta2",
    "Microsoft.AspNet.Hosting": "1.0.0-beta2",
    "Microsoft.AspNet.Mvc": "6.0.0-beta2",
    "Microsoft.AspNet.Server.WebListener": "1.0.0-beta2",
    "EntityFramework.SqlServer": "7.0.0-beta2",
    "Microsoft.AspNet.StaticFiles": "1.0.0-beta2",
     "Dapper":"1.38.0-*"
  },
  "commands": {
    "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5010",
  },
  "frameworks": {
    "aspnet50": {}
  }
}

Here is the constructor of the respository class. In this I am creating the instance of SqlConnection.

private IDbConnection _connection;
public EmployeeRepository()
{
	_connection = new SqlConnection("Server=.\\SQLEXPRESS; Database=DemoDb; Integrated Security=SSPI");
	_connection.Open();
}

Dapper extends the IDbConnection with Query method, which you can use to execute a query and map the result to a strongly typed object or list of objects.

public Employee Get(int? id)
{
	return _connection.Query<Employee>("SELECT * FROM Employees WHERE Id = @Id", new{ Id = id }).FirstOrDefault();
}

public IEnumerable<Employee> FindAll()
{
	return _connection.Query<Employee>("SELECT * FROM Employees");
}

You can use Execute method to execute DML queries as well to the Database.

public void Save(Employee employee)
{
	_connection.Execute("INSERT INTO Employees(Name,Designation,JoiningDate,Remarks) VALUES(@Name,@Designation,@JoiningDate,@Remarks)", employee);
}

public void Delete(Employee employee)
{
	_connection.Execute("DELETE FROM Employees WHERE Id=@Id", employee);
}

Dapper also supports Stored Procedures as well. You need to provide the command type parameter.

public void Update(Employee employee)
{
	_connection.Query("usp_UpdateEmployee", employee, commandType: CommandType.StoredProcedure);
}

You can use Dapper in ASP.NET or any .net applications, for that you need to include the Dapper nuget reference. You can find more details about Dapper from Dapper wiki

Happy Programming :)

Creating Unit Tests for ASP.NET MVC 6 Applications

Standard

This post is about unit testing ASP.NET MVC 6 applications. Unlike MS Test, this post is using XUnit Framework, which is the currently used unit testing framework for ASP.NET 5 applications.

Similar to TestMethod, XUnit uses Fact / Theory attributes. You can find more comparison details here.

Unit testing class libraries

Here is the unit tests for calculator class, with Add method.

public class CalculatorTests
{
	[Fact]
	public void AddTest()
	{
		var number1 = 10;
		var number2 = 20;
		var expected = 30;

		Calculator calculator = new Calculator();
		var result = calculator.Add(number1, number2);

		Assert.Equal(expected, result);
	}
	
	[Theory]
	[InlineData(10, 10,20)]
	[InlineData(20, 20,40)]
	public void AddTest(int number1, int number2, int expected)
	{
		Calculator calculator = new Calculator();
		var result = calculator.Add(number1, number2);
		
		Assert.Equal(expected, result);
	}
}

And here is source code

public class Calculator
{
	public int Add(int number1, int number2)
	{
		return number1 + number2;
	}
}

Similar to ASP.NET 5 applications, unit test project also requires a project.json file.

{
    "dependencies": {
        "xunit.runner.kre": "1.0.0-*"
    },
    "frameworks": {
        "aspnet50": { },
        "aspnetcore50": { }
    },
    "commands": {
        "test": "xunit.runner.kre"
    }
}

You need to execute the kpm restore command to download the XUnit runner, once it is finished, you can execute k test command to execute the tests. XUnit test runner will display result like this.

XUnit Test Results

XUnit Test Results

If you looked into the XUnit test results you can see something like Total :3, it because of the Theory and InlineData attributes, XUnit will treat the test method as a different one.

Unit testing MVC Controllers

Unlike class libraries, MVC controllers are little difficult to unit test. As controllers contains business logic and database interactions, you need to decouple it and inject it. This project is an ASP.NET MVC 6 project, code is generated using ASP.NET Scaffolding, it uses Entity Framework 7.0 and SQL Server localDb for database operations. In solution I wrote code to decouple the database interaction using repository pattern.

Here is the controller class.

public class EmployeeController : Controller
{
	private IEmployeeRepository _employeeRepository;
	public EmployeeController(IEmployeeRepository employeeRepository)
	{
		_employeeRepository = employeeRepository;
	}
}

I am using ASP.NET dependency injection framework for injecting the repository class to the controller. You can find more details about ASP.NET dependency injection here

public void Configure(IApplicationBuilder app)
{
    app.UseErrorPage();
    app.UseServices(services =>
    {
        services.AddMvc();
        services.AddScoped<IEmployeeRepository, EmployeeRepository>();
    });
 
    app.UseMvc();
}

And here is my index method, which returns employees from the database using repository.

// GET: Employee
public IActionResult Index()
{
	return View(_employeeRepository.FindAll().ToList());
}

And here is the unit test for the same. I am using Moq framework for mocking the

[Fact]
public void VerifyIndexDisplaysAllEmployees()
{
	_employeeRepository.Setup(x => x.FindAll()).Returns(new List<Employee>()
	{
		new Employee() { Id = 1, Name = "Employee 1" },
		new Employee() { Id = 2, Name = "Employee 2" },
		new Employee() { Id = 3, Name = "Employee 3" }
	});

	var indexResult = _employeeController.Index() as ViewResult;

	Assert.NotNull(indexResult);
	var employees = indexResult.ViewData.Model as List<Employee>;
	Assert.Equal(3, employees.Count);
	Assert.Equal(1, employees[0].Id);
	Assert.Equal("Employee 3", employees[2].Name);
}

As XUnit doesn’t have equivalents for Test Initialize / Class Initialize / Setup / Teardown, I have wrote the code to setup the controller and mocks in the test class constructor.

private EmployeeController _employeeController;
private Mock<IEmployeeRepository> _employeeRepository;
public EmployeeControllerTests()
{
	_employeeRepository = new Mock<IEmployeeRepository>();
	_employeeController = new EmployeeController(_employeeRepository.Object);
	var mockModelMetadataProvider = new Mock<IModelMetadataProvider>();
	var viewDataDictionary = new ViewDataDictionary<object>(mockModelMetadataProvider.Object);
	_employeeController.ViewData = viewDataDictionary;
}

As part of Index action, we are returning model object(Employee list), if we didn’t set ViewData property, tests will fail, with Null reference exception. This is because the controller class internally uses the ViewData property to return the Model to the view, while running controller from Unit test context, ASP.NET runtime won’t inject the required services to the view data property, so you need to set it manually.

Here is the Details action.

// GET: Employee/Details/5
public IActionResult Details(System.Int32? id)
{
	if (id == null)
	{
		return new HttpStatusCodeResult(404);
	}

	Employee employee = _employeeRepository.Get(id);
	if (employee == null)
	{
		return new HttpStatusCodeResult(404);
	}

	return View(employee);
}

And here is the unit tests for the same.

[Fact]
public void VerifyDetailsReturns404IfEmployeeIdIsNull()
{
	_employeeRepository
		.Setup(x => x.Get(It.IsAny<int?>())).Returns<Employee>(null);

	var httpStatusCodeResult 
		= _employeeController.Details(null) as HttpStatusCodeResult;

	Assert.NotNull(httpStatusCodeResult);
	Assert.Equal(404, httpStatusCodeResult.StatusCode);
}

[Fact]
public void VerifyDetailsReturns404IfEmployeeNotFound()
{
	_employeeRepository
		.Setup(x => x.Get(It.IsAny<int?>())).Returns<Employee>(null);

	var httpStatusCodeResult 
		= _employeeController.Details(1) as HttpStatusCodeResult;

	Assert.NotNull(httpStatusCodeResult);
	Assert.Equal(404, httpStatusCodeResult.StatusCode);
}

[Fact]
public void VerifyDetailsReturnsEmployee()
{
	_employeeRepository.Setup(x => x.Get(It.IsAny<int?>())).
		Returns((int id) => new Employee() { Id = id, Name = "Employee " + id });

	var viewResult = _employeeController.Details(1) as ViewResult;

	Assert.NotNull(viewResult);
	var employee = viewResult.ViewData.Model as Employee;
	Assert.NotNull(employee);
	Assert.Equal(1, employee.Id);
}

Most of the above tests are pretty straight forward, you can understand pretty easily. Here is the create action method.

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Employee employee)
{
	if (ModelState.IsValid)
	{
		_employeeRepository.Save(employee);
		return RedirectToAction("Index");
	}

	return View("Create", employee);
}

And unit tests for the Create method. One problem with the create method is that, it is using ModelState property of controller class to validate the model. As the model class is using Data Annotations API for validating the model, it is very difficult to mock. So we need to use the actual property to mock validation errors.

[Fact]
public void VerifyCreateEmployeeRedirectsToError()
{
	_employeeRepository.Setup(x => x.Save(It.IsAny<Employee>()));
	var employee = new Employee() { Id = 1 };
	//Mocking the _employeeController.ModelState.IsValid = false
	_employeeController.ModelState.AddModelError("Error", "Name is Required");

	var createResult = _employeeController.Create(employee) as ViewResult;

	Assert.NotNull(createResult);
	Assert.Equal("Create", createResult.ViewName);
}

[Fact]
public void VerifyCreateEmployeeInsertData()
{
	_employeeRepository.Setup(x => x.Save(It.IsAny<Employee>())).Verifiable();
	var employee = new Employee() { 
		Id = 1, 
		Name = "Employee", 
		Designation = "Designation", 
		JoiningDate = DateTime.Now };

	var createResult = _employeeController.Create(employee) as RedirectToActionResult;
	Assert.NotNull(createResult);
	Assert.Equal("Index", createResult.ActionName);
	_employeeRepository.Verify();
}

This code

_employeeController.ModelState.AddModelError("Error", "Name is Required");

is used to mock the model validation error. XUnit running on the tests

XUnit MVC Test Results

XUnit MVC Test Results

.

Here is my model class.

public class Employee
{
	public int Id { get; set; }
	[Required]
	public string Name { get; set; }
	[Required]
	public string Designation { get; set; }
	[Required]
	public DateTime JoiningDate { get; set; }
	public string Remarks { get; set; }
}

Repository interface

public interface IEmployeeRepository
{
	Employee Get(int? id);
	void Save(Employee employee);
	void Delete(Employee employee);
	void Update(Employee employee);
	IEnumerable<Employee> FindAll();
}

And the project.json file.

{
  "dependencies": {
    "Kestrel": "1.0.0-beta1",
    "Microsoft.AspNet.Diagnostics": "1.0.0-beta1",
    "Microsoft.AspNet.Hosting": "1.0.0-beta1",
    "Microsoft.AspNet.Mvc": "6.0.0-beta1",
    "Microsoft.AspNet.Server.WebListener": "1.0.0-beta1",
    "Microsoft.Framework.CodeGenerators.Mvc": "1.0.0-*",
    "EntityFramework.SqlServer": "7.0.0-*",
    "Microsoft.AspNet.StaticFiles": "1.0.0-*",
	"xunit.runner.kre": "1.0.0-*",
	"Moq":"1.0.0-*"
  },
  "commands": {
    "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5001",
    "gen": "Microsoft.Framework.CodeGeneration",
	"test": "xunit.runner.kre"
  },
  "frameworks": {
    "aspnet50": {}
  }
}

You can find the source code here

Happy Unit Testing :)

How to use SQLite in ASP.NET 5

Standard

SQLite is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. SQLite is the most widely deployed SQL database engine in the world. Most of the ASP.NET 5 tutorials / articles, SQL Server is used. In this post I am explaining about how to use SQLite with Entity Framework 7.0.

First you need to modify the project.json file, and need to add SQLite and Entity Framework dependencies. (“EntityFramework.SQLite”: “7.0.0-*”),the project.json, dependencies section will look like this.

{
    "dependencies": {
        "Microsoft.AspNet.Diagnostics": "1.0.0-beta1",
        "Microsoft.AspNet.Hosting": "1.0.0-beta1",
        "Microsoft.AspNet.Mvc": "6.0.0-beta1",
        "Microsoft.AspNet.Server.WebListener": "1.0.0-beta1",
	"Microsoft.AspNet.Identity.EntityFramework": "3.0.0-*",
	"EntityFramework.SQLite": "7.0.0-*"
    }
} 

Now you need to create DbContext class. If you are using SQL Server, you can generate it using scaffolding(For SQLite, it did worked for me.) Here is minimal DbContext class and the model class I have created.

using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;

public class Message
{
	public Guid Id { get; set; }
	public string Content { get; set; }
	public DateTime CreatedOn { get; set; }
	public string CreatedBy { get; set; }
}

public class HelloWorldContext : DbContext
{
	public DbSet<Message> Messages { get; set; }
	protected override void OnConfiguring(DbContextOptions builder)
	{
		builder.UseSQLite("Filename=messagedb.sqlite;");
	}

	protected override void OnModelCreating(ModelBuilder builder)
	{
		builder.Entity<Message>().Key(m => m.Id);
		base.OnModelCreating(builder);
	}
}

As you are using EF code first (creating the DB on the fly), you need to add the following code in the constructor of the Startup.cs, which will ensure SQLite Db is created, it is similar to Database Initializer classes in Entity Framework.

using(var context = new HelloWorldContext())
{
	context.Database.EnsureCreated();
}

This method won’t throw exception even if DB exists. Now you can write simple EF insert statement to insert data to the Table.

var helloWorldContext = new HelloWorldContext();
helloWorldContext.Messages.Add(new Message() {
	Id = Guid.NewGuid(),
	Content = "Hello World",
	CreatedOn = DateTime.Now,
	CreatedBy = "Anuraj" });
helloWorldContext.SaveChanges();

In the next post I will try explain how to scaffold controllers and views in ASP.NET 5 with SQLite.

Happy Programming :)

Dependency Injection in ASP.NET 5

Standard

Dependency injection is a software design pattern that implements inversion of control and allows a program design to follow the dependency inversion principle. An injection is the passing of a dependency (a service) to a dependent object (a client). The service is made part of the client’s state. Passing the service to the client, rather than allowing a client to build or find the service, is the fundamental requirement of the pattern. The pattern is used to create program designs that are loosely coupled and testable.

Types of Dependency Injection

  • Constructor injection: the dependencies are provided through a class constructor. – ASP.NET 5 supports only this.
  • Setter injection: the client exposes a setter method that the injector uses to inject the dependency.
  • Interface injection: the dependency provides an injector method that will inject the dependency into any client passed to it. Clients must implement an interface that exposes a setter method that accepts the dependency.

In ASP.NET 5, dependency injection is a first class citizen. While in the previous versions of the framework, DI was partially supported, in ASP.NET 5 it is available throughout the entire stack. A minimalistic DI container is provided out of the box, but you can use your own container (BYOC – Bring Your Own Container support).

The default dependency injection supports following life styles.

Lifestyle Description
Instance A specific instance is given all the time. You are responsible for its initial creation
Transient A new instance is created every time
Singleton A single instance is created and it acts like a singleton
Scoped A single instance is created inside the current scope. It is equivalent to Singleton in the current scope

A popular feature for DI in web applications is to create objects that have a single instance per web request. This means that the objects acts as a singleton inside that request but two distinct requests will have different instances of the objects.

In this post, I am injecting database repository to the controller with scoped life style – runtime will create instance of repository on every web request. Here is the changes required in the Startup.cs.

public void Configure(IApplicationBuilder app)
{
	app.UseErrorPage();
	app.UseServices(services =>
	{
		services.AddMvc();
		services.AddScoped<IUserRepository, UserRepository>();
	});

	app.UseMvc();
}

And in the controller, create a constructor, which accepts IUserRepository parameter, which will be injected by runtime while creating the instance of contolller.

public class HomeController : Controller
{
	private IUserRepository _userRepository;
	public HomeController(IUserRepository userRepository)
	{
		_userRepository = userRepository;
	}
	
	public ActionResult Index()
	{
		return View(_userRepository.Users()); 
	}
}

Here is the IUserRepository interface and its implementation.

public interface IUserRepository
{
	List<User> Users();
}
	
public class UserRepository : IUserRepository
{
	public List<User> Users()
	{
		var listOfUsers = new List<User>();
		for(int i = 0; i< 10; i++)
		{
			listOfUsers.Add(new User(){ Name = "User " + i });
		}
		
		return listOfUsers;
	}
}

public class User
{
	public string Name { get;set; } 
}

You can find more details about Dependency Injection in ASP.NET vNext here

Happy Programming :)