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

New C# 6.0 features

Standard

As part of the Connect(); event, Microsoft introduced VS2015 Preview, which includes C# 6.0 with few more features. (These features are not included in my earlier post What is new in C# 6.0, as I already mentioned these features introduced by Microsoft in the Connect(); event few days back.)

  • nameof operator – nameof operator allows developers to use program elements as text. In MVVM project, you are using property notifications, it is recommended to use strongly typed property notifications, instead of string. Because you are hard coding the property name, if you rename the property, you need to change the string manually. The nameof operator helps you to use the property as the parameter.
    public string FirstName
    {
        get { return _firstName; }
        set
        {
            if (_firstName != value)
            {
                _firstName = value;
                OnPropertyChanged(nameof(FirstName));
            }
        }
    }
    

    Runtime will replace the property with the property name while generating the IL code.

    IL code generated for nameof operator

    IL code generated for nameof operator

  • null conditional dot operator – as the name indicates it for null checking. This helps you to make null checking fade into the background.
    static void PrintBook(Book book)
    {
        var name = book.Name;
        var price = book.Price;
        Console.WriteLine("Name :{0} - Price {1}", name, price);
    }
    

    I have a function like this, which will print the name and price of the book. Please note I am not doing any null check, if the book instance is null, it will throw exception. The null conditional dot operator helps to avoid this validation and processing. If you are invoking a property of null object instance, it will return null for that property as well, it won’t throw null reference exception.

    static void PrintBook(Book book)
    {
        var name = book?.Name;
        var price = book?.Price;
        Console.WriteLine("Name :{0} - Price {1}", name, price);
    }
    

    In case of value types, Visual Studio will treat the type of the variable as nullable, if you use null conditional dot operator.

    null conditional dot operator - with value types

    null conditional dot operator – with value types

  • string interpolation – Another cool feature, which will help you to manage string formatting easy. In the current framework, you need use string.Format function, it little complex, you need to put numeric place holders ({n}) and based on the number you need to set the variables. String Interpolation will help developers to use actual variables as placeholders.
    var message = string.Format("Book Name :{0} Price :{1}", name, price);
    

    Can be re-write like this.

    var message = "Book Name :\{name} Price :\{price}";
    

    It supports IntelliSense for the variable names, also variables can be identified with different color.

    String Interpolation - IntelliSense

    String Interpolation – IntelliSense

You can download VS 2015 Preview from here

Happy Coding :)

Why you shouldn’t believe in your favorite .net decompiler

Standard

Yesterday I posted about explicit interface implementation. I was curious about to know how CLR treats Explicit interface implementation. I looked into the generated IL code using IL DASM, and it was pretty similar to C# code I wrote. So I thought of reverse engineering the assembly. I verified the assembly with five .net decompilers. And only two provided the compilable code. Here is the .Net decompilers I used.

This the code I compiled.

static void Main(string[] args)
{
    ISample sample = new Sample();
    var result = sample.Add(10, 20);
    Console.WriteLine(result);  //Will return 30

    ISample2 sample2 = new Sample();
    var result2 = sample2.Add(10, 20);
    Console.WriteLine(result2);  //Will return 40
}

And here is the code from decompilers.

ILSpy

// ConsoleApplication6.Program
private static void Main(string[] args)
{
	ISample sample = new Sample();
	int value = sample.Add(10, 20);
	Console.WriteLine(value);
	ISample2 sample2 = new Sample();
	int value2 = sample2.Add(10, 20);
	Console.WriteLine(value2);
}

dotPeek

private static void Main(string[] args)
{
    Console.WriteLine(new Sample().Add(10, 20));
    Console.WriteLine(new Sample().Add(10, 20));
}

JustDecompile

private static void Main(string[] args)
{
    Console.WriteLine((new Sample()).Add(10, 20));
    Console.WriteLine((new Sample()).Add(10, 20));
}

.NET CodeReflect

private static void Main(string[] args)
{
    Console.WriteLine(new ConsoleApplication6.Sample().Add(10, 20));
    Console.WriteLine(new ConsoleApplication6.Sample().Add(10, 20));
}

.NET Reflector 8

private static void Main(string[] args)
{
    ISample sample = new Sample();
    Console.WriteLine(sample.Add(10, 20));
    ISample2 sample2 = new Sample();
    Console.WriteLine(sample2.Add(10, 20));
}

If you look into the decompiled code, only ILSpy and .NET Reflector gives compilable code. It doesn’t mean other decompilers are not good, but for this given scenario, all the other three decompilers failed reverse engineer C# code properly.

Happy Programming :)